Is every anonymous function a closure?

Asked

Viewed 114 times

7

Every anonymous function is considered a closure or only those that refer to the context where they were created are?

I wish I knew that to distinguish them correctly. I know the concepts and the functionalities, but the impression is that many treat both as if they were the same.

1 answer

6


No, they’re completely independent mechanisms. Although it is technically possible to have a cloning mechanism in a function that is not anonymous, I only know implementations of closure in anonymous functions. But an anonymous function has no obligation to have a closure. So in theory there is no need for bonding of both in both directions and in practice what happens is there is bonding in one sense only.

The enclosure mechanism is only to capture a value contained in another scope for the scope of the anonymous function extending its lifespan. So if you don’t capture this value in this way in an anonymous function you didn’t include the enclosure mechanism.

Each technology can implement this the way it wants to internally. So it may be that a certain language makes all anonymous functions pay the price of being able to have a cloister even without capturing a value. That doesn’t mean you have one closure there, just that it has the ability to have. But reinforcement that is implementation detail and only worth knowing for optimization reasons.

In fact people tend to think it’s the same thing, but it’s not. There are subtle differences to the terms lambda, first class functions or of high order.

Some technologies may call the same name, for example to say that a simple anonymous function is a closure, but strictly this is wrong. The language that does this usually passes an image of ignorance, or arrogance or both.

An anonymous function can be implemented very simply with a trigger indirect and be able to store in some places. A closure needs a slightly more complex object to maintain the values or references for the captured variables.

You can see more in:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.