closures and objects [closed]

橙三吉。 提交于 2019-11-28 20:49:12

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

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.

-- Anton van Straaten

I've been using closures for a long time in Javascript. Sometimes they would form an 'object', other times they're a useful way to provide instance data to a callback.

As far as I'm concerned they're another useful tool in the box but it goes beyond just sugar. Sugar relates to something you could reasonable do with another somewhat more convoluted syntax. Acheiving closures in a language that doesn't directly support them would be very difficult.

Closures are much more than syntactic sugar although I think it depends somewhat on your definition of "syntactic sugar".

To me, Java 1.5's for-each was syntactic sugar, but, for example, Ruby blocks go far beyond that. Closures provide a convenient level of abstraction, which is useful for implicit declaration of intent -- a big step toward DSL-ish syntax.

Closures and anonymous blocks are pretty important programming constructs and I hit the lack fast in java, C++, C, and about any other language that's missing them. They are especially useful with asynchronous and eventing stuff. They also make function-taking functions more enjoyable to use and provide choices to do more things without additional syntax. (see: smalltalk and scheme)

closures are like objects in OO languages. But functional languages lack subtyping and inheritance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!