问题
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