首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >哈斯克尔。得到同样的邻居

哈斯克尔。得到同样的邻居
EN

Stack Overflow用户
提问于 2019-04-09 04:58:30
回答 1查看 265关注 0票数 1

我是最近开始学习Haskell的cs学生。我尽力在哈斯克尔找到解释的方法,但我还不能。我需要帮助。这是解释。内容有三种类型。

代码语言:javascript
复制
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。

代码语言:javascript
复制
-- 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

我做了一个“摩尔”列表,其中包含了所有的方向,但我不知道如何比较‘细胞’和‘邻居细胞’。我的想法是用另一种编程语言,

代码语言:javascript
复制
if (TheCell[X-1,Y] == TheCell)){
    stack ++;
    }
 ...
 ...
 ratio = stack / len(8);

我一直在寻找如何在Haskell中解释,但还没有找到。也许我的思维过程是错的。请以任何方式帮助我

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-09 05:41:43

代码语言:javascript
复制
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的(而不是“稀疏”表示,即。只有非空单元格的一维列表)那么ratio必须有一点不同。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55585360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档