Reputation: 549
Say I have a choice that takes an integer that represents a count and I want to create a contract that number of times, i.e. execute some block of code that many times.
In Ruby for example this might look like this:
n.times do
#run some code here
end
How do I achieve this in DAML?
Upvotes: 1
Views: 98
Reputation: 3585
To apply a ledger operation N
times the easiest way is to use the replicateA
function from DA.Action
.
daml 1.2
module ReplicateDaml
where
import DA.Action
template Demo
with
sig: Party
total: Int
where
signatory sig
testReplicate = scenario do
p <- getParty "party"
let
total = 10
p `submit` replicateA total $ create Demo with sig=p; total
The type signature for replicateA
is:
-- | `replicateA n act` performs the action n times, gathering the results.
replicateA : (Applicative m) => Int -> m a -> m [a]
You can read this as:
This function supports any type
m
that has an instance (implementation) for theApplicative
typeclass (api or interface). Its first parameter is anInt
Its second is an 'effect' of the typem
that provides a value of typea
It returns the result of repeating the effect N times, collecting the results in a list
The create
you describe is of type: Update (ContractId a)
; and as Update
instantiates (has an implementation for) the Applicative
typeclass you can use any function that works on Applicative
's on Update
's — which naturally includes replicateA
.
When used this way, substitute Update
for m
and (ContractId t)
for a
in the type signature, so:
replicateA : Int -> Update (ContractId t) -> Update [ContractId t]
Upvotes: 2