softshipper
softshipper

Reputation: 34081

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?

Upvotes: 2

Views: 248

Answers (1)

Anton Xue
Anton Xue

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

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

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

Upvotes: 5

Related Questions