Glimmer Labs

Exercise: Finding the Largest Value

Here's a Scheme procedure that finds the smallest value in a list of numbers.

(define (smallest lst)
  ; If the list has only one element
  (if (null? (cdr lst))
      ; That one element is the smallest
      (car lst)
      ; Otherwise, use the smaller of the first element and
      ; the smallest remaining element
      (smaller (car lst) (smallest (cdr lst)))))

(define (smaller val1 val2)
  (if (< val1 val2) val1 val2))

1. Test those procedures to make sure that they work as you'd expect.

2. Write and test a Scheme procedure that finds the largest value in a list of procedures.

As you may have observed, smallest and largest are surprisingly similar, differing only in their use of a procedure to select between two values and the procedure used on the rest of the list. We can perhaps phrase the procedure more generally as

(define (best lst better)
  ; If the list has only one element
  (if (null (cdr? lst))
      ; Then that value is the best
      (car lst)
      ; Otherwise, use the better of the first element and the
      ; best remaining element
      (better (car lst) (best (cdr lst) better))))

3. Test best using a list of numbers and smaller as parameters.

4. Test best using a list of numbers and larger as parameters.

5. Write a closer-to-100 procedure that, given two values, returns the one that is closer to 100.

6. Using best and closer-to-100, find the value in a list of numbers that is closest to 100.


This document was generated by Siteweaver on Fri Sep 10 10:16:20 2004.
The source to the document was last modified on Tue Aug 20 16:48:08 2002.
This document may be found at http://www.cs.grinnell.edu/~rebelsky/Glimmer/Sorting/largest.html.

You may wish to validate this document's HTML ; Valid CSS! ; Check with Bobby

Glimmer Labs: The Grinnell Laboratory for Interactive Multimedia Experimentation & Research
glimmer@grinnell.edu