summaryrefslogtreecommitdiff
path: root/ocaml-binary-annot/camlp4/examples/syb_fold.ml
blob: 3441c6b61c4d1fe0b986b44ea29f4b9573c3f989 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
type variable = string
 and term =
  | Var   of variable
  | Lam   of variable * term
  | App   of term * term
  | Const of constant
 and constant =
  | CInt    of int
  | CString of string
;;

class fold = Camlp4Filters.GenerateFold.generated;;
(* class fold = Camlp4FoldGenerator.generated;; *)

module VarSet = Set.Make(String);;

(* Compute free variables with the fold class *)
let free_variables_v1 =
  let o =
    object (self)
      inherit fold as super
      val fv = VarSet.empty
      method fv = fv
      method empty_fv = {< fv = VarSet.empty >}
      method term t =
        match t with
        | Var(v) -> {< fv = VarSet.add v fv >}
        | Lam(v, t) ->
            let fv1 = VarSet.remove v (self#empty_fv#term t)#fv in
            {< fv = VarSet.union fv fv1 >}
        | _ -> super#term t
    end
  in fun t -> VarSet.elements (o#term t)#fv
;;

(* Let's try to abstract that a little *)

let fold_term f t init =
  let o =
    object (self)
      inherit fold as super
      val acc = init
      method get = acc
      method reset = {< acc = init >}
      method term t =
        {< acc = f t acc (fun t -> (self#reset#term t)#get)
                         (fun t -> (super#term t)#get) >}
    end
  in
  (o#term t)#get
;;

(* A nicer version of free_variables *)
let free_variables_v2 t =
  VarSet.elements begin
    fold_term begin fun t fv self next ->
      match t with
      | Var(v)    -> VarSet.add v fv
      | Lam(v, t) -> VarSet.union fv (VarSet.remove v (self t))
      | _         -> next t
    end t VarSet.empty
  end
;;

let term1 =
  App(
    App(Var"x1",
      Lam("x",
        App(Var"x", App(Var"y", (Lam("y", Lam("z", (App(Var"y", App(Var"x4",Var"z")))))))))),
    Var"x3")

;;

let fv1 = free_variables_v1 term1;;
let fv2 = free_variables_v2 term1;;

(* Low cost syntax *)
let ( ^-> ) v t = Lam(v, t)
let ( @ ) t1 t2 = App(t1, t2)
let ( ! ) s = Var s

let term2 =
  !"x1" @
  ("x" ^-> !"x" @ !"y" @ ("y" ^-> ("z" ^-> !"y" @ !"x4" @ !"z"))) @
  !"x3"

;;

let fv1' = free_variables_v1 term2;;
let fv2' = free_variables_v2 term2;;