Why are functions in Ocaml/F# not recursive by default?

后端 未结 6 429
日久生厌
日久生厌 2020-11-29 18:36

Why is it that functions in F# and Ocaml (and possibly other languages) are not by default recursive?

In other words, why did the language designers decide it was a

6条回答
  •  执笔经年
    2020-11-29 19:37

    Some guesses:

    • let is not only used to bind functions, but also other regular values. Most forms of values are not allowed to be recursive. Certain forms of recursive values are allowed (e.g. functions, lazy expressions, etc.), so it needs an explicit syntax to indicate this.
    • It might be easier to optimize non-recursive functions
    • The closure created when you create a recursive function needs to include an entry that points to the function itself (so the function can recursively call itself), which makes recursive closures more complicated than non-recursive closures. So it might be nice to be able to create simpler non-recursive closures when you don't need recursion
    • It allows you to define a function in terms of a previously-defined function or value of the same name; although I think this is bad practice
    • Extra safety? Makes sure that you are doing what you intended. e.g. If you don't intend it to be recursive but you accidentally used a name inside the function with the same name as the function itself, it will most likely complain (unless the name has been defined before)
    • The let construct is similar to the let construct in Lisp and Scheme; which are non-recursive. There is a separate letrec construct in Scheme for recursive let's

提交回复
热议问题