Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 737
ffledgling Avatar asked Oct 20 '22 20:10

ffledgling


1 Answers

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.

like image 65
Jivan Avatar answered Oct 30 '22 21:10

Jivan