How can we implement an eval function case for the if-then-else expression in SML? This subject in SML is challenging and new to me.
datatype exp = ...
| Equal of exp * exp
| If of exp * exp * exp;
datatype value = BVal of bool | ...
fun print (Equal(x,y)) = "(" ^print(x)^ " = " ^print(y)^ ")"
| print (If(x,y,z)) = "if " ^print(x)^ "
then " ^print(y)^ " else " ^print(z)
| ...
fun eval (Equal(e1, e2)) ctx =
let
val (CVal x) = eval e1 ctx
val (CVal y) = eval e2 ctx
in
BVal (round x = round y)
end
| ...
How can we implement an eval function case for the if-then-else expression?
CVal
is defined. It looks like it should be a part of datatype value
, but it could also be defined in an area of the code that you have omitted. Please provide a minimal, reproducible example when you post on StackOverflow, since too much guessing can lead to nonsensical answers.eval
function with pattern matching to handle the If
constructor in a similar way as it already supports the Equal
constructor.Here is something that might get you started:
datatype value = BVal of bool | CVal of int (* replacing "..." *)
fun eval (Equal (e1, e2)) ctx =
let
val (CVal x) = eval e1 ctx
val (CVal y) = eval e2 ctx
in
BVal (round x = round y)
end
| eval (If (cond, e1, e2)) =
let
val ... = eval cond ctx
in
...
end
Depending on how you perform the pattern matching, you will want to pick eval e1 ctx
or eval e2 ctx
to be the result. You may want to look into the case-of construct here.