Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - lambda expression

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!

like image 491
user3377437 Avatar asked Mar 06 '14 09:03

user3377437


People also ask

What is lambda expression in Haskell?

λ-expressions (λ is the small Greek letter lambda) are a convenient way to easily create anonymous functions — functions that are not named and can therefore not be called out of context — that can be passed as parameters to higher order functions like map, zip etc.

Is Haskell a lambda calculus?

When talking about Haskell, the term “lambda calculus” often crops up. It's a theoretical framework used to define the meaning of computation in many functional languages, such as Haskell, Agda, Idris, etc. Understanding lambda calculus can be very helpful when talking about programs written in these languages.

How do you evaluate a lambda expression?

Evaluating a Lambda Expression Evaluation is done by repeatedly finding a reducible expression (called a redex) and reducing it by a function evaluation until there are no more redexes. Example 1: The lambda expression (λx. x)y in its entirety is a redex that reduces to y.


Video Answer


1 Answers

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]
like image 59
kosmikus Avatar answered Oct 17 '22 19:10

kosmikus