简体   繁体   中英

Monoid Bool in Haskell

Of course the data type is not exact, but is this how (more or less) the Monoid Bool is implemented?

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 ?

There are two possible Monoid instances for Bool , so Data.Monoid has newtypes to distinguish which one we intend:

-- | 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

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 .

The unit for Any is False , and the unit for All is True .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM