1.1 KiB
1.1 KiB
logosub, language, title, code
| logosub | language | title | code |
|---|---|---|---|
| Software | en | Lambda expressions | Haskell |
You can define a function like:
double :: Int -> Int
double x = x + x
Which can also be written as an anonymous function:
\x -> x + x
Here, the \ symbol represents the Greek letter lambda: λ. This is derived from lambda calculus.
Lambda expressions can be used to more explicitly state that a function is returned.
Consider:
const :: a -> b -> a
const x _ = x
This can be written using a lambda expression and added parenthesis in the type definition. This is more explicit in that a function is being returned.
const :: a -> (b -> a)
const x = \_ -> x
And as an anonymous function. Consider the difference between these similar functions that return a list of odd numbers:
odds :: Int -> [Int]
odds n = map f [0..n-1]
where f x = x*2 + 1
odds :: Int -> [Int]
odds n = map (\x -> x*2 + 1) [0..n-1]
-- > odds 15
-- > [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29]