[英]Monoid Bool in Haskell
Of course the data type is not exact, but is this how (more or less) the Monoid Bool
is implemented? 当然数据类型并不精确,但这是(或多或少)
Monoid Bool
的实现方式?
import Data.Monoid
data Bool' = T | F deriving (Show)
instance Monoid (Bool') where
mempty = T
mappend T _ = T
mappend _ T = T
mappend _ _ = F
If so/not, what is the reasoning for making Bool
's mappend
an OR
versus AND
? 如果是这样的话,是什么原因让
Bool
的mappend
成为OR
与AND
?
There are two possible Monoid
instances for Bool
, so Data.Monoid
has newtypes to distinguish which one we intend: Bool
有两个可能的Monoid
实例,因此Data.Monoid
有新的类型来区分我们打算使用哪一个:
-- | Boolean monoid under conjunction.
newtype All = All { getAll :: Bool }
deriving (Eq, Ord, Read, Show, Bounded, Generic)
instance Monoid All where
mempty = All True
All x `mappend` All y = All (x && y)
-- | Boolean monoid under disjunction.
newtype Any = Any { getAny :: Bool }
deriving (Eq, Ord, Read, Show, Bounded, Generic)
instance Monoid Any where
mempty = Any False
Any x `mappend` Any y = Any (x || y)
Edit: There are actually four valid instances as Ørjan notes 编辑:实际上有四个有效的实例,如Ørjan笔记
Your provided instance isn't a monoid. 您提供的实例不是幺半群。
mappend F mempty
mappend F T -- by definition of mempty
T -- by definition of mappend
so we've proven F <> mempty === T
, but for any monoid, x <> mempty === x
. 所以我们已经证明了
F <> mempty === T
,但对于任何幺半群, x <> mempty === x
。
The unit for Any
is False
, and the unit for All
is True
. Any
的单位为False
, All
的单位为True
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.