9

I am trying to understand what's useful and how to actually use lambda expression in Haskell. I don't really understand the advantage of using lambda expression over the convention way of defining functions. For example, I usually do the following:

let add x y = x+y

and I can simply call

add 5 6

and get the result of 11 I know I can also do the following:

let add = \x->(\y-> x+y)

and get the same result. But like I mentioned before, I don't understand the purpose of using lambda expression. Also, I typed the following code (a nameless function?) into the prelude and it gave me an error message.

let \x -> (\y->x+y)

parse error (possibly incorrect indentation or mismatched backets)

Thank you in advance!

1
  • As to the let \x -> (\y->x+y) statement - the let statement is used to give names to things. In its simplest form, the statement looks like let name = expression. And from that point you use name each time you want to refer to expression. In your example, \x -> (\y->x+y) is an expression (a value of function type). So, your whole statement has the form let expression, no names bound. It has no point such way. Let expression what? Commented Mar 6, 2014 at 12:46

1 Answer 1

22

Many Haskell functions are "higher-order functions", i.e., they expect other functions as parameters. Often, the functions we want to pass to such a higher-order function are used only once in the program, at that particular point. It's simply more convenient then to use a lambda expression than to define a new local function for that purpose.

Here's an example that filters all even numbers that are greater than ten from a given list:

ghci> filter (\ x -> even x && x > 10) [1..20]
[12,14,16,18,20]

Here's another example that traverses a list and for every element x computes the term x^2 + x:

ghci> map (\ x -> x^2 + x) [1..10]
[2,6,12,20,30,42,56,72,90,110]
Sign up to request clarification or add additional context in comments.

1 Comment

Isn't it better for legibility to use a descriptive name and then define it in a where later? filter myCompare [1..20] or map myTraverse [1..10].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.