1

I am trying to write a function that takes a matrix (represented as a list of lists) and adds the elements down the columns and returns a vector (represented as a list):

Example:

    (define sample
      '((2 6 0 4)
        (7 5 1 4)
        (6 0 2 2)))

should return '(15 11 3 10).

I was trying to use the (list-ref) function twice to obtain the first element of each column with no luck. I am trying something like:

(map (lambda (matrix) ((list-ref (list-ref matrix 0) 0)) (+ matrix))
soegaard
  • 30,661
  • 4
  • 57
  • 106
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
  • 3
    Obligatory reference to [Transpose a matrix in racket (list of lists](http://stackoverflow.com/q/30775032/1281433). Summing the columns just uses **+** instead of **list**. – Joshua Taylor Oct 10 '15 at 01:58

1 Answers1

3

The solution is simple if we forget about the indexes and think about higher-order procedures, try this:

(define sample
  '((2 6 0 4)
    (7 5 1 4)
    (6 0 2 2)))

(apply map + sample)
=> '(15 11 3 10)

Explanation: map can take multiple lists as arguments. If we apply it to sample (which is a list of lists) and pass + as the procedure to do the mapping, it'll take one element from each list in turn and add them, producing a list with the results - effectively, adding all the columns in the matrix.

Óscar López
  • 232,561
  • 37
  • 312
  • 386