arrayshaskellrepa

How to stack arrays in repa (Haskell)


Suppose there are two 1-D arrays of the same length:

let x = fromListUnboxed (ix1 4) [1, 2, 3, 4]
let y = fromListUnboxed (ix1 4) [5, 6, 7, 8]

Now I would like to stack these two arrays into one 2-D array so that these arrays form the rows. How can I do it in repa?

Basically, I'm looking for an equivalent of numpy's row_stack:

>>> x = np.array([1, 2, 3, 4])
>>> y = np.array([5, 6, 7, 8])
>>> np.row_stack((x, y))
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

Note. The two arrays, x and y, come from outside, i.e. I cannot create the 2-D array from scratch.


Solution

  • As I mentioned in the initial comment, all you need is to reshape then append (both in Data.Array.Repa.

    ghci> let x' = reshape (ix2 4 1) x
    ghci> let y' = reshape (ix2 4 1) y
    ghci> z <- computeP $ x' `append` y' :: IO (Array U DIM2 Int)
    ghci> z
    AUnboxed ((Z :. 4) :. 2) [1,5,2,6,3,7,4,8]
    

    As for pretty-printing, repa isn't very good (likely because there is no good pretty printing for higher dimensions). Here is a one-line hack to display z

    ghci> putStr $ unlines [ unwords [ show $ z ! ix2 i j  |  i<-[0..3] ] | j<-[0..1] ]
    1 2 3 4
    5 6 7 8