Does a language with first-class functions necessarily allow closures?

394 views Asked by At

I understand the broad concept of a closure (functions are stored along with a snapshot of environment at the time they were defined), and functions as first class citizens means that functions can be passed and returned like any other data type in the language.

Interestingly all languages that I've worked with that have functions as first class citizens, for example Python, Javascript, Scheme seem to always have closures as well.

Indeed passing and returning closures to and from a function is one way of implementing functions as first class citizens of the language, but I'm unsure if being able to write them is a direct and inevitable consequence of functions being first class citizens.

To put in more specific terms:

Can you provide an actual example of a language which has first-class functions but where it is not possible to write closures?

1

There are 1 answers

2
Jivan On

Such languages are languages in which functions are first-class objects.

When a function is defined inside another function, the nested function is called higher-order function.

Functions being first-class objects means that functions do not differ from other objects such as numbers, strings, classes etc. Thus, you can pass them as arguments, or return them, just like any other object, without calling them. For instance in Python, you can return the function in itself without calling it, by omitting the parenthesis.

Being able to write a higher-order function which another wrapping function can return is precisely the definition of a closure, and is a consequence of having functions as first-class objects.

Thus, the answer to your question is: yes, closures are a necessity for having functions as first-class objects, in the sense that they are a consequence of that. To put it more directly, you can't have first-class functions and not be able to write closures.

Note that some languages without first-class functions (Pascal, Algol) have sort of closures which are called lexical closures. But they are far less powerful than actual closures.