11

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)))
Will Ness
  • 70,110
  • 9
  • 98
  • 181
user3294726
  • 201
  • 1
  • 3
  • 4

3 Answers3

12

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))
GoZoner
  • 67,920
  • 20
  • 95
  • 145
  • Ouch, hit by a sniper. Down voted w/o an explanation - on a CORRECT answer no less. Bring it on! – GoZoner Feb 12 '14 at 00:04
  • 2
    you're right, the answer seems correct. here ya go. :) Why ppl in [tag:scheme] don't upvote each other, I don't understand it. It's not like we have a large audience here. Could you show the definition of `zip` through? Or are you using a built-in? (well, obviously it's `(define (zip a b) (map list a b))`, but for the sake of completeness it should be inside the answer perhaps). – Will Ness Feb 15 '14 at 17:57
  • Thanks. The same user asked a question on implementing `zip`. See http://stackoverflow.com/questions/21688944/zip-function-in-racket-scheme – GoZoner Feb 15 '14 at 18:34
  • 1
    already did. :) this was assumed to be homework, so giving full code isn't advisable... :) ... so you mean you're using same `zip` here as you gave there? still perhaps it's better to include the code (or its skeleton) here as well. (?) – Will Ness Feb 15 '14 at 18:47
9

You can express it in terms of foldl:

(define (reduce f xs)
  (and (not (empty? xs)) (foldl f (first xs) (rest xs))))
Jack
  • 2,223
  • 13
  • 23
2
(define reduce
  (λ (f init ls)
    (if (empty? ls)
        init
        (reduce f (f init (first ls)) (rest ls)))))
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
abcd
  • 21
  • 1