3

Can someone explain to me how lambda works in Haskell?

For eg. add' = \x -> (\y -> x+y) or foldl (\x _ -> x+1) 0 [1,2,3] == 3

I know what the results are and what the functions do, but I don't understand why do we need lambda expression or what does lambda do in the functions?

Thank you very much

1
  • 5
    You don't need lambda, as in you can define a function. It is simply a way to write short functions. The \x -> ... part defines a function that maps x to .... But fr your example, you could define add' = (+) and foldl (+1) 0 [1,2,3], so you do not per se need to use a lambda expression. Commented Mar 5, 2020 at 16:04

2 Answers 2

6

In some sense, a lambda expression is the way to define a function from scratch.

You could write

add' x y = x + y

but that desugars to

add' x = \y -> x + y

which itself desugars to

add' = \x -> \y -> x + y

In the case of foldl (\x _ -> x + 1) 0 [1,2,3], you need to provide a function as the first argument. A lambda expression is a convenient way to do that without having to come up with an otherwise unused name for it. For example,

foldl someFoldFunc 0 [1, 2, 3]
    where someFoldFunc x _ = x + 1

though one can also construct the function using other functions, rather than building it up from scratch.

foldl (const . (+1)) 0 [1, 2, 3]

Most would argue that this is less readable than either the explicit lambda expression or the named function.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to understand that defining a lambda function is just a way to express a function without a name. Lambdas exist in many languages like f.i. Haskell and JavaScript. However unlike many other languages, in Haskell including Lambdas all functions come by default in a curried manner. In another sense, you may always partially apply them.

What is partial application..? If a function asks for 4 parameters and you provide only 2 then what you get as a result is another function expecting the remaining 2 arguments. So when a function gets partially applied it returns you a new function which accepts the remaining arguments up until it returns the final result once the required arguments are all depleted.

This fancy behaviour yields to tons of mockery which is called Lambda calculus.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.