Held Monday, October 23, 2000
Today we consider how to define local procedures using
;;; "Safely" sum a list of numbers. ;;; Parameters: ;;; A list of numbers. ;;; Returns: ;;; The sum of the list. ;;; Preconditions: ;;; The list contains only numbers [Verified] ;;; Postconditions: ;;; Does not affect the list. ;;; Crashes and burns with a helpful error message if the ;;; parameter is not a list. (define safe-sum (lambda (numbers) (cond ((not (list? numbers)) (error "safe-sum: given a non-list as a parameter")) ((not (all-numbers? numbers)) (error "safe-sum: given a list that includes non numbers")) (else (safe-sum-kernel numbers))))) ;;; Sum a list of numbers ;;; Parameters: ;;; A list of numbers ;;; Returns: ;;; The sum of the list ;;; Preconditions: ;;; The list contains only numbers [Unverified] ;;; Postconditions: ;;; Does not affect the list. (define safe-sum-kernel (lambda (numbers) (if (null? numbers) 0 (+ (car numbers) (safe-sum-kernel (cdr numbers)))))) ;;; Determine if a list contains only numbers. ;;; Parameters: ;;; A list ;;; Returns: ;;; #t if the list contains no non-numbers. ;;; #f otherwise ;;; Preconditions: ;;; The parameters must be a list [Unverified] (define all-numbers? (lambda (lst) (or (null? lst) (and (number? (car lst)) (all-numbers? (cdr lst))))))
safe-sum-kernelshould really be local to
all-numbers?is more generally useful, and can be globally accessible.
When you're done with this outline, see the corresponding reading.
Thursday, 24 August 2000
Monday, 24 October 2000
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2000F/Outlines/outline.30.html
Source text last modified Mon Oct 23 10:51:08 2000.
This page generated on Tue Oct 24 10:55:11 2000 by Siteweaver. Validate this page's HTML.
Contact our webmaster at firstname.lastname@example.org