Haskell - lambda expression

19,632

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]
Share:
19,632
user3377437
Author by

user3377437

Updated on July 23, 2022

Comments

  • user3377437
    user3377437 over 1 year

    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!