add memo wrapper for recursive functions

This commit is contained in:
ryan 2023-11-20 14:10:29 -08:00
parent 421616a282
commit a652ec69da

View File

@ -10,6 +10,40 @@ let lines_of_input day =
IO.(with_in path read_lines_l)
;;
(** [f] in [memo f] should be a function that makes recursive calls
via the memoized function passed as its first argument. ie:
{[
let fib_m =
memo (fun self x ->
match x with
| 0 | 1 -> 1
| x -> self (x - 1) + self (x - 2))
;;
]} *)
let memo f =
let open Hashtbl in
let cache = create 1000 in
let rec f_mem k =
try find cache k with
| Not_found ->
let v = f f_mem k in
add cache k v;
v
in
f_mem
;;
let%expect_test "fib memoized" =
let fib_m =
memo (fun fib_m x ->
match x with
| 0 | 1 -> 1
| x -> fib_m (x - 1) + fib_m (x - 2))
in
Printf.printf "%i\n" @@ fib_m 100;
[%expect {| 1298777728820984005 |}]
;;
module Parse = struct
include Angstrom