0

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

1 Answer 1

1

If there are arguments in lst to process, then you want to combine the first argument with the result of processing the rest of lst. But, with (f (f base (first lst)) (reduce f base (rest lst))) the posted code is combining the result of (f base (first lst)) with the result of processing the rest of lst. Since the test is using +, this means that at every step base is added to the next item of lst, and that sum is combined with the remainder of the computation.

Instead, just use f to combine the next element of lst with the result of reducing the rest of lst:

(define (reduce f base lst)
  (cond ((empty? lst) base)
        (else (f (first lst) (reduce f base (rest lst))))))
scratch.rkt> (reduce + 1 '(1 2 3))
7
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.