Lambdas vs Closures

28 May 2015 | functional programming

Differences between Lambdas and Closures

A Lambda Expression is merely an anonymous function - a language construct. Giving a lambda a name makes it a named function.

A Closure on the other hand is a technique to implement first-class functions. They are functions that ‘close over the environment in which they are defined’ which just means that they have access to variables present in the context where they were created, not necessarily just those in their parameter list.

As with most things in life, the best way to understand something is through examples. So here goes:

Std disclaimer: closures/lambdas are language-dependent. They don’t mean quite the same thing in different languages nor are they implemented in the same way. For e.g: Java implements lambda expressions via closures. Hence, these terms are used interchangeably.


def select_runners(people)
  return { |p| p.can_run? }

Here the block of code passed to the select method is a lambda. This lambda is executed for each element in the collection.


def select_runners(people)
  min_speed_cutoff_kph = 10
  return { |p| p.can_run? && p.speed > min_speed_cutoff_kph }

Notice how the lambda refers to min_speed_cutoff_kph, a variable defined outside of it, in the scope of its enclosing function. It is now said to be closed over the environment it was defined in.

The above code can also be written as:

def can_run_fast_enough?(cutoff_speed_kph)
  return lambda { |p| p.can_run? && p.speed > cutoff_speed_kph}

can_run_faster_than_10_kph? = can_run_fast_enough?(10)

milkha_singh =
milkha_singh.speed = 20

Now the can_run_faster_than_10_kph?.call(milkha_singh) checks if Milkha Singh can run faster than 10 kph by calling the lambda in can_run_fast_enough?. The value of the cutoff_speed_kph is bound to 10 which is the value it was created with. Even if this went out of scope, the binding will remain.


To put it simply, a closure is a lambda paired with the environment in which it was created, which then closes over the lambda.

Some excellent reads on the subject:

comments powered by Disqus

Older · View Archive (17)

Hibernate Custom UUID generator

Use a custom uuid generator in Hibernate.

Many web applications these days use UUIDs as primary keys in their database. While this approach has its pros and cons (see Primary Keys vs GUIDs), one of the principal advantages is that you can generate these ids outside of the database.


How to say a REST-ful NO?

We had an interesting discussion at work yesterday: for a REST api, what HTTP status code to return when a resource does not exist - a 200 OK with an empty result, a 204 NO CONTENT or a 404 NOT FOUND ?