List 列出网格元素
我在这部分作业中取得了一些进展,但附上了我已完成的部分代码:List 列出网格元素,list,haskell,element,variable-assignment,List,Haskell,Element,Variable Assignment,我在这部分作业中取得了一些进展,但附上了我已完成的部分代码: 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 ini
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=anyint时的更新,如下所示(将xth元素倒置)-ghci
但是,当我尝试使用多个列表(如此)或选择列表中的某个列表以更新xth元素时,这一切都不顺利:
*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
在这个函数中,我似乎无法对公式进行“genralise”
我还必须遵循这种类型的约定:
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中列表的值
提前谢谢
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
只是一个行的列表
第二行现在表示“如果要更新此网格的第0行,则更新第一行”,最后一行应表示“如果要更新此网格的第yth行,则保持第一行不变,并递归更新其余行”(当然,在递归调用中必须相应地更改y).这是解决方案。经过一番思考,我得出以下结论,并填写了上述“模式”的最后一行:
...
update (g:gs) (x,y) = g : update gs (x,(y-1))
如果您定义datagrid=[Row]
,您可能会更清楚,这相当于datagrid=[[State]]]
...
update (g:gs) (x,y) = g : update gs (x,(y-1))