Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Haskell: Lambda: Anonymous functions

Lambdas are anonymous functions (don't have name), used in situations where you want to use function only once.

How to define a lambda?
Lambda is created by using \ followed by parameters, separated by spaces. After that comes a -> and then the function body.
Following snippet calculates the sum of three numbers.

*Main> let sum = \x y z -> (x+y+z) 
*Main>
*Main> sum 10 20 30
60
*Main>


You can also define lambda parameters by using parenthesis like below.

*Main> let sum = \(x, y, z) -> (x+y+z) 
*Main>
*Main> sum(10,20,30)
60


Following lambda swap two elements.

*Main> let swap = \x y -> (y, x)
*Main>
*Main> swap 10 20
(20,10)


You can also apply pattern matching in lambda expressions.

*Main> let tail_list = (\ (_:xs) -> xs)
*Main>
*Main> tail_list [2, 3, 5, 7]
[3,5,7]


Difference between lambda and normal functions
We can write normal functions using multiple clauses like guards, cases, if-else etc.,but a lambda can have only a single clause in its definition.


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell: Lambda: Anonymous functions

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×