How to use a monoid function instance?

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

GHCI tells me that type mconcat [id, id, id, id]is equal Monoid a => a -> a. But I expect it to be a -> a.

What's happening?

+4
source share
1 answer

You are 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 does not require endomorphisms (i.e. a -> a). To get the instance you expected, 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]
+8
source

Source: https://habr.com/ru/post/1678462/


All Articles