instance Monad (Either a) where
return = Left
fail = Right
Left x >>= f = f x
Right x >>= _ = Right x
在 'baby.hs' 这个代码断枝造成可怕的编译错误:为什么这个任意单子代码不能输入检查?
Prelude> :l baby
[1 of 1] Compiling Main (baby.hs, interpreted)
baby.hs:2:18:
Couldn't match expected type `a1' against inferred type `a'
`a1' is a rigid type variable bound by
the type signature for `return' at <no location info>
`a' is a rigid type variable bound by
the instance declaration at baby.hs:1:23
In the expression: Left
In the definition of `return': return = Left
In the instance declaration for `Monad (Either a)'
baby.hs:3:16:
Couldn't match expected type `[Char]' against inferred type `a1'
`a1' is a rigid type variable bound by
the type signature for `fail' at <no location info>
Expected type: String
Inferred type: a1
In the expression: Right
In the definition of `fail': fail = Right
baby.hs:4:26:
Couldn't match expected type `a1' against inferred type `a'
`a1' is a rigid type variable bound by
the type signature for `>>=' at <no location info>
`a' is a rigid type variable bound by
the instance declaration at baby.hs:1:23
In the first argument of `f', namely `x'
In the expression: f x
In the definition of `>>=': Left x >>= f = f x
baby.hs:5:31:
Couldn't match expected type `b' against inferred type `a'
`b' is a rigid type variable bound by
the type signature for `>>=' at <no location info>
`a' is a rigid type variable bound by
the instance declaration at baby.hs:1:23
In the first argument of `Right', namely `x'
In the expression: Right x
In the definition of `>>=': Right x >>= _ = Right x
Failed, modules loaded: none.
为什么出现这种情况?我怎么能让这个代码编译? 感谢您的任何帮助〜
我明白了。我调整了代码,看它编译:
instance Monad (Either a) where
return = Right
Left a >>= f = Left a
Right x >>= f = f x
它编译成功! 但是......再更多的问题:
instance Monad (Either a)
使得“无论是”一个单子,我得到了“回报=右” ...我怎么能得到“回报=左”? 我已经尝试过这一点,但失败:
instance Monad (`Either` a) where
return = Left
Right a >>= f = Right a
Left x >>= f = f x
或: 实例单子(\ X - >中X一)
不编译了!
关于此问题的博客文章:http://ro-che.blogspot.com/2008/09/haskell-puzzle-either-monad.html – 2010-04-06 17:44:58