简体   繁体   中英

Reduce function in Racket?

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)))

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))

You can express it in terms of foldl :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM