The attempted solution uses list-ref
twice, which is not needed, and one of those calls does not have enough arguments: (list-ref M)
has the function taking only one argument, but it requires two arguments -- a list and an integer.
The list-ref
function will return an indexed element from an input list, so (list-ref '(1 2 3) 1)
will return 2
. Consider what map
will do here: the matrix is represented as a list of lists (a list of rows), i.e., as ((1 2 3) (2 3 4) (6 7 9))
. The map
function will act on the members of the input list, which are the lists (1 2 3)
, (2 3 4)
, and (6 7 9)
. By map
ping the list-ref
function over that input, you can take whichever element you want from the sublists. So, (map (lambda (row) (list-ref row 1)) '((1 2 3) (2 3 4) (6 7 9)))
would evaluate to (2 3 7)
, as desired.
Here is a function that lets you take any column from a matrix:
(define (nth-column M n)
(map (lambda (row) (list-ref row n)) M))
Sample interactions:
scratch.rkt> (define M '((1 2 3)
(2 3 4)
(6 7 9)))
scratch.rkt> (nth-column M 1)
'(2 3 7)
scratch.rkt> (nth-column M 0)
'(1 2 6)
scratch.rkt> (nth-column M 2)
'(3 4 9)