Prev Up Next

We have seen quite a few primitive Scheme procedures, eg, cons, string->list, and the like. Users can create their own procedures using the special form lambda. For example, the following defines a procedure that adds 2 to its argument:

(lambda (x) (+ x 2))

The first subform, (x), is the list of parameters. The remaining subform(s) constitute the procedure's body. This procedure can be called on an argument, just like a primitive procedure:

((lambda (x) (+ x 2)) 5)
=> 7

If we wanted to call this same procedure many times, we could create a replica using lambda each time, but we can do better. We can use a variable to hold the procedure value:

(define add2
  (lambda (x) (+ x 2)))

We can then use the variable add2 each time we need a procedure for adding 2 to its argument:

(add2 4) => 6
(add2 9) => 11

3.1.1  Procedure parameters

The parameters of a lambda-procedure are specified by its first subform (the form immediately following the head, the symbol lambda). add2 is a single-argument -- or unary -- procedure, and so its parameter list is the singleton list (x). The symbol x acts as a variable holding the procedure's argument. Each occurrence of x in the procedure's body refers to the procedure's argument. The variable x is said to be local to the procedure's body.

We can use 2-element lists for 2-argument procedures, and in general, n-element lists for n-argument procedures. The following is a 2-argument procedure that calculates the area of a rectangle. Its two arguments are the length and breadth of the rectangle.

(define area
  (lambda (length breadth)
    (* length breadth)))

Notice that area multiplies its arguments, and so does the primitive procedure *. We could have simply said:

(define area *)

3.1.2  Variable number of arguments

Some procedures can be called at different times with different numbers of arguments. To do this, the lambda parameter list is replaced by a single symbol. This symbol acts as a variable that is bound to the list of the arguments that the procedure is called on.

In general, the lambda parameter list can be a list of the form (x ...), a symbol, or a dotted pair of the form (x ... . z). In the dotted-pair case, all the variables before the dot are bound to the corresponding arguments in the procedure call, with the single variable after the dot picking up all all the remaining arguments as one list.

Prev Up Next

Log in or register to write something here or to contact authors.