My task is to implement a reduce procedure that takes a function that adds, or multiplies, or divides, each number in a list. I am stuck with the argument base. I have been able to check through the list of numbers and apply the function passed as argument. However, in the recursive call, I don't know how to handle the base number. I don't want the recursion to take into account the argument base in every call (base could be any number).
Here is what I have been able to do:
(define (reduce f base lst)
(cond ((empty? lst) base)
(else (f (f base (first lst)) (reduce f base (rest lst))))))
When base is 0 it passes the test for addition:
> (test (reduce + 0 '(1 2 3)) 6)
good (reduce + 0 '(1 2 3)) at line 3
expected: 6
given: 6
However, when base is 1, the test fails because base is added in the recursion call every time:
> (test (reduce + 1 '(1 2 3)) 7)
bad (reduce + 1 '(1 2 3)) at line 13
expected: 7
given: 10