我是最近开始学习Haskell的CS学生。 我尽力寻找在Haskell中进行口译的方法,但还没有。我需要帮助。这是解释。内容共有三种。
type Coord = (Int, Int)
-- Type-definition of a Cell: it is just a coordinate and an optional
AgentType.
-- Note: the agent type is optional and is Nothing in case the cell is
empty.
type Cell = (Coord, Maybe AgentType)
-- data definition for the agent types
data AgentType
= Red -- ^ Red agent
| Green -- ^ Green agent
| Blue -- ^ Blue agent
deriving (Eq, Show) -- Needed to compare for equality, otherwise would need to implement by ourself
每个单元格都有一个内容(可以是红色,绿色或蓝色)或为空。我正在尝试寻找方方面面内容相同的邻居,包括对角线方式,总数为8。如果40%的单元格邻居与该单元格相同,则返回true。
-- Returns True if an agent on a given cell is happy or not
isHappy :: Double -- ^ The satisfaction factor
-> [Cell] -- ^ All cells
-> Cell -- ^ The cell with the agent
-> Bool -- ^ True in case the agent is happy, False otherwise
isHappy ratio cs c
| ratio < 0.4 = False
| otherwise = True
where
moore = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y+1),(x+1,y+1),(x+1,y),(x+1,y-1),(x,y-1)]
-- here is where I got stuck
我制作了一个“摩尔”列表,其中包含所有方向,但是我不确定如何将“细胞”与“邻居[细胞]”进行比较。 我的想法是采用另一种编程语言,
if (TheCell[X-1,Y] == TheCell)){
stack ++;
}
...
...
ratio = stack / len(8);
我一直在寻找如何在Haskell中进行解释,但尚未找到它。也许我的思维过程是错误的。请以任何方式帮助我
答案 0 :(得分:1)
data Cell = Cell Coord (Maybe AgentType)
inBounds :: Coord -> Bool
inBounds (x,y) = 0 <= x && x <= fst worldSize
&& 0 <= y && y <= snd worldSize
isHappy cs (Cell (x,y) a) = ratioSameNeighbours >= 0.4
where neighbourCoords = filter inBounds [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y+1),(x+1,y+1),(x+1,y),(x+1,y-1),(x,y-1)]
sameNeighbours = filter ((\(Cell p ma) -> p `elem` neighbourCoords && ma == a) cs
ratioSameNeighbours = fromIntegral (length sameNeighbours) / fromIntegral (length neighbours)
您所说的话仍然有点不足(例如,一个空单元格可以开心吗?),但这是一个开始。如果假定输入单元格数组是2D(而不是“稀疏”表示,即仅是非空单元格的1D列表),则ratio
必须有所不同。