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

To write an inline function in Haskell, we use a very specific syntax. It looks like this: \arg -> body.

The backslash \ is used because it visually resembles the Greek letter lambda (λ\lambda), which is a traditional symbol for functions in math and computer science. Following the backslash, we state the parameter our function will accept. In this example, this is arg. Next, we use an arrow -> to point to the body of the function, which contains the actual logic we want to perform.

One of the best features of lambdas is that we usually do not need to write out type signatures for them. Haskell's smart type inference figures out the types automatically based on how and where the lambda is used in your code.

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.

Haskell
(\n -> n * 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.

Haskell
tripled :: [Int]
tripled = map (\n -> n * 3) [1, 2, 3, 4]

To see this in action, let's write a small program to print the result.

Haskell
tripled :: [Int]
tripled = map (\n -> n * 3) [1, 2, 3, 4]

main :: IO ()
main = do
  print tripled

Output:

text
[3,6,9,12]

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!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal