module Closure: sig val memo_with : ('a -> 'b) -> 'a -> 'b val memo_rec: (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b val memo_rec_with: ('a -> ('b -> 'c) -> 'b -> 'c) -> 'a -> 'b -> 'c end = struct let memo_rec f = let h = Hashtbl.create 10000 in let rec g x = let try_find = Hashtbl.find_opt h x in match try_find with | Some (x) -> x | None -> let y = f g x in Hashtbl.add h x y ; y in g;; let memo_with f arr = f arr;; (* Usage: let rec sushi_as_fib sushi_array self x = if x < 1 then 0 else max ((self (x - 2)) + sushi_array.(x - 1)) (self (x - 1));; => (array -> self -> 'a) = f: 'a -> 'b let sushi = Closure.memo_rec_with sushi_as_fib sarray;; *) let memo_rec_with f farr = memo_rec (memo_with f farr);; end let rec dice_as_fib self x = if x < 2 then 1 else (self (x - 1)) + self (x - 2);; let sugoroku = Closure.memo_rec dice_as_fib;; let () = read_int () |> sugoroku |> print_int; print_newline ();;