Luiz Miranda
Luiz Miranda

Reputation: 128

Sum matrix Racket

I'm trying to do a function in Racket that sum 2 matrix, using map and apply, the problem is that I only used map like this

(define (sumM x y) (map(lambda (x y) (map + x y)) x y)) (sumM '((10 10 10) (5 5 5)) '((1 1 1) (2 2 2)))

Which it gives me: (sumM '((10 10 10) (5 5 5)) '((1 1 1) (2 2 2))) ->'((11 11 11) (7 7 7))

but the thing is: I want just the result, something like 54 ¿How can I use the apply to get the 54 and not the result matrix?

Upvotes: 0

Views: 631

Answers (1)

Óscar López
Óscar López

Reputation: 236004

Try this:

(define (sumM x y)
  (+ (apply + (map (lambda (sl) (apply + sl)) x))
     (apply + (map (lambda (sl) (apply + sl)) y))))

It works for lists of lists of arbitrary length, finding the total sum of all its elements. For example:

(sumM '((10 10 10) (5 5 5)) '((1 1 1) (2 2 2)))
=> 54

Upvotes: 2

Related Questions