Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

10 reduce Write a function called reduce that applies a combiner function of 2 o

ID: 3625291 • Letter: 1

Question

10 reduce
Write a function called reduce that applies a combiner function of 2 operands to successive elements of a
list and accumulates the result in a single scalar value. The combiner should first be applied to the first two
elements to get an initial accumulator value, and then the combiner should be applied to the accumulator
and successive elements of the list until the list is exhausted and the function returns the final accumulated
value. For example,
> (reduce + ’( 1 2 3 4 5))
15
> (reduce * ’( 1 2 3 4 5))
120
Show how to define factorial in terms of reduce.

Explanation / Answer

(define (reduce-helper op total lst)
(if (null? lst) total
    (reduce-helper op (op total (car lst)) (cdr lst))))

(define (reduce op lst)
(reduce-helper op (op (car lst) (cadr lst)) (cddr lst)))

----------
part 2, defining factorial
range is a helper function that returns the list of numbers from n down to 1, for instance (range 3) equals (list 3 2 1)

(define (range n)
(if (= n 1) (list 1)
     (cons n (range (- n 1)))))

(define (factorial n)
(reduce * (range n)))