Search code examples
haskellmonadsmonoids

Haskell data type Counts for State Monad


How can I use the following data type for a Monoid instance of it?

data Counts = Counts {
    binds   :: Int,
    returns :: Int,
    gets    :: Int,
    puts    :: Int
} deriving (Eq, Show)

E.g. I figured something like:

mempty  = Counts { 0, 0, 0, 0 }
(Counts { b, r, g, p }) mappend (Counts { b', r', g', p' })  = Counts { (b + b'), (r + r'), (g + g'), (p + p') }

But that gives me a parse error on '0'... Maybe I'm doing it totally wrong and misunderstanding the data type / monoid, but I cannot figure it out. If anyone could help me out it'd be much appreciated!

Best regards, Skyfe.


Solution

  • This works:

    Counts 0 0 0 0
    

    This works:

    Counts {binds = 0, returns = 0, gets = 0, puts = 0}
    

    This does not work:

    Counts {0, 0, 0, 0}
    

    You either have to put the brackets and the field names, or you leave the brackets out completely. One or the other.

    Other than that, your approach looks sane. You just have your record syntax messed up.