On ZVON, one of the definitions provided for the takeWhile function is
Input: takeWhile (\x -> 6*x < 100) [1..20]
Output: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
Can someone explain what the portion (\x -> 6*x < 100)
means?
It's an anonymous function definition, otherwise known as a lambda-expression. (\x -> 6*x < 100)
is a function which takes a number, and returns the boolean result of the inequality.
Since functional languages like Haskell frequently take functions as arguments, it is convenient to be able to define simple functions in-line, without needing to assign them a name.
Originally, the story goes, Alonzo Church wanted to mark variables in functional expressions with a circumflex, like e.g. (ŷ.x(yz))
but the Princeton printing press just couldn't do that at the time. He then wanted at least to print carets before the vars, like this: (^y.x(yz))
, but they couldn't do that either.
The next best option was to use the Greek letter lambda instead, and so they ended up writing (λy.x(yz))
etc., hence the "lambda" in lambda-expression. It was all just a typographical accident.
Today on ASCII terminals we can't even use the letter λ
, and so in Haskell we use a backslash instead (and an arrow in place of a dot in original lambda-expressions notation):
(\y -> x (y z))
stands for a function g
such that
g y = x (y z)
Source: read it somewhere, don't remember where.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With