Reduce function in Racket?
functional-programming, racket, recursion, scheme
Solution
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))
Problem
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))) ```