9
votes

I'm stuck 5 days with this task in Racket, does anybody know how can I approach it?

Given a function of arity 2 and a list of n elements, return the evaluation of the string function of all the elements, for example:

>(reduce + '(1 2 3 4 5 6 7 8 9 10))

55

> (reduce zip '((1 2 3) (4 5 6) (7 8 9)))
'((1 (4 7)) (2 (5 8)) (3 (6 9)))
3
The sample output doesn't seem right, please check to see if it's correct. Also, post the implementation of zip. - Óscar López

3 Answers

12
votes

Here you go.

(define (reduce func list)
  (assert (not (null? list)))
  (if (null? (cdr list))
      (car list)
      (func (car list) (reduce func (cdr list)))))

Tests:

> (reduce + '(1 2 3 4 5 6 7 8 9 10))
55
> (reduce zip '((1 2 3) (4 5 6) (7 8 9)))
((1 (4 7)) (2 (5 8)) (3 (6 9)))

For completeness, an implementation for zip (one that assumes two lists and that your lists are all the same length) is:

(define (zip l1 l2) (map list l1 l2))
7
votes

You can express it in terms of foldl:

(define (reduce f xs)
  (and (not (empty? xs)) (foldl f (first xs) (rest xs))))
0
votes
(define reduce
  (λ (f init ls)
    (if (empty? ls)
        init
        (reduce f (f init (first ls)) (rest ls)))))