是否没有标准(任一)monad 实例?
我的印象是某处有一个 Either a 的实例,但我似乎找不到它。我尝试导入 Control.Monad、Control.Monad.Instances 和 Data.Either,如图所示
module Main where
import Control.Monad
import Data.Either
import Control.Monad.Instances
test :: [Either a b] -> Either a [b]
test = sequence
main = return ()
,但 ghc 告诉我它无法推断(Monad (Either a))。添加
instance Monad (Either a) where
return = Right
Right b >>= f = f b
Left a >>= _ = Left a
使得代码可以编译,但是这个实例声明看起来很笼统,如果它还没有出现在某个标准模块中,那么它对我来说就没有意义。如果是,我应该在哪里找到它,如果不是,那么这有什么原因吗?
-------------- 编辑 ---------------
请注意,我现在认为下面 user31708 的答案(“从基础 4.6 开始,实例在 Data.Either 本身中。”)目前是正确的答案。我不确定在这种情况下重新分配所选答案的正确协议,其中所选答案是提出问题时的正确答案,因此我将其保留原样。如果有其他指导方针,请纠正我。
I was under the impression that there was an instance for Either a somewhere, but I can't seem to find it. I have tried importing Control.Monad, Control.Monad.Instances and Data.Either as shown
module Main where
import Control.Monad
import Data.Either
import Control.Monad.Instances
test :: [Either a b] -> Either a [b]
test = sequence
main = return ()
but ghc tells me that it could not deduce (Monad (Either a)). Adding
instance Monad (Either a) where
return = Right
Right b >>= f = f b
Left a >>= _ = Left a
makes the code compile, but this instance declaration seems so general that it doesn't make sense to me if it isn't already out there in some standard module. If it is, where should I look to find it, and if it isn't, is there then a reason for this?
-------------- EDIT ---------------
Be aware that I now think that the answer by user31708 below ("As of base 4.6, the instance is in Data.Either itself.") is currently the correct answer. I am not sure of the proper protocol of reassigning the selected answer in this case, where the selected answer was the correct answer at the time that the question was asked, so I have left it as it is. Please correct me, if there is another guideline for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此实例 已添加到
base 4.3.xx
中,该版本随ghc 7
一起提供。同时,您可以直接使用Either
实例,或者,如果您使用Either
来表示某些内容这可能会失败,您应该使用 < code>ErrorT monad 转换器。
This instance has been added in
base 4.3.x.x
, which comes withghc 7
. Meanwhile, you can use theEither
instance directly, or, if you are usingEither
to represent somethingthat may fail you should use
ErrorT
monad transformer.从 Base 4.6 开始,实例 位于
Data.Either
本身中。As of base 4.6, the instance is in
Data.Either
itself.在
Control.Monad.Error
中没有Either a
的实例,但有Either String
的实例。 (实际上,它是针对Error e => Either e
,IIRC)。There is not an instance for
Either a
, but there is forEither String
inControl.Monad.Error
. (Actually, it's forError e => Either e
, IIRC).我相信
Control.Monad.Error
中有一些东西 - 但没有任何东西要检查。I believe there's something in
Control.Monad.Error
- don't have anything to check, though.