next up previous contents index
Next: Examples Up: Introductory Scheme Previous: Binding

Functions are First-Class

 

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)

((lambda (x) (+ 5 x)) 10) tex2html_wrap_inline972 15

This allows us, for example, to define a function called map  that applies some function to each element of a list:
   (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)) 		  tex2html_wrap_inline972  		 (2 3 4)

(map (lambda (x) (* 2 x)) '(1 2 3)) tex2html_wrap_inline972 (2 4 6)

(map (lambda (x) (list x)) '(1 2 3)) tex2html_wrap_inline972 ((1) (2) (3))

(map sqrt '(1 4 9)) tex2html_wrap_inline972 (1 2 3)



Steven J. Zeil
Tue Mar 4 14:36:27 EST 1997