Monoid Bool in Haskell

Of course, the data type is not exact, but how to implement it (more or less) 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 / no, what is the reason for creating Bool mappenda ORcompared to AND?

+4
source share
2 answers

There are two possible instances Monoidfor Bool, so it Data.Monoidhas new types to distinguish the one we intend to:

-- | 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, for example, Ørjan notes

+13
source

Your provided instance is not a monoid.

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

therefore we proved F <> mempty === T, but for any monoid x <> mempty === x.

Any False, All - True.

+3

All Articles