concept lambda function in category haskell

appears as: lambda functions, lambda function
Get Programming with Haskell

This is an excerpt from Manning's book Get Programming with Haskell.

One of the most foundational concepts in functional programming is a function without a name, called a lambda function (hence lambda calculus). Lambda functions are often referred to using the lowercase Greek letter λ. Another common name for a lambda function is an anonymous function. You can use a lambda function to redefine your simple function from lesson 2, only without a name. To do this, you use Haskell’s lambda syntax, shown in figure 3.1.

Figure 3.1. The simple function rewritten as a lambda function

Lambda functions are the minimum possible function: they take a value and return a value, and that’s all. You can’t paste this anonymous function you just wrote into GHCi or a Haskell program, because it’s just an expression that by itself does nothing. To bring life to a lambda function, you must use it for something. The easiest thing you can do is pass an argument to it:

GHCi> (\x -> x) 4
4
GHCi> (\x -> x) "hi"
hi
GHCi> (\x -> x) [1,2,3]
[1,2,3]

Notice that each time you use your lambda expression, you have to redefine it. This makes sense, because you have no name to call it by! Lambda functions are useful but are designed to exist for only a short while. In general, if a named function will do the job, it’s better to use one.

To solve this problem, JavaScript developers used a lambda function. By wrapping your code in a lambda function and then immediately calling that function, you can keep your code safe. This pattern is called an immediately invoked function expression (IIFE). Using IIFE, your code now looks like this:

In this lesson, our objective was to teach you about lambda functions. Lambda functions are a simple idea: a function with no name. But they’re foundational for functional programming. Aside from their role as a theoretical corner store of functional programming, they provide practical benefits. The most obvious benefit is that lambda functions allow you to easily write functions on the fly. The even more powerful feature of lambda functions is that they allow you to create scope as needed. Let’s see if you got this.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest