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

问题描述 投票:2回答:1

我是最近开始学习Haskell的学生。我尽力找到在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

我创建了一个包含所有方向的'moore'列表,但我不确定如何比较'the Cell'和'neighbors [Cell]'。我的想法是用另一种编程语言,

if (TheCell[X-1,Y] == TheCell)){
    stack ++;
    }
 ...
 ...
 ratio = stack / len(8);

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

haskell
1个回答
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必须有点不同。

© www.soinside.com 2019 - 2024. All rights reserved.