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.
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.
(\x -> 6*x < 100)
is the same as((<100).(6*))
. – Landei.
mean? – CodyBugstein(.) f g x = (f .) g x = (. g) f x = (f . g) x = f (g x)
. So((<100).(6*)) x = (<100) ( (6*) x) = (<100) (6*x) = (6*x)<100
. IOW,((<100).(6*)) = \x -> (6*x)<100
. See also: stackoverflow.com/questions/13139969/… – Will Ness