Advertisement
Guest User

Untitled

a guest
May 3rd, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. type unop =
  2. | Negate
  3. ;;
  4.  
  5. type binop =
  6. | Plus
  7. | Minus
  8. | Times
  9. | Equals
  10. | LessThan
  11. ;;
  12.  
  13. type expr =
  14. | Var of varid (* variables *)
  15. | Num of int (* integers *)
  16. | Bool of bool (* booleans *)
  17. | Unop of unop * expr (* unary operators *)
  18. | Binop of binop * expr * expr (* binary operators *)
  19. | Conditional of expr * expr * expr (* if then else *)
  20. | Fun of varid * expr (* function definitions *)
  21. | Let of varid * expr * expr (* local naming *)
  22. | Letrec of varid * expr * expr (* recursive local naming *)
  23. | Raise (* exceptions *)
  24. | Unassigned (* (temporarily) unassigned *)
  25. | App of expr * expr (* function applications *)
  26. and varid = string ;;
  27.  
  28. module SS = Set.Make (struct
  29. type t = varid
  30. let compare = String.compare
  31. end ) ;;
  32.  
  33. type varidset = SS.t ;;
  34.  
  35. let same_vars = SS.equal;;
  36.  
  37. let vars_of_list = SS.of_list ;;
  38.  
  39. let rec free_vars (exp : expr) : varidset =
  40. match exp with
  41. | Num _ | Bool _ | Raise | Unassigned -> SS.empty
  42. | Var v -> SS.singleton v
  43. | Unop (_, e) -> free_vars e
  44. | Binop (_, e1, e2) | App (e1, e2) ->
  45. SS.union (free_vars e1) (free_vars e2)
  46. | Conditional (e1, e2, e3) ->
  47. let u1 = SS.union (free_vars e1) (free_vars e2) in
  48. SS.union u1 (free_vars e3)
  49. | Fun (v, e) -> SS.remove v (free_vars e)
  50. | Let (v, e1, e2) ->
  51. let u1 = SS.union (free_vars e2) (free_vars e1) in
  52. SS.remove v u1
  53. | Letrec (v, e1, e2) -> SS.empty ;;
  54.  
  55. assert (free_vars (Num(3)) = SS.empty) ;;
  56. assert (not (SS.equal (free_vars (Fun(x, y))) (free_vars (Fun(x, x))))) ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement