;; standard (non-accumulator) way to sum the numbers in a list ;;; sum: list-of-number -> number ;;; produces the sum of the numbers in the list ;(define (sum alon) ; (cond [(empty? alon) 0] ; [(cons? alon) (+ (first alon) (sum (rest alon)))])) ;; alternative way, using an accumulator ;; sum-accum: list-of-number number -> number ;; produces the sum of the numbers in the list, keeping track of the total in sum-so-far (define (sum-accum alon sum-so-far) (cond [(empty? alon) sum-so-far ] [(cons? alon) (sum-accum (rest alon) (+ (first alon) sum-so-far))])) ;; function that calls the accumulator-style function, and initializes the accumulator ;;sum: list-of-number -> number ;; produces the sum of the numbers in the list (define (sum alon) (sum-accum alon 0)) ;; test case (check-expect (sum (list 4 9 2)) 15) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; largest-number: list-of-number (non-empty) -> number ;; returns the largest number in the list (define (largest-number alon) (largest-number-accum (rest 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) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; revers: list-of-number -> list-of-number ;; reverses the order of the numbers in a list (define (revers alon) (revers-accum alon empty)) ;; revers-accum: list-of-number list-of-number -> list-of-number ;; reverses the order of the numbers in a list, building the result in lsf (list-so-far) (define (revers-accum alon lsf) (cond [(empty? alon) lsf] [(cons? alon) (revers-accum (rest alon) (cons (first alon) lsf))])) ;; a second way to write the reverse function, without using accumulator-style programming ;; This solution turns out to be considerably less efficient than the accumulator-style solution ;; revers2: list-of-number -> list-of-number ;; reverses the order of the numbers in a list (define (revers2 alon) (cond [(empty? alon) empty] [(cons? alon) (append (revers2 (rest alon)) (list (first alon)))]))