add memo wrapper for recursive functions
This commit is contained in:
parent
421616a282
commit
a652ec69da
34
src/utils.ml
34
src/utils.ml
|
|
@ -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
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user