I need to create a function that generates an exception in certain cases but I need it to generate a certain error using try catch. It uses functions :
let lookup (x,evn) = match listAssoc(x,evn) with
|Some Int v ->Int v
| None -> raise (MLFailure "variable not found")
;;
let arithmetic (x,y,z) = match (x,y,z) with
| (Int a, Int b, Plus)-> Int (a+b)
| (Int a, Int b,Minus) -> Int (a-b)
| (Int a, Int b, Mul)-> Int (a*b)
| (Int a, Int b, Div)-> Int (a/b)
;;
This is the function:
let errorlookup (x,evn) = match listAssoc(x,evn) with
|Some Int v ->Int v
| None -> raise (Nano.MLFailure "variable not found %s" x)
;;
let rec eval (evn,e) = match e with
| Const a -> Int a
| Var x-> (lookup (x,evn) )
| Bin( expr1, Plus, expr2) -> arithmetic(eval(evn,expr1),eval(evn,expr2),Plus)
|Bin( expr1, Minus,expr2) -> arithmetic(eval(evn,expr1),eval(evn,expr2),Minus)
|Bin( expr1, Mul, expr2) -> arithmetic(eval(evn,expr1),eval(evn,expr2),Mul)
| Bin( expr1, Div, expr2) -> arithmetic(eval(evn,expr1),eval(evn,expr2),Div)
;;
I need to make sure that in the Var x case, when lookup result is None I need to print an Exception
eval (evn, Var "p");;
Exception: MLFailure "variable not bound: p".
eval evaluates an expression with a current environment ex.
let evn = [("z1",Int 0);("x",Int 1);("y",Int 2);("z",Int 3);("z1",Int 4)];;
val evn : (string * Nano.value) list =
[("z1", Int 0); ("x", Int 1); ("y", Int 2); ("z", Int 3); ("z1", Int 4)]
I made the types for Bin and Val and Expr but those arent relevant to this.
I need to raise an exception based on the result of lookup but not raise the exception that is in lookup. Someone suggested using try catch but Im not sure how that would work for ocaml and this. this was the hint given by TA
lookup should throw the following exception:
raise (MLFailure "not found")
Whereas eval should throw the following one:
eval (evn, Var "p");;
Exception: MLFailure "variable not bound: p".
It seems that you've to do exception handling here. You can use the
try with | ->
syntax to catch & handle exceptions inside eval.