From 47ea4b27c60e271b7ed1058957c88eb0363ba5f7 Mon Sep 17 00:00:00 2001 From: Dmitry Boulytchev Date: Wed, 14 Feb 2018 16:07:03 +0300 Subject: [PATCH] Restored the implementation --- src/Embedding.ml | 4 ++-- src/Expr.ml | 34 +++++++++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/Embedding.ml b/src/Embedding.ml index 5946027df..d52fbdf25 100644 --- a/src/Embedding.ml +++ b/src/Embedding.ml @@ -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] - +*) diff --git a/src/Expr.ml b/src/Expr.ml index c694a2a11..7292c06f0 100644 --- a/src/Expr.ml +++ b/src/Expr.ml @@ -1,4 +1,3 @@ -!!! (* Simple expressions: syntax and semantics *) (* 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: *) 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 val eval : state -> expr -> int 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)