Reputation: 23322
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?
Upvotes: 4
Views: 10352
Reputation: 71065
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.
Upvotes: 8
Reputation: 26097
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.
Upvotes: 11
Reputation: 12700
It is a lambda function, that is, a function that you define in the spot mostly for convenience. You read it as "take x as your input, multiply it by 6 and see if it is less than 100". There are some other amenities related, though. For example, in Haskell Lambda functions and ordinary functions have a lexical environment associated and are properly speaking closures, so that they can perform computations using the environment as input.
Upvotes: 4
Reputation: 57470
(\x -> 6*x < 100)
is a lambda, an anonymous function that takes one argument (here called x
) and computes & returns 6*x < 100
, i.e., tests whether that number multiplied by 6 is less than 100.
Upvotes: 4