mirror of
https://github.com/ProgramSnail/Lama.git
synced 2025-12-08 07:48:47 +00:00
Restored the implementation
This commit is contained in:
parent
2c35249e83
commit
47ea4b27c6
2 changed files with 31 additions and 7 deletions
|
|
@ -33,8 +33,8 @@ let y = !"y"
|
|||
let z = !"z"
|
||||
let t = !"t"
|
||||
|
||||
(* Voila; comment this out before submitting the solution *)
|
||||
(* Voila; comment this out before submitting the solution
|
||||
let _ =
|
||||
List.iter (fun e -> Printf.printf "eval s (%s) = %d\n" (show(expr) e) (eval s e)) [x+y*z- !?3; t-z+y && x]
|
||||
|
||||
*)
|
||||
|
||||
|
|
|
|||
30
src/Expr.ml
30
src/Expr.ml
|
|
@ -1,4 +1,3 @@
|
|||
!!!
|
||||
(* Simple expressions: syntax and semantics *)
|
||||
|
||||
(* Opening a library for generic programming (https://github.com/dboulytchev/GT).
|
||||
|
|
@ -35,13 +34,14 @@ let update x v s = fun y -> if x = y then v else s y
|
|||
(* An example of a non-trivial state: *)
|
||||
let s = update "x" 1 @@ update "y" 2 @@ update "z" 3 @@ update "t" 4 empty
|
||||
|
||||
(* Some testing; comment this definition out when submitting the solution. *)
|
||||
(* Some testing; comment this definition out when submitting the solution.
|
||||
let _ =
|
||||
List.iter
|
||||
(fun x ->
|
||||
try Printf.printf "%s=%d\n" x @@ s x
|
||||
with Failure s -> Printf.printf "%s\n" s
|
||||
) ["x"; "a"; "y"; "z"; "t"; "b"]
|
||||
*)
|
||||
|
||||
(* Expression evaluator
|
||||
|
||||
|
|
@ -50,5 +50,29 @@ let _ =
|
|||
Takes a state and an expression, andreturns the value of the expression in
|
||||
the given state.
|
||||
*)
|
||||
let eval = failwith "Not implemented yet"
|
||||
let rec eval st expr =
|
||||
let to_func op =
|
||||
let bti = function true -> 1 | _ -> 0 in
|
||||
let itb b = b <> 0 in
|
||||
let (|>) f g = fun x y -> f (g x y) in
|
||||
match op with
|
||||
| "+" -> (+)
|
||||
| "-" -> (-)
|
||||
| "*" -> ( * )
|
||||
| "/" -> (/)
|
||||
| "%" -> (mod)
|
||||
| "<" -> bti |> (< )
|
||||
| "<=" -> bti |> (<=)
|
||||
| ">" -> bti |> (> )
|
||||
| ">=" -> bti |> (>=)
|
||||
| "==" -> bti |> (= )
|
||||
| "!=" -> bti |> (<>)
|
||||
| "&&" -> fun x y -> bti (itb x && itb y)
|
||||
| "!!" -> fun x y -> bti (itb x || itb y)
|
||||
| _ -> failwith (Printf.sprintf "Unknown binary operator %s" op)
|
||||
in
|
||||
match expr with
|
||||
| Const n -> n
|
||||
| Var x -> st x
|
||||
| Binop (op, x, y) -> to_func op (eval st x) (eval st y)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue