Restored the implementation

This commit is contained in:
Dmitry Boulytchev 2018-02-14 16:07:03 +03:00
parent 2c35249e83
commit 47ea4b27c6
2 changed files with 31 additions and 7 deletions

View file

@ -33,8 +33,8 @@ let y = !"y"
let z = !"z" let z = !"z"
let t = !"t" let t = !"t"
(* Voila; comment this out before submitting the solution *) (* Voila; comment this out before submitting the solution
let _ = 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] 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]
*)

View file

@ -1,4 +1,3 @@
!!!
(* Simple expressions: syntax and semantics *) (* Simple expressions: syntax and semantics *)
(* Opening a library for generic programming (https://github.com/dboulytchev/GT). (* Opening a library for generic programming (https://github.com/dboulytchev/GT).
@ -35,20 +34,45 @@ let update x v s = fun y -> if x = y then v else s y
(* An example of a non-trivial state: *) (* An example of a non-trivial state: *)
let s = update "x" 1 @@ update "y" 2 @@ update "z" 3 @@ update "t" 4 empty 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 _ = let _ =
List.iter List.iter
(fun x -> (fun x ->
try Printf.printf "%s=%d\n" x @@ s x try Printf.printf "%s=%d\n" x @@ s x
with Failure s -> Printf.printf "%s\n" s with Failure s -> Printf.printf "%s\n" s
) ["x"; "a"; "y"; "z"; "t"; "b"] ) ["x"; "a"; "y"; "z"; "t"; "b"]
*)
(* Expression evaluator (* Expression evaluator
val eval : state -> expr -> int val eval : state -> expr -> int
Takes a state and an expression, andreturns the value of the expression in Takes a state and an expression, andreturns the value of the expression in
the given state. 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)