简体   繁体   中英

How do I use a monoid instance of a function?

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?

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 (ie 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM