Re:Why Python doesn't need blocks
by anaphor on Monday June 30, 2014 @12:14PM
(#7965820)
Part of the reason why functional languages like Scheme have anonymous functions (lambdas) is so that you can encode various language features in them.
function definition: (define (f x) (+ x x)) => (define f (lambda (x) (+ x x)))
variable binding: (let ((x 1) (y 2)) (+ x y)) => ((lambda (x y) (+ x y)) 1 2)
But they also sometimes are convenient when you have a function or procedure that expects the same as one of its parameters, but said function doesn't already exist, and there isn't a simple composition of higher-order (functions that take or return functions) functions that does what you want.
For example, say you wanted to multiply a list of numbers by their squares (this is in Racket):
function definition: (define (f x) (+ x x)) => (define f (lambda (x) (+ x x)))
variable binding: (let ((x 1) (y 2)) (+ x y)) => ((lambda (x y) (+ x y)) 1 2)
delayed evaluation: (delay (display "foo")) => (lambda () (display "foo"))
and lots more...
But they also sometimes are convenient when you have a function or procedure that expects the same as one of its parameters, but said function doesn't already exist, and there isn't a simple composition of higher-order (functions that take or return functions) functions that does what you want.
For example, say you wanted to multiply a list of numbers by their squares (this is in Racket):
(define (sqrmult n) (foldr (lambda (x y) (* (sqr x) (sqr y))) 1 (stream->list (in-range 1 n))))
See you don't have to name the function?