Lambda expressions, also known as anonymous functions, are a powerful feature in Haskell that allow you to create functions without naming them. They are particularly useful for short, throwaway functions that you don't need to reuse.
Key Concepts
- Syntax: The basic syntax for a lambda expression in Haskell is
\args -> expression
. - Usage: Lambda expressions are often used in higher-order functions like
map
,filter
, andfold
. - Scope: Variables defined within a lambda expression are local to that expression.
Syntax
The general form of a lambda expression is:
\
is the lambda symbol.arg1 arg2 ... argN
are the arguments.expression
is the body of the function.
Example
Here is a simple example of a lambda expression that adds two numbers:
You can use this lambda expression just like any other function:
Practical Examples
Example 1: Using Lambda with map
The map
function applies a given function to each element of a list. You can use a lambda expression to define this function on the fly.
Example 2: Using Lambda with filter
The filter
function selects elements from a list that satisfy a given predicate. A lambda expression can be used to define this predicate.
Example 3: Using Lambda with foldr
The foldr
function reduces a list to a single value using a binary function and a starting value. A lambda expression can define this binary function.
Exercises
Exercise 1: Double the Elements
Write a lambda expression to double each element in a list.
Exercise 2: Filter Even Numbers
Write a lambda expression to filter out even numbers from a list.
Exercise 3: Sum of Squares
Write a lambda expression to calculate the sum of squares of a list of numbers using foldr
.
Solutions
Solution 1: Double the Elements
Solution 2: Filter Even Numbers
Solution 3: Sum of Squares
Common Mistakes and Tips
- Forgetting the backslash (
\
): Always start a lambda expression with\
. - Misplacing the arrow (
->
): Ensure the arrow is placed correctly between the arguments and the expression. - Scope issues: Remember that variables inside a lambda expression are local to that expression.
Conclusion
Lambda expressions are a concise way to define functions on the fly. They are particularly useful in higher-order functions like map
, filter
, and fold
. By mastering lambda expressions, you can write more flexible and concise Haskell code. In the next section, we will explore Map, Filter, and Fold
in more detail, building on the concepts introduced here.
Haskell Programming Course
Module 1: Introduction to Haskell
- What is Haskell?
- Setting Up the Haskell Environment
- Basic Syntax and Hello World
- Haskell REPL (GHCi)