Reputation: 34081
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?
Upvotes: 2
Views: 248
Reputation: 833
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.
Upvotes: 5