Producing higher dimensional lists in Haskell

Viewed 63

I wrote a Haskell function to generate a list of tuples.

defineIndices :: Int -> Int -> [(Int,Int)]
defineIndices n m = [(i,j) | i <- [1..n], j <- [1..m]]

The function has the following behaviour.

λ> defineIndices 2 3
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3)]

It turns out that I require the function which behaves as the following:

λ> defineIndices2D 2 3
[[(1,1),(1,2),(1,3)],[(2,1),(2,2),(2,3)]]

In which defineIndices2D returns a list of list of (Int,Int) with dimensions n*m. I am a little bit stuck here, and I was wondering how my existing solution could be altered to produce a list of a higher order.

My end goal is to generate a list of x,y indices to use as the key for values in a Data.Map Map.

1 Answers

You can nest list comprehension, you thus make an outer list comprehension which will enumerate over the value for m, and you each time yield a list you produce with another list comprehension expression:

defineIndices2D :: Int -> Int -> [[(Int,Int)]]
defineIndices2D n m = [ [(i,j) | j <- [1..m]] | i <- [1..n]]

For a 2×3 grid, this thus produces:

Prelude> defineIndices2D 2 3
[[(1,1),(1,2),(1,3)],[(2,1),(2,2),(2,3)]]
Related