0

I want to write a function that generates a list of tuples containing the coordinates of an n by n grid.

For example:

> genGrid 2
[(0,0),(0,1),(1,0),(1,1)]
> genGrid 3
[(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]

I know I can generate a diagonal by doing the following:

genDiagonal n = zip [0..] [0..n-1]

I am thinking there is a fairly simple way to do this, perhaps a variant of my diagonal function, but am coming up blank.

sschilli
  • 2,021
  • 1
  • 13
  • 33
  • 1
    `[(x, y) | x <- [0..n-1], y <- [0..n-1]]` for row-major, or `[(y, x) ...]` for column-major. – Mephy Apr 19 '16 at 01:08
  • Also see [this question](http://stackoverflow.com/questions/8029046/) which generates the exact desired output (although it is a different question). – Mephy Apr 19 '16 at 01:10
  • `grid d n = sequence $ replicate d [0..n]` will generate a `d` dimensional grid of size `n`. This can be partially evaluated to get a 2 dimensional grid `2dGrid = grid 2`. – Ben Campbell Apr 19 '16 at 03:02
  • 3
    this is also almost a duplicate of http://stackoverflow.com/questions/4119730/cartesian-product, which gives a bunch of alternate solns. My favorite is `(,) <$> [0..x] <*> [0..x]` – jamshidh Apr 19 '16 at 03:43

1 Answers1

5

The range function does this:

Data.Ix> range ((0, 0), (2, 3))
[(0,0),(0,1),(0,2),(0,3),(1,0),(1,1),(1,2),(1,3),(2,0),(2,1),(2,2),(2,3)]
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380