ocaml: phase 5.1 memo_fib.ml baseline (16/16 pass)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Memoized fibonacci using Hashtbl.find_opt + Hashtbl.add. fib(25) = 75025. Demonstrates mutable Hashtbl through the OCaml stdlib API in real recursive code.
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
"factorial.ml": 3628800,
|
||||
"fizzbuzz.ml": 57,
|
||||
"list_ops.ml": 30,
|
||||
"memo_fib.ml": 75025,
|
||||
"module_use.ml": 3,
|
||||
"mutable_record.ml": 10,
|
||||
"option_match.ml": 5,
|
||||
|
||||
15
lib/ocaml/baseline/memo_fib.ml
Normal file
15
lib/ocaml/baseline/memo_fib.ml
Normal file
@@ -0,0 +1,15 @@
|
||||
(* Baseline: memoized fibonacci using Hashtbl *)
|
||||
let cache = Hashtbl.create 16 ;;
|
||||
|
||||
let rec fib n =
|
||||
if n < 2 then n
|
||||
else
|
||||
match Hashtbl.find_opt cache n with
|
||||
| Some v -> v
|
||||
| None ->
|
||||
let v = fib (n - 1) + fib (n - 2) in
|
||||
Hashtbl.add cache n v ;
|
||||
v
|
||||
;;
|
||||
|
||||
fib 25
|
||||
Reference in New Issue
Block a user