;; sum: list-of-number -> number ;; sums the numbers in a list (define (sum alon) (cond [(empty? alon) 0] [(cons? alon) (+ (first alon) (sum (rest alon)))])) (check-expect (sum (list 3 4 5)) 12) ;; sum-accum: list-of-number number -> number ;; sum a list of numbers, keeping the running total in total (define (sum-accum alon total) (cond [(empty? alon) total] [(cons? alon) (sum-accum (rest alon) (+ total (first alon)))])) (check-expect (sum-accum (list 3 4 5) 0) 12) ;; sum2: list-of-number -> number ;; sums the numbers in a list (define (sum2 alon) (sum-accum alon 0)) (check-expect (sum2 (list 3 4 5)) 12) ;; largest-number: list-of-number -> number ;; returns the largest number in the list (define (largest-number alon) (largest-number-accum alon (first alon))) ;; largest-number-accum: list-of-number number -> number ;; determines the largest number in the list, keeping track of the largest seen ;; so far in largest (define (largest-number-accum alon largest) (cond [(empty? alon) largest ] [(cons? alon) (cond [(> (first alon) largest) (largest-number-accum (rest alon) (first alon))] [else (largest-number-accum (rest alon) largest)])])) (check-expect (largest-number (list 3 19 4 27 2)) 27) ;; long-words: list-of-string -> list-of-string ;; produces a list of words with more than 5 characters (define (long-words alos) (long-words-accum alos empty)) ;; long-words-accum: list-of-string list-of-string -> list-of-string ;; produces a list of words with more than 5 chars, keeping the list so far in long-list (define (long-words-accum alos long-list) (cond [(empty? alos) long-list] [(cons? alos) (cond [(> (string-length (first alos)) 5) (long-words-accum (rest alos) (cons (first alos) long-list))] [else (long-words-accum (rest alos) long-list)])])) ;; this test case fails, because accumulator-style programs produce the list of results in ;; reverse order ;;(check-expect (long-words (list "orange" "pear" "cantaloupe" "watermelon")) ;; (list "orange" "cantaloupe" "watermelon"))