Home

> urticator.net
Search

> Domains
Glue
Stories

> Computers
Driving
Games
Humor
Law
Math
Numbers
Science

Concepts for Persistent Objects
Language Design Principles
> Miscellaneous

An Owning Pointer
Finalization in Java
 > What Is Lambda?
Hierarchical Namespaces
How I Learned to Write Comments

## What Is Lambda?

Since the idea might not be familiar to everybody, I thought it would be nice to write a short explanation of what lambda expressions are all about. If you want a longer explanation, see any book on Scheme or Lisp, or, of course, the lambda calculus.

I think of lambda expressions as functions. Here are some examples.

(lambda (x) x)
(lambda (x) (+ x 1))
(lambda (x y) (+ x y))
(lambda (x y) (if (> x y) x y))

These are, respectively, the identity function, a function that increments a number, a function that adds two numbers, and a function that takes the maximum of two numbers. The addition function, for example, accepts two arguments, as indicated in the list (x y), and returns the value of the expression (+ x y).

The correct statement, by the way, is not that lambda expressions are functions, but that they evaluate to functions … or rather to closures.

Although closures are in themselves nameless, it's certainly possible to assign names to them, like so.

(define increment (lambda (x) (+ x 1)) )

(increment 17) = 18

However, it's not necessary to assign names; one can use closures directly.

( (lambda (x) (+ x 1)) 17 ) = 18

That's the basic idea, now let's look at a few of the fun parts.

Suppose we want to make some functions that increment not by 1 but by a variable amount, like so.

(lambda (x) (+ x delta))

Since we want a lot of these, it would be nice if we didn't have to define them individually, if we could just supply a value for delta and get back a function … in other words, if we had a function that returned functions. But we can do exactly that!

(lambda (delta)
(lambda (x) (+ x delta)) ))

( (add 3) 17 ) = 20

But that's not all we can do. Not only can closures be returned from functions, they can be passed in as arguments. Here's one of the many possibilities.

(define apply-twice (lambda (f x) (f (f x))) )

(apply-twice (add 3) 17) = 23

Amazing, no?