打印出给定 x y 尺寸的网格坐标列表



我需要在给定宽度和高度 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 吗?蓄能器?那会是什么样子,因为累加器仍然让我感到困惑

编辑** 我已经尝试过列表理解,但我不确定如何组合。

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已经知道,您可以在lst1中删除它们,并像这样lst2

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]]

最新更新