为了帮助我学习应用函数器和函数器,我认为看看Either是如何用类型类Functor和Applicative实现的会很有趣。显然,我可以继续阅读代码,但我发现尝试自己实现一些东西以更好地理解它们会更有用。
仅供参考我正在尝试实现此演示文稿http://applicative-errors-scala.googlecode.com/svn/artifacts/0.6/chunk-html/index.html结果的Haskell版本
不管怎样,这就是我目前所知道的
data Validation a b = Success a | Failure b deriving (Show, Eq)
instance Functor (Validation a) where
fmap f (Failure x) = Failure x
fmap f (Success x) = Success (f x)但每当我尝试用ghci运行它时,我只得到以下错误信息:-
[1 of 1] Compiling Main ( t.hs, interpreted )
t.hs:5:35:
Couldn't match type `b' with `a1'
`b' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Validation a a1 -> Validation a b
at t.hs:4:5
`a1' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Validation a a1 -> Validation a b
at t.hs:4:5
Expected type: a
Actual type: b
In the return type of a call of `f'
In the first argument of `Success', namely `(f x)'
In the expression: Success (f x)
t.hs:5:37:
Couldn't match type `a' with `a1'
`a' is a rigid type variable bound by
the instance declaration at t.hs:3:30
`a1' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Validation a a1 -> Validation a b
at t.hs:4:5
In the first argument of `f', namely `x'
In the first argument of `Success', namely `(f x)'
In the expression: Success我不太确定为什么会这样,有人能帮上忙吗?
发布于 2011-08-19 20:08:56
您正在尝试使Functor实例在Success部件上工作,这是正常的做法,但是由于类型参数的顺序,它是在Failure部件中的类型上定义的。
因为您已经将其定义为
data Validation a b = Success a | Failure b
instance Functor (Validation a) where
...这意味着您的fmap实现应该具有(x -> y) -> Validation a x -> Validation a y类型。但由于第二个类型变量用于Failure情况,因此不会进行类型检查。
您希望Success案例的类型变量是最后一个变量:
data Validation b a = Success a | Failure bhttps://stackoverflow.com/questions/7121257
复制相似问题