Reduce function in Racket?
Asked Answered
A

3

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)))
Aschim answered 10/2, 2014 at 21:26 Comment(1)
The sample output doesn't seem right, please check to see if it's correct. Also, post the implementation of zip.Testosterone
T
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))
Tread answered 10/2, 2014 at 22:34 Comment(4)
Ouch, hit by a sniper. Down voted w/o an explanation - on a CORRECT answer no less. Bring it on!Tread
you're right, the answer seems correct. here ya go. :) Why ppl in 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).Ninepins
Thanks. The same user asked a question on implementing zip. See #21689444Tread
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. (?)Ninepins
D
9

You can express it in terms of foldl:

(define (reduce f xs)
  (and (not (empty? xs)) (foldl f (first xs) (rest xs))))
Desiredesirea answered 8/8, 2014 at 20:6 Comment(0)
P
2
(define reduce
  (λ (f init ls)
    (if (empty? ls)
        init
        (reduce f (f init (first ls)) (rest ls)))))
Pianist answered 15/1, 2017 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.