Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)))
like image 651
user3294726 Avatar asked Feb 10 '14 21:02

user3294726


2 Answers

You can express it in terms of foldl:

(define (reduce f xs)
  (and (not (empty? xs)) (foldl f (first xs) (rest xs))))
like image 67
Jack Avatar answered Oct 13 '22 01:10

Jack


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))
like image 12
GoZoner Avatar answered Oct 13 '22 03:10

GoZoner