Learning Haskell - Lambda functions
In the last post, we explored the basics of Haskell, how to install Haskell, “variables”, functions, etc. In part 2 of “Learning Haskell”, we are going to explore a little bit about Lambda functions.
You probably have seen this piece of JavaScript code before:
(function () {
console.log('Something...')
})()
The pattern above is called IIFE (Immediately Invoked Function Expression), this is a function that it’s immediately invoked and runs as soon as it is defined.
In other words, we can say that IIFE is a Lambda function too.
Lambda functions
Also called as Anonymous function, Lambda functions (λ) are functions with no name, they are the very minimum possible function, and as any other function in Haskell, it takes a value and return that value.
A very simple Lambda function:
(\x -> x)
-- The backslash means this function is a Lambda function
To use this very simple function, you should call it passing its parameters like so:
(\x -> x) "Haskell!"
-- Haskell!
Another example, let’s say we have this function that doubles twice a value:
doubleDouble x = dubs * 2
where dubs = x * 2
This is a very simple function, we are using the where
keyword to create or dubs
“variable”, no big deal.
With Lambda function, we could write the same function like so:
doubleDouble x = (\dubs -> dubs * 2) (x * 2)
-- doubleDouble 2
-- will return 8 :p
Although the Lambda function might look a little difficult to understand at first, bear in mind that as an expression, your Lambda function is not syntactically wrapped in your function like the way the where
keyword it is.
The big thing about Lambda functions is that you can create functions on the fly, with its own scope. By the way, Haskell uses Lexical Scope like JavaScript.
–
That’s all for today. Stay tuned!