Haskell的Monoid Bool

时间:2014-10-27 04:15:05

标签: haskell monoids

当然数据类型并不准确,但这是(或多或少)实现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 

如果是/否,那么Bool mappend ORAND的对比是什么原因?

2 个答案:

答案 0 :(得分:15)

Monoid有两个可能的Bool个实例,因此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)

编辑:实际上有四个有效的实例,如Ørjannotes

答案 1 :(得分:3)

您提供的实例不是幺半群。

mappend F mempty
mappend F T  -- by definition of mempty
T            -- by definition of mappend

所以我们已经证明F <> mempty === T,但对于任何幺半群,x <> mempty === x

Any的单位为FalseAll的单位为True