简体   繁体   中英

Pattern matching with a record in Oz

i'm having some trouble wrapping my head on how to utilize the elements of a record in Oz with pattern matching. Below is my code

declare
fun {Eval X E}
case X
of int(N) then N
   [] var(X) then E.X
   [] mul(X Y) then X*Y
   [] add(X Y) then X+Y
   end
   end
end

{Eval add(var(a) mul(int(3) var(b))) env(a:2 b:4)}

This is the input I have to utilize, the var(a) is supposed to return 2, (and var(b) return 4) from the env record in the input, I just cannot figure it out for anything.

In your code, you need to call Eval recursively whenever you haven't reached a number or var. Try this instead:

declare
fun {Eval Node Env}
   if {IsNumber Node} then Node
   else
      case Node
      of var(X) then Env.X
      [] mul(X Y) then {Eval X Env} * {Eval Y Env}
      [] add(X Y) then {Eval X Env} + {Eval Y Env}
      end
   end
end

Additionally, Oz requires the return value of functions to be bound to a variable, so try something like:

declare
Ans = {Eval add(var(a) mul(3 var(b))) env(a:2 b:4)}

You can then view Ans with the Browser to verify the code is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM