how to call function with dynamic name in Daml?

131 Views Asked by At

the choice call have few function to required to be called based on the values which we passed from list.

For Example:

Choice Call: update X
let list = [FunctionX,FunctionZ,FunctionY]
list.forEach (FunctionName =>
  FunctionName  parameter 
)
function 1 :
X:FunctionX parameter  = X
function 2:
Z:FunctionZ parameter  = Z
function3 :
Y:FunctionY parameter  = Y

here in this choice expectation is the call function X and function Z how we can achieve this

2

There are 2 best solutions below

0
Gary Verhaegen On BEST ANSWER

I'm not entirely sure what you're after here, but this may be helpful:

module Main where

import Daml.Script
import qualified DA.Text

data Function = Reverse | Length | Dup
  deriving (Eq, Show)
data Result = ResultInt Int | ResultText Text
  deriving (Eq, Show)

execFn: Text -> Function -> Result
execFn arg = \case
  Reverse -> ResultText (DA.Text.reverse arg)
  Length -> ResultInt (DA.Text.length arg)
  Dup -> ResultText (arg <> arg)

template ChooseYourFunctions
  with
    owner: Party
    argument: Text
  where
    signatory owner
    controller owner can
      RunFunctions: [Result]
        with
          functions: [Function]
        do
          return $ map (execFn argument) functions
           

setup : Script ()
setup = script do
  alice <- allocatePartyWithHint "Alice" (PartyIdHint "Alice")

  exec <- submit alice do
    createCmd ChooseYourFunctions with
      owner = alice
      argument = "hello"
  
  result <- submit alice do
    exerciseCmd exec RunFunctions with functions = [Reverse, Length, Reverse, Reverse, Dup]

  debug result

  return ()

This will print out the following trace (from the debug call):

[ResultText "olleh",ResultInt 5,ResultText "olleh",ResultText "olleh",ResultText "hellohello"]

where you can see that we're calling the list of functions supplied.

If you want more flexibility in defining the functions on a per-call basis, you may want to have a look at these two threads on the Daml forum.

0
stefanobaghino On

The simplest solution is probably to just add a parameter to the choice and make it change its behavior based on the input.