首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试实现Data.Either

尝试实现Data.Either
EN

Stack Overflow用户
提问于 2011-08-19 20:03:32
回答 1查看 593关注 0票数 12

为了帮助我学习应用函数器和函数器,我认为看看Either是如何用类型类FunctorApplicative实现的会很有趣。显然,我可以继续阅读代码,但我发现尝试自己实现一些东西以更好地理解它们会更有用。

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

不管怎样,这就是我目前所知道的

代码语言:javascript
复制
 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运行它时,我只得到以下错误信息:-

代码语言:javascript
复制
[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

我不太确定为什么会这样,有人能帮上忙吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-19 20:08:56

您正在尝试使Functor实例在Success部件上工作,这是正常的做法,但是由于类型参数的顺序,它是在Failure部件中的类型上定义的。

因为您已经将其定义为

代码语言:javascript
复制
data Validation a b = Success a | Failure b

instance Functor (Validation a) where
    ...

这意味着您的fmap实现应该具有(x -> y) -> Validation a x -> Validation a y类型。但由于第二个类型变量用于Failure情况,因此不会进行类型检查。

您希望Success案例的类型变量是最后一个变量:

代码语言:javascript
复制
data Validation b a = Success a | Failure b
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7121257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档