3 ms·
This explanation did not add anything to help me better understand closures and anonymous functions. I already understand that closures allow you to pass an ano
by dmbass 15y ago
This explanation did not add anything to help me better understand closures and anonymous functions. I already understand that closures allow you to pass an anonymous function around and it maintains the variables that were in its scope when it was created (whether by copy or reference).
The problem, at least for me, is finding a non-trivial example of using an anonymous function. Does anybody have other examples like malkia's[1] that demonstrate why anonymous functions and closures are useful? Or maybe just a good explanation of functional programming?
1. http://news.ycombinator.com/item?id=2919149 http://news.ycombinator.com/item?id=2919149
- viscanti 15y agoIn Scheme named functions are simply syntactic sugar for anonymous functions (or Lambda expressions). The same is true in Javascript. http://lpar.ath0.com/2010/10/14/javascript-when-is-a-function-not-a-function/ http://lpar.ath0.com/2010/10/14/javascript-when-is-a-functio...
- njharman 15y agoWhether a function is anonymous or not is sugar. The important thing is functions aren't special, they can be passed around (i.e. the are 1st class objects). I actually can't fathom having to code in a language in which you can't pass functions around. Call backs is my biggest use of function passing. This is really, really huge. Currying, decorating/wrapping functions Replacing methods/functions at run time. Great for testing. Putting them in data structures. Often dictionaries. Often to create more dynamic switch like logic. dict[key] = func_that_handles_key, etc. then later, dict[key](key) Lots of data is code stuff. Closures just make the passed functions more powerful / convenient as they capture their scope. Which is often used (at least by me in Python) to create function factories that return custom functions. A contrived example but a pattern I use often. Logging object with warn, debug, error functions. You could hardcode / boilerplate each of those functions but that is boring, tedious, and nonDRY. So instead you create a function factory and use it to return anonymous functions, like so. Python. def log_func_factory(level): def closure(msg): print level, msg return closure class logging(object): debug = log_func_factory('debug') warn = log_func_factory('warn') error = log_func_factory('error') With real code I'd not repeat those assignments and instead use a loop driven by data. for level in ('debug', 'warn', 'error'): setattr(logger, level) = log_func_factory(level) Bam, data driven code. Very DRY, very concise, very dynamic. Maintenance is adding one text string in one place.
- spacemanaki 15y agoI think the classic example of using anonymous functions is probably as arguments to map, filter, reduce, etc: > (mapcar #'(lambda (x) (+ x x)) (list 1 2 3 4)) (2 4 6 8) In that case, the anonymous function doesn't close over anything. Here's an example where it does (from On Lisp): > (defun list+ (lst n) (mapcar #'(lambda (x) (+ x n)) lst)) > (list+ (list 1 2 3) 10) (11 12 13) In this case `n` is closed over. Both of these ARE pretty trivial, but the point I'm trying to make is that anonymous functions in many cases just make some code a bit more concise and avoids the need for nested named functions, which I guess is common in Python where `lambda` can only contain an expression. I'm reading On Lisp now, and there are some examples early on of functions that return functions. In those cases, the functions being returned are almost always anonymous, just because naming them would be kind of verbose and unnecessary. There are other, more complicated uses, for instance closures can be used as a sort of crude way of making objects, and supporting hacky encapsulation, which is described in a lot of Scheme textbooks, like SICP: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%_sec_3.2.3 http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html... As for functional programming, it's a lot more than just first-class, anonymous and higher order functions. It also encourages or enforces pure functions: functions in the mathematical sense that do not have side effects, and always return the same value given the same arguments. SICP is a good start, if you're curious about Lisp. It's a great book. There's other places too though, to get this stuff, if you wanted to dive into the Haskell world via Learn you a Haskell I'm sure you'd see some of what FP is about. I'm less familiar with it though. edited for clarity and fix the SICP link
- malkia 15y agoFor anonymous - GUI event-handlers/callbacks. Say in MFC, or wxWidgets, or similar you have to explicitly say this even tones to this function, with anonymous functions this is easier, you can just "inline it". If I'm not wrong, in .NET something like this: With functions (.NET, C# kind of) button1.Click += new EventHandler(OnButton1Clicked) somewhere you would have to declare OnButton1Clicked with anonymous function: button1.Click += delegate(Event e) { Console.WriteLine(e.ToString()); }; or for newer .NET (both of my examples might be wrong, check the docs) button1.Click += (e) { Console.WriteLine(e.ToString()); }; but what the other folks said in answers to you is how most of the time anonymous were used - map/reduce type of situations, or your "C" sort() if you can plug anonymous there.