Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.30 KB | None | 0 0
  1. type aExp =          (* arithmetical expressions *)
  2.     | N of int           (* numbers *)
  3.     | V of string        (* variables *)
  4.     | Add of aExp * aExp (* addition *)
  5.     | Mul of aExp * aExp (* multiplication *)
  6.     | Sub of aExp * aExp (* subtraction *);;
  7.  
  8.     let unop  f a s   = f (a s);;
  9.     let binop f a b s = f (a s) (b s);;
  10.  
  11.     let rec A =
  12.         function
  13.         | N n          -> fun _ -> n
  14.         | V x          -> Map.find x
  15.         | Add (a1, a2) -> binop ( + ) (A a1) (A a2)
  16.         | Mul (a1, a2) -> binop ( * ) (A a1) (A a2)
  17.         | Sub (a1, a2) -> binop ( - ) (A a1) (A a2);;
  18.  
  19.     type bExp =          (* boolean expressions *)
  20.     | TT                 (* true *)
  21.     | FF                 (* false *)
  22.     | Eq of aExp * aExp  (* numeric equality *)
  23.     | Lt of aExp * aExp  (* numeric less than *)
  24.     | Neg of bExp        (* boolean not *)
  25.     | Con of bExp * bExp (* boolean conjunction *);;
  26.  
  27.     (* TODO: Write a function B : bExp -> state -> bool
  28.              to evaluate boolean expressions (note that you will need to refer to A) *)
  29.  
  30.  
  31.     //let rec B _ = failwith "Not implementd"
  32.     let rec B (xp:bExp) state =
  33.         match xp with
  34.         | TT -> true
  35.         | FF -> false
  36.         | Eq(a1,a2) -> (A a1 state) = (A a2 state)
  37.         | Lt(a1,a2) -> (A a1 state) < (A a2 state)
  38.         | Neg(b) -> not (B b state)
  39.         | Con(b1, b2) -> (B b1 state) && (B b2 state);;
  40.        
  41.  
  42.  
  43.  
  44.  
  45.     type stm =                (* statements *)
  46.     | Ass of string * aExp    (* variable assignment *)
  47.     | Skip                    (* nop *)
  48.     | Seq of stm * stm        (* sequential composition *)
  49.     | ITE of bExp * stm * stm (* if-then-else statement *)
  50.     | While of bExp * stm     (* while statement *);;
  51.  
  52.     let update = Map.add;;
  53.  
  54.     (* TODO: Write I : stm -> state -> state.
  55.              You can rewrite the skeleton if you want, but the signature must be the same *)
  56.  
  57.  
  58.     let rec I stm state =
  59.       match stm with
  60.       | Ass (x,a)         -> update x (A a state) state(* use update *)
  61.       | Skip              -> state
  62.       | Seq (stm1, stm2)  -> I stm1 state |> I stm2
  63.       | ITE (b,stm1,stm2) -> if (B b state ) then (I stm1 state) else (I stm2 state)
  64.       | While (b, stm)    -> if B b state then I (Seq(stm,While(b,stm))) state else state
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement