I am trying to create a function that takes an expression and evaluates it. Expressions can contain the following operations:
- Integers - described by a tuple
int(N)
, whereN
is an integer. - Addition - described by a tuple
add(X Y)
, where bothX
andY
are arithmetic expressions. - Multiplication - described by a tuple
mul(X Y)
, where bothX
andY
are arithmetic expressions. - Variables - described by a tuple
var(A)
, whereA
is an atom giving the variable name - An environment - described by a record
env(a:5 b:5)
, wherea
andb
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.
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.