简体   繁体   English

如何使用函数的monoid实例?

[英]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. 今天我尝试通过monoid类型类减少函数列表,但是由于某种原因,结果函数期望它的参数是Monoid的一个实例。

GHCI tells me that the type of mconcat [id, id, id, id] is Monoid a => a -> a . GHCI告诉我mconcat [id, id, id, id]Monoid a => a -> a Yet I would expect it to be a -> a . 但我希望它是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 ). 这更通用,因为它不需要内同胚(即a -> a )。 To get the instance you were expecting, you can wrap your functions in Endo : 要获得您期望的实例,您可以将您的函数包装在Endo

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

or 要么

appEndo $ mconcat $ fmap Endo [id, id, id, id]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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