Limitations of let rec in OCaml

前端 未结 3 897
攒了一身酷
攒了一身酷 2021-02-19 22:10

I\'m studying OCaml these days and came across this:

OCaml has limits on what it can put on the righthand side of a let rec. Like this one

let memo_rec f         


        
3条回答
  •  梦谈多话
    2021-02-19 22:35

    You can use tying-the-knot techniques to define memoizing fixpoints. See for example those two equivalent definitions:

    let fix_memo f =
      let rec g = {contents = fixpoint}
      and fixpoint x = f !g x in
      g := memoize !g;
      !g
    
    let fix_memo f =
      let g = ref (fun _ -> assert false) in
      g := memoize (fun x -> f !g x);
      !g
    

    Or using lazy as reminded by Alain:

    let fix_memo f =
      let rec fix = lazy (memoize (fun x -> f (Lazy.force fix) x)) in
      Lazy.force fix
    

提交回复
热议问题