通过键编辑AssocList [英] edit AssocList by key

查看:43
本文介绍了通过键编辑AssocList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个递归函数,该递归函数将CellType替换为Cell.就是这样:

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

我不断收到错误消息

无法匹配预期的类型‘[(Cell, CellType)]’ 实际类型为‘Board’

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

即使董事会被定义为

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

我在做什么错了?

推荐答案

函数的签名表明您正在返回Board,但是otherwise子句将返回一个列表:

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

但是我认为您会使事情变得太复杂了.最好创建一个与(Cell, CellType)对象列表配合使用并返回该列表,然后让editBoard包装和拆开内容的辅助函数:

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 … = …

我将实施go留作练习.

这篇关于通过键编辑AssocList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆