Print a list of lists row wise in Haskell

  Kiến thức lập trình

I’m trying to print a list of lists in Haskell. It’s something I’ve successfully done before for two sub lists but I can’t remember all the steps and I haven’t seen something for an arbitrary number of sub-lists. The list is of type [[Double]] where all sub-lists are of equal length.
With input [[1,2,3],[1,2,3],[1,2,3]] the output should be

1 1 1
2 2 2
3 3 3

My idea thus far is using mapM_. I would like to control the print using something like printf. However, this prints sub-list by sub-list, not index by index.

import Text.Printf ( printf )

print_row :: Double -> IO ()
print_row r = do
    printf "%9.6f" r

print_rows :: [[Double]] -> Int -> IO ()
print_rows r i = do
    mapM_ print_row (r !! i)

main :: IO ()
main = do
    let rs = [[1,2,3],[1,2,3],[1,2,3]]
        n  = length rs - 1
    mapM_ (print_rows rs) [0..n] 

LEAVE A COMMENT