Anonymous Functions with Lambdas
Introduction to Anonymous Functions
Welcome back! As we continue through the fourth unit of our six-unit course, we will examine a new way to write functions.
In our previous lessons, we learned how to process lists using the map and filter functions. As a quick reminder, to tell these higher-order functions what to do, we passed other functions into them. Up until now, we have always used named helper functions or partial applications to get the job done.
However, creating a whole new named function for a tiny, single-use calculation often feels like too much extra work. Imagine needing to write a quick grocery list. You would probably jot it down on a sticky note rather than opening a word processor and formatting a formal document with a title. In Haskell, we have a "sticky note" equivalent called a lambda or anonymous function. It allows us to define a quick, one-off operation right where we need it without bothering to give it a name.
The Anatomy of a Lambda
Transforming Data with Lambdas
Let's look at how to use a lambda with the map function to transform data. Imagine we want to take a list of numbers and multiply each one by three.
First, let's write the lambda itself. We need an anonymous function that takes a number n and multiplies it by 3.
Notice that we place parentheses around the lambda. This informs Haskell that the entire \n -> n * 3 expression should be treated as a single unit.
Now, we want to apply this transformation to a list of integers: [1, 2, 3, 4]. We can drop our lambda straight into the map function, just as we would with a named function.
To see this in action, let's write a small program to print the result.
Output:
The lambda \n -> n * 3 catches each item in the list as n and multiplies it by 3. This completely eliminates the need to define a separate helper function elsewhere in our file!
