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)))
You can express it in terms of foldl
:
(define (reduce f xs)
(and (not (empty? xs)) (foldl f (first xs) (rest xs))))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With