edit AssocList by key

允我心安 提交于 2020-01-22 02:21:07

问题


I'm trying to build a recursive function that replaces the CellType by the Cell. Just like this:

> editBoard [((2,2),Mine),((2,3),Mine),((3,2),Mine)]((2, 4), Flag)

> [((2,2),Mine),((2,3),Flag),((3,2),Mine)]

This is what I have so far:

editBoard :: Board -> (Cell, CellType) -> Board
editBoard (Board ((x, y):xs)) (a, b) 
         | x == a = (Board ((x, b) : xs))
         | otherwise = ((x, y) : editBoard (Board xs) (a, b))

I keep getting an error that says

Couldn't match expected type ‘[(Cell, CellType)]’ with actual type ‘Board’

even though Board is defined as

newtype Board = Board [(Cell,CellType)] deriving(Eq)

What am I doing wrong?


回答1:


The signature of your function says you are returning a Board, but the otherwise clause will return a list:

editBoard :: Board -> (Cell, CellType) -> Board
editBoard (Board ((x, y):xs)) (a, b) 
         | x == a = (Board ((x, b) : xs))
         | otherwise = ((x, y) : editBoard (Board xs) (a, b))

I think however you make things too complicated. It might be better to make a helper function that works with a list of (Cell, CellType) objects, and returns such list, and let the editBoard wrap and unwrap the content:

editBoard :: Board -> (Cell, CellType) -> Board
editBoard (Board bs) xy@(x0, y0) = Board (go bs)
    where go :: [(Cell, CellType)] -> [(Cell, CellType)]
          go … = …

I leave implementing go as an exercise.



来源:https://stackoverflow.com/questions/59714767/edit-assoclist-by-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!