How to memoize recursive functions?

后端 未结 2 1504
闹比i
闹比i 2021-01-02 06:09

Consider a recursive function, say the Euclid algorithm defined by:

let rec gcd a b =
  let (q, r) = (a / b, a mod b) in
  if r = 0 then b else gcd b r
         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 06:50

    # let memoize f =
        let table = Hashtbl.Poly.create () in
        (fun x ->
          match Hashtbl.find table x with
          | Some y -> y
          | None ->
            let y = f x in
            Hashtbl.add_exn table ~key:x ~data:y;
            y
        );;
    val memoize : ('a -> 'b) -> 'a -> 'b = 
    
    
    # let memo_rec f_norec x =
        let fref = ref (fun _ -> assert false) in
        let f = memoize (fun x -> f_norec !fref x) in
        fref := f;
        f x
      ;;
    val memo_rec : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = 
    

    You should read the section here: https://realworldocaml.org/v1/en/html/imperative-programming-1.html#memoization-and-dynamic-programming in the book Real World OCaml.

    It will help you truly understand how memo is working.

提交回复
热议问题