CSC 153 | Grinnell College | Spring, 2005 |
Computer Science Fundamentals | ||
Laboratory Exercise | ||
This laboratory exercise introduces the concept of procedures with varying numbers of parameters and provides experience writing such procedures.
Consider the following procedure display-line which prints as many values as desired on a line:
(define display-line (lambda values (let loop ((lst values)) (if (null? lst) (newline) (begin (display (car lst)) (loop (cdr lst)) ) ) ) ) )
Apply display-line to several other expressions to check what it prints. For example, try the following:
(display-line "To" "Be" "Or" "Not" 2 "B") (display-line "Going" "Going" "Gone") (display-line "Countdown:" 5 4 3 2 1 "Done") (display-line) ;;; apply display-line to the null list
This version of display-line prints all text together without spaces. Modify the code, so that one space is printed between each value specified for display-line. Thus, the first sample run above should print:
To Be Or Not 2 B
A second version of display-line prints out the items separated by a specified string. This is illustrated in the following code:
(define display-line (lambda (separator . element-list) (let loop ((lst element-list)) (cond ((null? lst) (newline)) ((null? (cdr lst)) (display (car lst)) (newline)) (else (display (car lst)) (display separator) (loop (cdr lst))) ) ) ) )
Check the correctness of this code by running it with the above examples. Describe how the result is formatted in each case. What happens when this version of display-line is run with no parameters? What happens when only 1 parameter is given?
Note that in the definition, a space was left on each side of the dot in
(separator . element-list). What happens if these spaces
are removed to yield (separator.element-list)? Explain why
you think this result is obtained.
Discuss why you think the condition (null? (cdr lst)) appears in this procedure.
This procedure has the disadvantage that both (null? lst) and (null? (cdr lst)) will be evaluated each time loop is called recursively. Can you revise this procedure (perhaps inserting some code before the let), so that only one condition will be tested during the recursion.
The reading for this lab observed that the dot notation can be used to specify any number of initial values. Thus,
(first-value second-value . remaining-values)
gives explicit bindings for two parameters, with any further parameters collected on a list for remaining-values.
(increasing? 2) ==> #t (increasing? 2 6 10 24 129) ==> #t (increasing? 6 2 10 24 129) ==> #f (increasing? 2 6 10 129 24) ==> #f
This document is available on the World Wide Web as
http://www.walker.cs.grinnell.edu/courses/153.sp05/labs/lab-variable-arity.shtml
created March 22, 1997 last revised February 3, 2005 |
![]() ![]() |
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |