了解Either是Functor的一个实例 [英] Understanding how Either is an instance of Functor

查看:126
本文介绍了了解Either是Functor的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的空闲时间里,我正在学习Haskell,所以这是一个初学者的问题。



在我的阅读中,我遇到了一个例子,说明 被做成 Functor 的一个实例:

 <$ ($ x 



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'

现在,我正试图理解为什么在 Right 值的情况下映射实现构造函数,但不在 Left



的情况下,这是我的理解:



首先让我把上面的例子重写为

  instance Functor(或者a)where 
fmap g(Right x)= Right(gx)
fmap g(Left x)= Left x

现在:


  1. 我知道 fmap ::(c - > ; d) - > f c - >如果我们用替换 f ,那么fd

  2. 或者我们得到 fmap ::(c - > d) - >或者c - >广告


  3. 右(gx)类型(gx) gx 的类型都是 d ,所以我们知道 Right(gx)的类型是或者ad ,这是我们期望的 fmap (见上面的2.)现在,如果我们看看 Left( gx)我们可以用相同的推理来说明它的类型是 Either(gx)b ,也就是 E db ,这不是我们所期望的 fmap (见上面的2.): d 应该是第二个参数,而不是第一个!所以我们不能映射 Left


是我的推理是正确的吗?

解决方案

这是正确的。此行为还有另一个非常重要的原因:您可以将或者ab 视为计算,这可能会成功并返回 b 或失败,并显示错误消息 a 。 (这也是monad实例的工作原理)。所以很自然,仿函数实例不会触及 Left 值,因为您想映射计算,如果失败,则无法操作。 p>

In my free time I'm learning Haskell, so this is a beginner question.

In my readings I came across an example illustrating how Either a is made an instance of Functor:

instance Functor (Either a) where
    fmap f (Right x) = Right (f x)
    fmap f (Left x) = Left x

Now, I'm trying to understand why the implementation maps in the case of a Right value constructor, but doesn't in the case of a Left?

Here is my understanding:

First let me rewrite the above instance as

instance Functor (Either a) where
    fmap g (Right x) = Right (g x)
    fmap g (Left x) = Left x

Now:

  1. I know that fmap :: (c -> d) -> f c -> f d

  2. if we substitute f with Either a we get fmap :: (c -> d) -> Either a c -> Either a d

  3. the type of Right (g x) is Either a (g x), and the type of g x is d, so we have that the type of Right (g x) is Either a d, which is what we expect from fmap (see 2. above)

  4. now, if we look at Left (g x) we can use the same reasoning to say that its type is Either (g x) b, that is Either d b, which is not what we expect from fmap (see 2. above): the d should be the second parameter, not the first! So we can't map over Left.

Is my reasoning correct?

解决方案

This is right. There is also another quite important reason for this behavior: You can think of Either a b as a computation, that may succeed and return b or fail with an error message a. (This is also, how the monad instance works). So it's only natural, that the functor instance won't touch the Left values, since you want to map over the computation, if it fails, there's nothing to manipulate.

这篇关于了解Either是Functor的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆