What is the “let” keyword in functional languages like F# and OCaml for?

≯℡__Kan透↙ 提交于 2019-11-28 07:05:44

问题


When looking at F#, Ocaml and other functional language code examples I notice that the let keyword is used very often.

  • Why do you need it? Why were the languages designed to have it?
  • Why can't you just leave it out? e.g: let x=4 becomes x=4

回答1:


In F# (and OCaml) let is quite powerful construct that is used for value binding, which means assigning some meaning to a symbol. This can mean various things:

Declaring local or global value - you can use it for declaring local values. This is similar to creating a variable in imperative languages, with the exception that the value of the variable cannot be changed later (it is immutable):

let hello = "Hello world"
printfn "%s" hello

Declaring function - you can also use it for declaring functions. In this case you specify that a symbol is a function with some arity:

let add a b = a + b
printfn "22 + 20 = %d" (add 22 20)

Why do you need it? In F#, the code would be ambiguous without it. You can use value hiding to create new symbol that hides the previous symbol (with the same name), so for example the following returns true:

let test () =
  let x = 10
  let x = 20 // hides previous 'x'
  x = 20     // compares 'x' with 20 and returns result

If you omitted the let keyword, you wouldn't know whether you're comparing values or whether you're declaring a new symbol. Also, as noted by others, you can use the let <symbol> = <expression> in <expression> syntax (if you use line-break in F#, then you don't need in) to write value bindings as part of another expression:

let z = (let x = 3 + 3 in x * x)

Here, the value of z will be 36. Although you may be able to invent some syntax that doesn't require the let keyword, I think that using let simply makes the code more readable.




回答2:


The main purpose of "let" is putting a scope around its definitions.

let <definitions> in <expression>

Makes sure that the definitions don't pollute the namespace of anything other than <expression>.




回答3:


"let" introduces a new variable scope, and allows you to bind variables to values for that scope. It is often read as "let x be [value] in ...". When you don't have assignment, it is very useful to avoid conflicting variable names.




回答4:


In Haskell,

foo = let x = 5
      y = 7
      in z=x+y

is used to make clear that x and y are "private" variables to foo.




回答5:


let means "bind value to name" and generally spoken, creates a new variable. x = 4 means "assign 4 to x", which doesn't create a new name.

See http://msdn.microsoft.com/en-us/library/dd233238.aspx




回答6:


If you're into learning, this lecture might be relevant also, esp. the part about evaluating the let term.



来源:https://stackoverflow.com/questions/2844047/what-is-the-let-keyword-in-functional-languages-like-f-and-ocaml-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!