3 ms·
I 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
by spacemanaki 15y ago
I 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