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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In F# (and OCaml)
letis 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):
Declaring function – you can also use it for declaring functions. In this case you specify that a symbol is a function with some arity:
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:If you omitted the
letkeyword, 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 thelet <symbol> = <expression> in <expression>syntax (if you use line-break in F#, then you don’t needin) to write value bindings as part of another expression:Here, the value of
zwill be 36. Although you may be able to invent some syntax that doesn’t require theletkeyword, I think that usingletsimply makes the code more readable.