Haskell虚函数

问题描述 投票:2回答:1

我是Haskell的新手。在Monad文档中,void函数有一个示例用法:

>>> void (Left 8675309)
Left 8675309
>>> void (Right 8675309)
Right ()

我很难弄清楚为什么会这样。

[我看到void定义为:void x = () <$ x(<$) = fmap . const,但我无法弄清为什么左和右之间存在差异。

有任何提示吗?

haskell monads functor
1个回答
0
投票

因为fmap映射了Right中定义的值,而不是Left中定义的值。实际上,Either定义为:

data Either a b = Left a | Right b

因此FunctorEither 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 cEitherfmap :: (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 ()
© www.soinside.com 2019 - 2024. All rights reserved.