Hacker News new | ask | show | jobs
by masklinn 2325 days ago
Closures are completely unnecessary to start with yet I don’t see you bemoan their existence.

“Callability” not being restricted to functions (closures or not) can often be convenient, especially when that use is colloquial (eg closure where symbols and collections are callable), and obviate unnecessary boilerplate.

2 comments

What unnecessary boilerplate is obviated by callable objects in a language that already has closures?
Having to wrap every use of whatever method in a closure when you could just pass the object itself eg

    (map (fn [x] (get m x)) a-vec)
Would usually be

    (map m a-vec)
That's not a fair comparison. You don't have to wrap every use of your method in a closure any more than you have to call the constructor of your callable class on every use.

You have to bind your state to a function exactly once in both cases.

Your example just happens to omit the constructor call required to create the callable object while you are showing the code to create the closure.

How are closures unnecessary?
The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures."

Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress.

On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened.

From: http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/m...

Anything you do with a closure, you can do with an object that holds the closed-over state and a function that performs the same operation on that state. For a real-world example of this in action, partial application is traditionally associated with closures, but Python's functools.partial() is implemented as a callable object that holds the partially applied function and parameters in instance variables.