了解Either是Functor的一个实例 [英] Understanding how Either is an instance of Functor
问题描述
在我的阅读中,我遇到了一个例子,说明 被做成
Functor
的一个实例:
<$ ($ x
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
现在,我正试图理解为什么在 Left
?
的情况下,这是我的理解:
首先让我把上面的例子重写为
instance Functor(或者a)where
fmap g(Right x)= Right(gx)
fmap g(Left x)= Left x
现在:
-
我知道
fmap ::(c - > ; d) - > f c - >如果我们用
替换
f
,那么fd 或者我们得到 -
右(gx)
类型(gx)
和gx
的类型都是d
,所以我们知道Right(gx)
的类型是或者ad
,这是我们期望的fmap
(见上面的2.)现在,如果我们看看Left( gx)
我们可以用相同的推理来说明它的类型是Either(gx)b
,也就是E db ,这不是我们所期望的
fmap
(见上面的2.):d
应该是第二个参数,而不是第一个!所以我们不能映射Left
。
fmap ::(c - > d) - >或者c - >广告
是我的推理是正确的吗?
这是正确的。此行为还有另一个非常重要的原因:您可以将或者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:
I know that
fmap :: (c -> d) -> f c -> f d
if we substitute
f
withEither a
we getfmap :: (c -> d) -> Either a c -> Either a d
the type of
Right (g x)
isEither a (g x)
, and the type ofg x
isd
, so we have that the type ofRight (g x)
isEither a d
, which is what we expect fromfmap
(see 2. above)now, if we look at
Left (g x)
we can use the same reasoning to say that its type isEither (g x) b
, that isEither d b
, which is not what we expect fromfmap
(see 2. above): thed
should be the second parameter, not the first! So we can't map overLeft
.
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屋!