Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 645
Trix Avatar asked May 16 '10 14:05

Trix


People also ask

What is let in programming language?

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

Which language uses let keyword?

Stateful imperative languages such as ALGOL and Pascal essentially implement a let expression, to implement restricted scope of functions, in block structures.

What is let in C++?

let is the keyword for variable declaration. There is no such keyword in C++ since variable are declared TypeName variable_name . Anytime you have a let you are declaring one or many variables. They can be immutable(by default), mutable(with the mut modifier) or defined with a more complex pattern. 17.

Is F# functional language?

F# is a functional programming language, and with that comes more new vocabulary than you may expect.


1 Answers

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.

like image 180
Tomas Petricek Avatar answered Oct 07 '22 15:10

Tomas Petricek