本文介绍了我如何使用函数的monoid实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
GHCI告诉我,这个函数是一个Monoid类型的实例。 mconcat [id,id,id,id]
的类型是 Monoid a => a - >一个
。但我预计它会是 a - > a
。
发生了什么?
解决方案
instance Monoid b => Monoid(a - > b)其中
mempty _ = mempty
mappend fgx = fx`mappend` gx
这是更通用的,因为它不需要同态(即 a - > a
)。为了得到你期待的实例,你可以将你的函数封装在 Endo
中:
appEndo(mconcat [Endo id,Endo id,Endo id,Endo id])
或
appEndo $ mconcat $ fmap Endo [id,id,id,id]
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 (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]
这篇关于我如何使用函数的monoid实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!