Guest User

Untitled

a guest
May 25th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. (* Opening GT *)
  2. open GT
  3.  
  4. (* Some useful idioms: identity, fixpoint *)
  5. let id x = x
  6. let rec fix f x = f (fix f) x;;
  7.  
  8. (* The first example: decorated expressions *)
  9. @type 'expr a_expr =
  10. | Const of int
  11. | Add of 'expr * 'expr with show, gmap, foldl
  12.  
  13. (* Must replace with @type expr = expr a_expr with ... *)
  14. type expr = expr a_expr
  15. let show_expr = fix (fun s e -> show(a_expr) s e)
  16.  
  17. (* Must replace with @type 'a decorated = ('a decorated a_expr * 'a) with ...*)
  18. type 'a decorated = ('a decorated a_expr * 'a)
  19. let show_decorated sa = fix (fun s (e, a) -> Printf.sprintf "(%s, %s)"(show(a_expr) s e) (sa a))
  20.  
  21. (* Simple --- one-level --- decoration *)
  22. module Simple =
  23. struct
  24.  
  25. (* Decoration *)
  26. let decorate : (unit -> 'a) -> expr -> 'a decorated = fun fd e ->
  27. fix (fun s e -> let d = fd () in gmap(a_expr) s e, d) e
  28.  
  29. (* Stripping *)
  30. let strip : 'a decorated -> expr = fun e ->
  31. fix (fun s e -> gmap(a_expr) s (fst e)) e
  32.  
  33. (* Testing *)
  34. let _ =
  35. let e = Add (Add (Const 1, Const 2), Const 3) in
  36. Printf.printf "%s\n" (show_expr e);
  37. let e = decorate (let i = ref 0 in fun () -> let n = !i in incr i; n) e in
  38. Printf.printf "%s\n" (show_decorated string_of_int e);
  39. Printf.printf "%s\n" (show_expr @@ strip e)
  40.  
  41. end
  42.  
  43. (* Advanced --- multilayer decorations *)
  44. module Advanced =
  45. struct
  46.  
  47. (* Lifting --- attaching unit decoration *)
  48. let lift = Simple.decorate (fun _ -> ())
  49.  
  50. (* Redecorate *)
  51. let redecorate : ('a -> 'b) -> 'a decorated -> 'b decorated = fun ab e ->
  52. fix (fun s (e, a) -> gmap(a_expr) s e, ab a) e
  53.  
  54. (* Testing *)
  55. let _ =
  56. let e = Add (Add (Const 1, Const 2), Const 3) in
  57. Printf.printf "%s\n" (show_expr e);
  58. let e = lift e in
  59. Printf.printf "%s\n" (show_decorated (fun _ -> "()") e);
  60. let e = redecorate (let i = ref 0 in fun () -> let n = !i in incr i; n) e in
  61. Printf.printf "%s\n" (show_decorated (show int) e);
  62. let e = redecorate (let i = ref 0 in fun a -> let n = !i in incr i; (a, n)) e in
  63. Printf.printf "%s\n" (show_decorated (show(pair) (show int) (show int)) e);
  64. let e = redecorate snd e in
  65. Printf.printf "%s\n" (show_decorated (show int) e)
  66.  
  67. end
  68.  
  69. (* Custom --- no use of gmap *)
  70. module Custom =
  71. struct
  72.  
  73. (* OO transformer for redecorate *)
  74. class virtual ['a, 'b] decorator =
  75. object ('self)
  76. inherit [] @pair
  77. end
  78.  
  79. end
Add Comment
Please, Sign In to add comment