Memoization in OCaml?

后端 未结 2 865
南方客
南方客 2021-01-01 00:15

It is possible to improve \"raw\" Fibonacci recursive procedure

Fib[n_] := If[n < 2, n, Fib[n - 1] + Fib[n - 2]]

with

         


        
2条回答
  •  隐瞒了意图╮
    2021-01-01 01:09

    You pretty much do what the mathematica version does but manually:

    let rec fib = 
      let cache = Hashtbl.create 10 in
      begin fun n ->
        try Hashtbl.find cache n
        with Not_found -> begin
          if n < 2 then n
          else 
            let f = fib (n-1) + fib (n-2) in
            Hashtbl.add cache n f; f
        end
      end
    

    Here I choose a hashtable to store already computed results instead of recomputing them. Note that you should still beware of integer overflow since we are using a normal and not a big int.

提交回复
热议问题