我正在尝试制作一个井字游戏,我决定构建单元格(板的元素)和板的类型如下:
data Cell = X | O deriving (Show, Eq)
type Board = [[Maybe Cell]]
Run Code Online (Sandbox Code Playgroud)
这里,Nothing表示空单元格(Just X)和(Just O)分别表示用X和O填充的单元格.
我想将(Maybe Cell)定义为monoid,如下所示:
instance Monoid (Maybe Cell) where
mempty = Nothing
mappend Nothing x = x
mappend (Just x) _ = (Just x)
Run Code Online (Sandbox Code Playgroud)
和董事会作为另一个幺半群
instance Monoid Board where
mempty = [[Nothing, Nothing, Nothing]
,[Nothing, Nothing, Nothing]
,[Nothing, Nothing, Nothing]]
mappend = zipWith (zipWith mappend)
-- where the right-hand-side mappend is the addition on (Maybe Cell)
Run Code Online (Sandbox Code Playgroud)
我知道我可以在没有幺半群的情况下完全实现这一点,但我正在尝试探索这个领域,而这只是一种非常巧妙的方式来编写它.
我得到的问题是Maybemonoid实例已经定义GHC.Base如下:
instance Semigroup …Run Code Online (Sandbox Code Playgroud)