2

I have a problem and I don't really know how to implement it in OZ: Suppose that you are given an arithmetic expression described by a tree constructed from tuples as follows:

  1. An integer is described by a tuple int(N), where N is an integer.
  2. An addition is described by a tuple add(X Y), where both X and Y are arithmetic expressions.
  3. A multiplication is described by a tuple mul(X Y), where both X and Y are arithmetic expressions.

Implement a function Eval that takes an arithmetic expression and returns its value.

For example, add(int(1) mul(int(3) int(4))) is an arithmetic expression and its evaluation returns 13.

Raduan Santos
  • 1,023
  • 1
  • 21
  • 45
Alma A
  • 138
  • 10

1 Answers1

0

It is a bit sad that you didn't show your attempts so far.

Anyway. Typically, when dealing with such problems, you think in terms of recursion. And pattern matching is a good way to analyze the expression.

For instance, if you capable to evaluate int(4) then it is pretty evident how to evaluate add(int(4) int(4)) with a simple recursion:

declare
proc {Eval Exp Res}
   case Exp
   of int(N) then Res = N
   [] add(X Y) then
      local R1 R2 in
         {Eval X R1}
         {Eval Y R2}
         Res = R1 + R2
      end
   end
end

Now you can expand it with mul or any other expression.

vonaka
  • 913
  • 1
  • 11
  • 23