打印出给定 x y 维度的网格坐标列表

Printing out a list of coordinates of a grid given x y dimensions

我需要列出给定宽度和高度 x y 的网格坐标。我最初尝试过这样的事情

allCoords :: Int -> Int -> [GridCoord]
allCoords x y 
| x <= 0 || y <= 0 = error "allCoords: Grid dimensions must have positive Integers"
| 0 <- x, 0 <- y = [(0,0)]
| 0 <- x = grid 0 y 
| otherwise = grid x y ++ allCoords (x-1) y 
where 
   grid :: Int -> Int -> [GridCoord]
   grid x 0 = [(x,0)]
   grid x y = (x,y):grid x (y-1)

这确实给了我

的输出
allCoords 3 2
[(3,2),(3,1),(3,0),(2,2),(2,1),(2,0),(1,2),(1,1),(1,0),(0,2),(0,1),(0,0)]

但是预期的输出是

[(0,0),(1,0),(2,0),(0,1),(1,1),(2,1)].

我曾想过可以通过创建两个函数来使用列表理解,将所有 x 元素放入一个列表,将所有 y 元素放入一个列表,然后进行笛卡尔积,但认为这有点麻烦。

我现在意识到 x 会增加,而 y 保持不变,一旦我们达到 x 的 mmax,我们就会增加 y。这需要我保存一个变量来保存 x 和 y 的最大值,因为我们需要将当前 x 与它们进行比较。我现在甚至不知道如何开始,我更想寻找提示而不是写出代码以便我学习。我知道我需要一盒 x 但我应该使用 foldl 吗?蓄能器?那会是什么样子,因为累加器仍然让我感到困惑

编辑** 我试过 List Comprehension,但我不确定如何组合。

allCoords :: Int -> Int -> [GridCoord]
allCoords x y 
| x<= 0 || y <=0 = error "allCoords: Grid dimensions must have positive Integers"
| otherwise = lst1 ++ lst2
where 
 lst1 x = [(x,0) | x <- [0..x-1]]
 lst2 y = [(0,y) | y <- [0..y-1]]

但是它为 Lst2 抛出了一个错误。我可以这样结合吗?我还尝试将两个 lst 放在不同的函数中,这会引发类型声明

的错误

您的尝试非常接近。

您收到的错误是因为 lst1lst2 需要参数,但您没有在 lst1 ++ lst2 中向它们传递任何参数。由于 xy 是已知的,您可以像这样在 lst1lst2 中删除它们:

allCoords :: Int -> Int -> [GridCoord]
allCoords x y 
    | x<= 0 || y <=0 = error "allCoords: Grid dimensions must have positive Integers"
    | otherwise = lst1 ++ lst2
  where 
         lst1 = [(x,0) | x <- [0..x-1]]
         lst2 = [(0,y) | y <- [0..y-1]]

但是,此函数现在为您提供 [(0,0),(1,0),(2,0),(0,0),(0,1)],因此 xy 始终为 0。要组合这些值,您只需在单行列表理解中生成元组。

allCoords :: Int -> Int -> [GridCoord]
allCoords x y 
    | x<= 0 || y <=0 = error "allCoords: Grid dimensions must have positive Integers"
    | otherwise = [(x,y) | y <- [0..y-1], x <- [0..x-1]]