haskellcartesian-productcartesian-coordinates

Returning a list of every possible coordinate in a grid of that width and height


So I am writing a function allCoords that returns a list of every possible coordinate in a grid of width w and height h Both width and height must be non-negative integers in order to return a sensible result.

Example: allCoords 3 2 should return [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)]

This is all I've got so far but I don't know how to even start writing the function

type GridCoord = (Int, Int)

allCoords :: Int -> Int -> [GridCoord]

Solution

  • You could do that using a list comprehension.

    [ (x,y) | x <- [0..1], y <- [0..2] ]
    

    Will give the list in your example.

    Your function would then need to be defined as:

    type GridCoord = (Int, Int)
    
    allCoords :: Int -> Int -> [GridCoord]
    allCoords height width = [ (x,y) | x <- [0..width-1], y <- [0..height-1] ]