haskellmonoidssemigroup

Could not deduce (Semigroup (TimedEvents a))


I am trying to compile the code found here using stable-aarch64-apple-darwin. I am getting the below error:

    src/Observations.hs:77:10: error:
        • Could not deduce (Semigroup (TimedEvents a))
            arising from the superclasses of an instance declaration
          from the context: Monoid a
            bound by the instance declaration at src/Observations.hs:77:10-43
        • In the instance declaration for ‘Monoid (TimedEvents a)’
       |
    77 | instance Monoid a => Monoid (TimedEvents a) where
       |          ^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This is the relevant part of the code:

newtype TimedEvents a = TEs [(Time, a)]
  deriving (Show, Read, Eq)

unTEs :: TimedEvents a -> [(Time, a)]
unTEs (TEs x) = x

instance Functor TimedEvents where
  fmap f (TEs tes) = TEs [ (t,f e) | (t,e) <- tes ]

instance Monoid a => Monoid (TimedEvents a) where
  mempty        = TEs []
  mappend as bs =
      fmap mappendMergeResult (mergeEvents as bs)
    where
      mappendMergeResult (OnlyInLeft  a)   = a
      mappendMergeResult (InBoth      a b) = a `mappend` b
      mappendMergeResult (OnlyInRight   b) =             b

I know next to nothing about Haskell, I am just trying to build the code so I can use the binary. Any hints on how to resolve this?


Solution

  • Since base-4.9, a Monoid [Hackage] is a "subclass" of Semigroup [Hackage], you thus implement this as:

    instance Semigroup a => Semigroup (TimedEvents a) where
      as <> bs =
        fmap mappendMergeResult (mergeEvents as bs)
        where
          mappendMergeResult (OnlyInLeft a) = a
          mappendMergeResult (InBoth a b) = a <> b
          mappendMergeResult (OnlyInRight b) = b
    
    instance Semigroup a => Monoid (TimedEvents a) where
      mempty = TEs []

    The mappend definition thus has been renamed (<>) and is defined on the Semigroup class.