Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding (\x -> ) in Haskell

Tags:

haskell

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?

like image 309
CodyBugstein Avatar asked Nov 28 '22 17:11

CodyBugstein


2 Answers

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.

like image 195
comingstorm Avatar answered Dec 10 '22 11:12

comingstorm


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.

like image 24
Will Ness Avatar answered Dec 10 '22 13:12

Will Ness