左右的区别
Difference between Left and Right
我目前正在阅读优秀的 "Learn You a Haskell for Great Good",在 section about functors 中有一个涉及 Either
的例子,我不明白:
ghci> fmap (replicate 3) (Right "blah")
Right ["blah","blah","blah"]
ghci> fmap (replicate 3) (Left "foo")
Left "foo"
为什么不是后者Left ["foo", "foo", "foo"]
?
Either
上的 Left
构造函数实现为 "failure case"。与其他函子一样,一旦这个失败值进入方程,它就会阻止任何真正的计算发生。因此,当您将 fmap
应用于 Left "foo"
时,它会立即 returns 相同的 "failure" 值。
您可以通过查看 Either
如何实现 fmap
:
来了解这一点
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
这里的想法是 Left "foo"
实际上会更具描述性,例如 Left "Value could not be computed"
。如果您尝试对该值应用更多函数,您只希望 "error" 完整传递。
如果有帮助,请想象一下 fmap
如何在失败情况更明显的其他类型上工作,例如:
-- Maybe: failure value is `Nothing`
fmap (replicate 3) (Nothing)
这会产生 Nothing
,而不是 [Nothing, Nothing, Nothing]
我目前正在阅读优秀的 "Learn You a Haskell for Great Good",在 section about functors 中有一个涉及 Either
的例子,我不明白:
ghci> fmap (replicate 3) (Right "blah")
Right ["blah","blah","blah"]
ghci> fmap (replicate 3) (Left "foo")
Left "foo"
为什么不是后者Left ["foo", "foo", "foo"]
?
Either
上的 Left
构造函数实现为 "failure case"。与其他函子一样,一旦这个失败值进入方程,它就会阻止任何真正的计算发生。因此,当您将 fmap
应用于 Left "foo"
时,它会立即 returns 相同的 "failure" 值。
您可以通过查看 Either
如何实现 fmap
:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
这里的想法是 Left "foo"
实际上会更具描述性,例如 Left "Value could not be computed"
。如果您尝试对该值应用更多函数,您只希望 "error" 完整传递。
如果有帮助,请想象一下 fmap
如何在失败情况更明显的其他类型上工作,例如:
-- Maybe: failure value is `Nothing`
fmap (replicate 3) (Nothing)
这会产生 Nothing
,而不是 [Nothing, Nothing, Nothing]