Haskell 空函数

标签 haskell monads functor

我是 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

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 cEither 做一个映射与 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/

相关文章:

scala - 批处理和函数式编程

haskell - 插入新绑定(bind)时是否复制了整个 map ?

javascript - 在 JavaScript 中实现 monad

haskell - 实现 `Monad ((->) e)`

haskell - 第一次使用 monad 的经验 (Haskell)

haskell - 是否可以在运行时分配 KnownNat?

python - 是否有类似其他语言(Java、Lisp、Haskell、Go 等)的 Stackless Python 项目?

C++:函数指针作为模板参数而不是仿函数

c++ - 如何在 std::vector<string> 中查找重复项并返回它们的列表?

c++ - 使用 std::sort 时禁止仿函数(继承)?