I am trying to create a function that takes an expression and evaluates it. Expressions can contain the following operations:
int(N)
, where N
is an integer.add(X Y)
, where both X
and Y
are arithmetic expressions.mul(X Y)
, where both X
and Y
are arithmetic
expressions.var(A)
, where A
is an atom giving the variable nameenv(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
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.