7

Today I tried to reduce a list of functions trough monoid typeclass but the resulting function expects its argument to be an instance of Monoid for some reason.

GHCI tells me that the type of mconcat [id, id, id, id] is Monoid a => a -> a. Yet I would expect it to be a -> a.

What is happening?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Ford O.
  • 1,394
  • 8
  • 25

1 Answers1

12

You're using this instance:

instance Monoid b => Monoid (a -> b) where
    mempty _ = mempty
    mappend f g x = f x `mappend` g x

which is more general because it doesn't require endomorphisms (i.e. a -> a). To get the instance you were expecting, you can wrap your functions in Endo:

appEndo (mconcat [Endo id, Endo id, Endo id, Endo id])

or

appEndo $ mconcat $ fmap Endo [id, id, id, id]
user2297560
  • 2,953
  • 1
  • 14
  • 11