In Scheme, as in most dialects of Lisp, functions are first-class . This means that they are values, just like any other data type--they may be passed as arguments to functions and returned as values of functions. This is one of the most powerful aspects of Scheme.
One construct that is useful when passing functions as arguments is lambda . This gives one the capability to define functions without names. The lambda statement has the same syntax as the define statement, but without a function name. For instance, (lambda (x) (+ 5 x)), when evaluated, returns a function of one argument, that adds five to that argument. That is,
MMM ¯((lambda (x)This allows us, for example, to define a function called map that applies some function to each element of a list:((lambda (x) (+ 5 x)) 10) 15
(define (map fn l1) (cond ((null? l1) '()) (else (cons (fn (car l1)) (map fn (cdr l1))))))We may now apply map like so:
MMM T(map (lambda (x) (list x)) '(1 2 3))MM MMM T(map (lambda (x) (+ 1 x)) '(1 2 3)) (2 3 4) (map (lambda (x) (* 2 x)) '(1 2 3)) (2 4 6)
(map (lambda (x) (list x)) '(1 2 3)) ((1) (2) (3))
(map sqrt '(1 4 9)) (1 2 3)