Haskell Let Expressions
A let expression binds names inside an expression and gives a result that uses them. The bindings last only for that one expression.
A let value can be used straight away
The let binds x to 5 inside the print call. The result after in doubles it.
main :: IO ()
main = print (let x = 5 in x * 2)One let can hold several bindings
This let binds x to 10 and y to 5. The result after in adds the two names.
total =
let x = 10
y = 5
in x + y
main :: IO ()
main = print totalA let can sit inside a function
The function binds discount inside its own let. The result takes that discount away from the price input.
finalPrice price =
let discount = 5
in price - discount
main :: IO ()
main = print (finalPrice 30)Example
discountedTotal =
let subtotal = 4 * 15
discount = 10
in subtotal - discount
main :: IO ()
main = print (let extra = 5 in discountedTotal + extra)Key points
- Let expression: a binding written inside an expression, before the word in.
- in: the word in separates the bindings from the result that uses them.
- Result: the value of the whole let expression is the value of the part after in.
- Scope: a name bound by let can be used only in the result part of that same let expression.
- Several bindings: one let can hold several bindings, and the result can use all of them.
In this example, the first let works out a subtotal of 60 and takes off a discount of 10, giving 50. A second let inside print adds an extra 5, so the program prints 55.
Note
a let expression is a value, so it can sit inside a larger expression such as a print call.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is the value of let x = 4 in x * x?