Print out a Zig-Zag Matrix in Haskell My task is to code something that prints out this:



This is what I have done so far.

diag matrix = diag2 [] [] matrix where
 diag2 []  []           []       = []      
 diag2 xss []           (zs:zss) =     diag2 []       (reverse $ zs:xss) zss
 diag2 xss ((y:ys):yss) zss      = y : diag2 (ys:xss) yss                zss  
 diag2 xss ([]    :yss) zss      =     diag2 xss      yss                zss
 diag2 xss []           []       =     diag2 []       (reverse xss)      []


Is there an easier way to code this?  Also, how can I solve it if this is a very big matrix?
One inefficiency of your solution is that is calls reverse. This means that it will have to traverse an entire row. It also means it won't work with infinite lists.

The best implementation I've found is Data.Universe.Helpers.diagonals from the universe-base package.

It can even operate on an infinite list of infinite lists:

import Data.Universe.Helpers
import Control.Monad

mat = [ [i..] | i &lt;- [1..] ]

example n = forM_ (take n $ diagonals mat) $ print


e.g.:

ghci&gt; example 4
[1]
[2,2]
[3,3,3]
[4,4,4,4]


More info available at this SO answer: https://stackoverflow.com/a/32469565/866915