What's the reason of 'let rec' for impure functional language OCaml?

前端 未结 6 1820
梦谈多话
梦谈多话 2021-02-02 06:54

In the book Real World OCaml, the authors put why OCaml uses let rec for defining recursive functions.

OCaml distinguishes between nonrecurs

6条回答
  •  灰色年华
    2021-02-02 07:34

    I am not an expert, but I'll make a guess until the truly knowledgable guys show up. In OCaml there can be side effects that happen during the definition of a function:

    let rec f =
        let () = Printf.printf "hello\n" in
        fun x -> if x <= 0 then 12 else 1 + f (x - 1)
    

    This means that the order of function definitions must be preserved in some sense. Now imagine that two distinct sets of mutually recursive functions are interleaved. It doesn't seem at all easy for the compiler to preserve the order while processing them as two separate mutually recursive sets of definitions.

    The use of `let rec ... and`` means that distinct sets of mutually recursive function definitions can't be interleaved in OCaml as they can in Haskell. Haskell doesn't have side effects (in some sense), so definitions can be freely reordered.

提交回复
热议问题