Expression Evaluation Oz/Mozart

185 views Asked by At

I am trying to create a function that takes an expression and evaluates it. Expressions can contain the following operations:

  1. Integers - described by a tuple int(N), where N is an integer.
  2. Addition - described by a tuple add(X Y), where both X and Y are arithmetic expressions.
  3. Multiplication - described by a tuple mul(X Y), where both X and Y are arithmetic expressions.
  4. Variables - described by a tuple var(A), where A is an atom giving the variable name
  5. An environment - described by a record env(a:5 b:5), where a and b are variables with values of 5.

For example: {Eval add(var(a) mul(int(3) var(b))) env(a:5 b:5)}. Which should evaluate to 20.

So far, I have implemented integers, addition, and multiplication. But I'm not really sure where to start for the variables and the environment.

My current code:

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

There are 1 answers

0
Timmy Chan On BEST ANSWER

You need to get the value of the variable from the environment. This can be done by passing the env() as parameter to the Eval function, in order to access it from inside.

I have solved it for you. It should be easy to understand.

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

As a side note, this is practically how a common interpreter runs a programming script. By using statement stack and environment to store variable mappings.