我是 Haskell 的新手。在 Monad 文档中,有一个用于 void 函数的示例:
>>> void (Left 8675309)
Left 8675309
>>> void (Right 8675309)
Right ()
我很难弄清楚为什么会这样。
我看到 void 被定义为:
void x = () <$ x
和 (<$) = fmap . const
但我无法弄清楚为什么左和右之间存在差异。任何提示?
最佳答案
因为 fmap
映射 Right
中定义的值,不在 Left
.确实,Either
定义为:
data Either a b = Left a | Right b
和
Functor
的 Either a
因此实现为:instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right x) = Right (f x)
这是有道理的,因为
Functor
期望一种类型 * -> *
,因此 fmap :: Functor f => (b -> c) -> f b -> f c
为 Either
做一个映射与 fmap :: (b -> c) -> Either a b -> Either a c
.自
void
定义为 void = fmap (const ())
,这意味着如果我们对每个案例进行分析,我们会看到:fmap (const ()) (Left x) = Left x
fmap (const ()) (Right x) = Right (const () x) = Right ()
关于Haskell 空函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60698787/