Functions in data structure

s/impossible/cumbersome/

module Main where

import Daml.Script

data Formula =
    Arg1
  | Arg2
  | Plus with arg1: Formula, arg2: Formula
  | Minus with arg1: Formula, arg2: Formula
  | Times with arg1: Formula, arg2: Formula
  deriving (Eq, Show)

eval: Formula -> Int -> Int -> Int
eval f a b = case f of
  Arg1 -> a
  Arg2 -> b
  Plus f1 f2 -> (eval f1 a b) + (eval f2 a b)
  Minus f1 f2 -> (eval f1 a b) - (eval f2 a b)
  Times f1 f2 -> (eval f1 a b) * (eval f2 a b)

template Calculator
  with
    owner: Party
    formula: Formula
    obs: Party
  where
    signatory owner
    observer obs
    nonconsuming choice Eval: Int
      with a : Int, b: Int
      controller obs
      do
        return $ eval formula a b

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

  c1 <- submit bob do createCmd Calculator with owner = bob, obs = alice, formula = (Plus Arg1 Arg2)
  c2 <- submit bob do createCmd Calculator with owner = bob, obs = alice, formula = (Minus (Times Arg1 Arg1) (Times Arg2 Arg2))

  res1 <- submit alice do exerciseCmd c1 (Eval 3 4)
  res2 <- submit alice do exerciseCmd c2 (Eval 3 4)

  assert (res1 == 7)
  assert (res2 == -7)

  return ()
1 Like