简体   繁体   中英

Monoid how to use mempty

I have following datatype, that is implemented in Monoid typeclass:

data Optinal a = 
    Nada
  | Only a
  deriving (Eq, Show)

instance Monoid a => Monoid (Optinal a) where
  mempty = Nada
  mappend Nada (Only a) = Only a
  mappend (Only a) Nada = Only a
  mappend Nada Nada = Nada
  mappend (Only a) (Only b) = Only (mappend a b)  

My question is, how to use mempty function?

The mempty in a Monoid defines the "unit" element. One particular scenario in which it might be used is if we had a function that aggregates over a list of Monoid s:

aggregate :: (Monoid a) => [a] -> a
aggregate [] = mempty
aggregate (x:xs) = x `mappend` aggregate xs

Remember that Monoid s are an abstraction over common forms of computation. When you write general functions for Monoid s, that's where mempty may show up.

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