Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I implemented anonymous methods in Delphi, and I faced a similar kind of problem trying to sell them, as it were, to the Delphi community.

What they are: functions with state.

Why they're useful: callbacks where a whole separate method or class would be overkill.

Motivating examples:

* Delegating work to a background thread. Captured variables are an easy way to pass along necessary state.

* A generic benchmarking routine. Benchmarking requires taking a measurement before the code, running the code to be measured possibly multiple times, and taking another measurement after the code. If you can turn the code to be measured into a callback, then the benchmarking code can be written once and reused elsewhere. But having to put all your benchmarks into their own methods, much less worry about state and possibly creating classes and initializing data in constructors, is pretty tedious. Closures avoid this tediousness.

(Yes, I'm conflating several concepts here, anonymous functions and lambda closures, for colloquial and didactic reasons. Nitpicking doesn't buy you much in terms of practicality when learning here.)



Are they similar in any way to Python generators? They are functions with a state, at least.


Multiple closures can share the same state ("environment"). Consider:

  (let ((i 0))
    (list (lambda () (incf i))
          (lambda () (decf i))
          (lambda () i)))
If you evaluate the first function this form returns ("increment") and then the third form ("get"), the result is 1. If you evaluate the whole form again, you now have another "instance", with its own separate shared i.

In Python, you would probably just make this a class. (But sometimes it's nice to have something equivalent to a class that's automatically built for you, and closures are that something.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: