Search code examples
haskellmatrixrepa

Haskell / repa - is there a way to pretty-print matrices?


Using repa in haskell, is there a way to print matrices so they're nicely formatted with matrix rows being on separate lines (the default for most numerical computing environments like R or matlab)?

I could write one, but it seems like something that would already exist.

This type of output is unwieldy to interact with:

λ> foo
AUnboxed ((Z :. 3) :. 5) (fromList [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) 

Solution

  • This works for me. Maybe it's worth adding to repa or a repa-extras package?

    {-# LANGUAGE FlexibleInstances #-}
    
    module PrettyPrint where
    
    import Data.Array.Repa
    import Data.Array.Repa.Algorithms.Matrix
    
    import Text.PrettyPrint
    import Text.PrettyPrint.HughesPJClass
    
    instance (Source t a, Pretty a) => Pretty (Array t DIM1 a) where
     pPrint a = brackets $ hcat $ punctuate (comma <> space) elems
        where
         elems = [ pPrint (a!j) | i <- [0..n-1], let j = Z :. i ]
         Z :. n = extent a
    
    instance (Source t a, Pretty a) => Pretty (Array t DIM2 a) where
     pPrint a = vcat elems
       where
         elems = [ pPrint (slice a j) | i <- [0..n-1], let j = Any :. i :. All]
         Z :. n :. _m = extent a