Chapter 5: Control Operations


click to expand

Three warped, two-armed spirals.

This chapter introduces the syntactic forms and procedures that serve as control structures for Scheme programs, The first section covers the most basic control structure, procedure application, and the remaining sections cover sequencing, conditional evaluation, recursion, continuations, delayed evaluation, multiple values, and evaluation of constructed programs.

5.1. Procedure Application

(procedure exp ...)

syntax

returns: result of applying the value of procedure to the values of exp

Procedure application is the most basic Scheme control structure. Any structured form without a syntax keyword in the first position is a procedure application. The expressions procedure and exp are evaluated and the value of procedure is applied to the values of exp .

The order in which the procedure and argument expressions are evaluated is unspecified. It may be left to right, right to left, or any other order. The evaluation is guaranteed to be sequential, however; whatever order is chosen, each expression is fully evaluated before evaluation of the next is started.

 (+ 3 4)  7 ((if (odd? 3) + -) 6 2)  8 ((lambda (x) x) 5)  5 (let ((f (lambda (x) (+ x x))))   (f 8))  16 

(apply procedure obj ... list)

procedure

returns: the result of applying procedure to obj and the elements of list

apply invokes procedure, passing the first obj as the first argument, the second obj as the second argument, and so on for each object in obj , and passing the elements of list in order as the remaining arguments. Thus, procedure is called with as many arguments as there are objs plus elements of list.

apply is useful when some or all of the arguments to be passed to a procedure are in a list, since it frees the programmer from explicitly destructuring the list.

 (apply + '(4 5))  9 (apply min '(6 8 3 2 5))  2 (apply min 5 1 3 '(6 8 3 2 5))  1 (apply vector 'a 'b '(c d e))  #5(a b c d e) (define first   (lambda (l)     (apply (lambda (x . y) x)              l))) (define rest   (lambda (l)     (apply (lambda (x . y) y) l))) (first '(a b c d))  a (rest '(a b c d))  (b c d) 




The Scheme Programming Language
The Scheme Programming Language
ISBN: 026251298X
EAN: 2147483647
Year: 2003
Pages: 98

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net