gpt4 book ai didi

haskell - 尝试实现 Data.Either

转载 作者:行者123 更新时间:2023-12-04 00:59:12 25 4
gpt4 key购买 nike

为了帮助我学习 Applicative Functors 和 Functors,我想看看 Either使用类型类 Functor 实现和 Applicative .显然我可以继续阅读代码,但我发现自己尝试实现事物以更好地理解事物更有用。

仅供引用,我正在尝试实现此演示文稿结果的 Haskell 版本 http://applicative-errors-scala.googlecode.com/svn/artifacts/0.6/chunk-html/index.html

无论如何,这就是我到目前为止所拥有的

 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

我不确定这是为什么,有人可以帮忙吗?

最佳答案

您正在尝试制作 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 的类型变量case 改为最后一个:
data Validation b a = Success a | Failure b

关于haskell - 尝试实现 Data.Either,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7121257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com