【问题标题】:List Grid Elements列出网格元素
【发布时间】:2011-05-14 04:30:40
【问题描述】:

我在这部分作业中取得了一些进展,但在下面附上了我所做的部分代码:

module Grid where

data State = On | Off deriving (Eq, Show)


next :: State -> State
next On = Off
next Off = On

type Row = [State]
type Grid = [[State]]
type Point = (Int,Int)

initialRow      :: Int -> Row
initialRow w    = replicate w Off


updateRow :: Row -> Int -> Row
updateRow  (r:rs) x 
    | x==0        = next r:rs
    | otherwise   = r : (updateRow rs (x-1))

update :: Grid -> Point -> Grid
update [[]] (x,y)       =   [[]]
update [(g:gs)] (x,y)   =   [(updateRow (g:gs) x)]

如上面最后一行所示,当 x = any Int 时,我已经设法让更新工作,如下所示(第 x 个元素倒置) - ghci。

*Grid> update [[Off,Off,Off,Off]] (2,0)
[[Off,Off,On,Off]]
*Grid> 

然而,当我尝试使用多个列表(例如这样)或选择列表中的某个列表来更新第 x 个元素时,这一切都没有解决:

*Grid> update [[Off,Off,Off,Off],[Off,Off,Off,Off]] (2,0)
*** Exception: Grid.hs:(24,0)-(25,47): Non-exhaustive patterns in function update

我似乎无法在此函数中“概括”公式。

我还必须遵循这个类型约定:

updateRow :: Grid -> Point -> Grid

基本上,我想做的是从这样的东西更新......

[[Off,Off,Off,Off],
 [Off,Off,Off,Off],
 [Off,Off,Off,Off],
 [Off,Off Off,Off]]

到这里:

[[Off,Off,Off,Off],
 [Off,Off,**On**,Off],
 [Off,Off,Off,Off],
 [Off,Off Off,Off]]

其中“x”是元素的值,“y”是列表 IYGWIM 中列表的值。

提前致谢。

【问题讨论】:

  • 你定义data Grid = [Row]可能会更清楚,相当于data Grid = [[State]]

标签: list haskell element variable-assignment


【解决方案1】:
update :: Grid -> Point -> Grid
update [[]] (x,y)       =   [[]]

这会检查包含空列表的列表。

update [(g:gs)] (x,y)   =   [(updateRow (g:gs) x)]

这会检查包含一个列表的列表,后者包含至少一个元素(绑定到变量 g)。

您要检查包含多个列表的列表。

图案应如下所示:

update :: Grid -> Point -> Grid
update [[]] (x, y)       = [[]]
update (row:rows) (x, 0) = updateRow row x : rows
update (row:rows) (x,y)  = -- I'll let you fill this, notice the 0 on the previous line

记住Grid 只是Rows 的列表。

第二行现在的意思是“如果你想更新这个网格的第0行,那么更新第一行”,最后一行应该是“如果你想更新这个网格的第y行,那么离开第一行”一个原样,并递归更新其余行”(当然,必须在递归调用中相应地更改 y)。

【讨论】:

    【解决方案2】:

    这里是解决方案。经过一番思考,我得出了以下内容并填写了上述“模式”的最后一行:

    ...
    update        (g:gs)  (x,y) =  g : update gs (x,(y-1))
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 2021-05-06
      • 1970-01-01
      • 2022-12-31
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2013-08-20
      相关资源
      最近更新 更多