Advertisement
Guest User

Untitled

a guest
Aug 14th, 2015
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.69 KB | None | 0 0
  1. module Memo : sig
  2.   type 'a endo
  3.   val id : 'a endo
  4.   val (++) : 'a endo -> 'a endo -> 'a endo
  5.  
  6.   val lift : 'b endo -> ('a -> 'b) endo
  7.   val memo : ('a -> 'b) endo
  8.  
  9.   val apply : 'a endo -> 'a -> 'a
  10. end = struct
  11.   type 'a endo = 'a -> 'a
  12.   let id x = x
  13.   let (++) f g x = f (g x)
  14.   let lift m f x = m (f x)
  15.  
  16.   let memo f =
  17.     let cache = Hashtbl.create 10 in
  18.     fun x ->
  19.       try Hashtbl.find cache x
  20.       with Not_found ->
  21.         let y = f x in
  22.         Hashtbl.add cache x y;
  23.         y
  24.  
  25.   let apply m x = m x
  26. end
  27.  
  28. let z = Memo.id
  29. let s n = Memo.(memo ++ lift n)
  30.  
  31. let test x y z = Printf.printf "%d %d %d\n" x y z; x + y + z
  32.  
  33. let t = Memo.(apply (s (s (s z))) test)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement