the1337sauce
the1337sauce

Reputation: 549

How do I execute some code in DAML N times?

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

Answers (1)

Recurse
Recurse

Reputation: 3585

TLDR

To apply a ledger operation N times the easiest way is to use the replicateA function from DA.Action.

Example

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

Discussion

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 the Applicative typeclass (api or interface). Its first parameter is an Int Its second is an 'effect' of the type m that provides a value of type a 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

Related Questions