Transpose a matrix in racket (list of lists

前端 未结 3 505
既然无缘
既然无缘 2020-12-10 18:26

I got a list of lists in racket and have to transpose them.

(: transpose ((list-of(list-of %a)) -> (list-of (list-of %a))))

(check-expect (transpose (lis         


        
相关标签:
3条回答
  • 2020-12-10 18:59

    for/list can be used sequentially to create a list of lists with transposed items:

    (define (transpose_ lol)                    ; lol is list of lists
      (for/list ((i (length (list-ref lol 0)))) ; loop for length of first inner list
        (for/list ((il lol))                    ; for each inner list (il)
          (list-ref il i))))                    ; get its item
    

    Testing:

    (transpose_ (list (list 1 2 3)
                      (list 4 5 6)))
    

    Output:

    '((1 4) (2 5) (3 6))
    
    0 讨论(0)
  • 2020-12-10 19:05
    (define (tr ls)
      (if (empty? (car ls)) empty
     (if (null? ls) empty
         (cons (map car ls) (tr (map cdr ls))))))
    
    0 讨论(0)
  • 2020-12-10 19:16

    The simplest definition of transpose is:

    (define (transpose xss)
      (apply map list xss))
    

    Why does it work?

      (apply map list '((a b) (d e))
    = (apply map List '((a b) (d e))    ; use List rather than list
    = (map List '(a b) '(d e))
    = (list (List 'a 'd) (List 'b e))
    = '((a d) (b e))
    

    Here List is spelled with capital letters only to show which list was given by the user and which was produced by map.

    Here is a less "clever" solution. It uses that the first column of a matrix becomes the first row in the transposed matrix.

    (define transpose
      (lambda (xss)
        (cond
          [(empty? xss)         empty]
          [(empty? (first xss)) empty]
          [else                 (define first-column   (map first xss))
                                (define other-columns  (map rest  xss))
                                (cons first-column
                                      (transpose other-columns))])))
    
    0 讨论(0)
提交回复
热议问题