Guest User

Untitled

a guest
Jul 31st, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.81 KB | None | 0 0
  1.  
  2. type terme =
  3.   | Var of string
  4.   | Lambda of string * terme
  5.   | Application of terme * terme
  6.   | Nothing
  7.   | Multiplication of terme * terme
  8.   | Addition of terme * terme
  9.   | Number of int
  10.   | Boolean of bool
  11.   | If of terme * terme * terme
  12. ;;
  13.  
  14. let t_true = Boolean(true) and
  15.     t_false = Boolean(false) and
  16.     t_three = Number(3) and
  17.     identity = Lambda("x", Var("x")) and
  18.     multiplication = Lambda("x", Lambda("y", Multiplication(Var("x"), Var("y"))))  
  19. ;;
  20.  
  21.  
  22. let get_val = function
  23.     Var s -> s
  24.   | _ -> failwith "Bad Type in get_val"
  25. ;;
  26.  
  27.  
  28. let identity = Lambda("x", Var("x"));;
  29. let three = Application(identity, Number(3));;
  30.  
  31. let lookup env k =
  32.   snd  (List.find (fun x-> ((fst x)=k)) env)
  33. ;;
  34.  
  35. let rec remplace l t i = match l with
  36.     Lambda(v, b) -> Lambda(v, (remplace b t i))
  37.   | Var(x) ->
  38.       if x = t then
  39.     i
  40.       else
  41.     l
  42.   | _ -> failwith "test"
  43. ;;
  44.  
  45. remplace (Lambda ("x", Var("x"))) "x" (Number(3))
  46. ;;
  47.                          
  48. let rec evaluate terme env = match terme with
  49.   | Application(l, t) ->(
  50.       let l = evaluate l env in
  51.       let t = evaluate t env in
  52.     match l with
  53.         Lambda(v, b) -> evaluate b ((v, t)::env)    
  54.     )      
  55.   | Var(v) ->
  56.       begin
  57.     try
  58.       lookup env v
  59.     with Not_found -> terme
  60.       end
  61.   | Multiplication(t1, t2) ->
  62.       begin
  63.     let t1v = evaluate t1 env and
  64.         t2v = evaluate t2 env in
  65.       match (t1v, t2v) with
  66.         | (Number(x), Number(y)) -> Number(x*y)
  67.        
  68.         | _ -> Multiplication(t1v, t2v)
  69.       end    
  70.   | Lambda(v, b) -> Lambda(v, (evaluate b env))
  71.   | _ -> terme
  72. ;;
  73.  
  74.  
  75. evaluate (Application(identity, Number(42))) [];; (* -> 42 *)
  76.  
  77. evaluate three [];;
  78.  
  79. evaluate (Application(Lambda("x",
  80.                 (Application(Lambda("y",
  81.                         Multiplication(Var("x"), Var("y"))),
  82.                      Number(3)))),
  83.              Number(2))) [];;
  84.  
  85.  
  86. evaluate (Application (Application (multiplication, Number(2)), Number(3))) [];;
Add Comment
Please, Sign In to add comment