haskell - 为什么不丢弃任何值?

标签 haskell monads

在 ghci 中有以下内容:

:m + Control.Monad.Error
let f x = Right x

Left 1.0 >> Right 1 >>= f


Left 1.0

据我了解 >> 运算符丢弃第一个参数的一元结果,
但我看到它在这里被保留了下来。你能解释一下吗?

http://hackage.haskell.org/package/base-4.10.0.0/docs/src/Data.Either.html#Either

奇怪的是,该链接没有显示 Either 如何实现 Monad 类型类的方法。

最佳答案

As I understand[, the] >> operator discards monadic result of the first argument,



不,有不是 .它或多或少看到LeftMaybe monad 看到 Nothing (主要区别在于 Left 还带有一个值)。因此,它有时被用作“高级Maybe”,例如可以携带错误消息。
(>>) :: Monad m => m a -> m b -> m b是一个函数,使得 f >> g相当于f >>= \_ -> g f >>= const g .这是 Monad 中的默认实现。类型类。

因此,这取决于 (>>=) :: Monad m => m a -> (a -> m b) -> m b被实现。

现在申请 Either它是 implemented as :

instance Monad (Either e) where
    Left  l >>= _ = Left l
    Right r >>= k = k r


这意味着在 的情况下Left l在左侧,则忽略右侧 , 如果左侧是 Right r ,然后 k应用于 Right 的值构造函数正在包装。

所以我们可以用(为清楚起见添加括号)替换您的查询:
   Left 1.0 >> Right 1 >>= f
=  (>>) (Left 1.0) (Right 1 >>= f)
-> Left 1.0

从语义上您可以看到 Either作为 Maybe 的“更高级”版本在哪里 Left代替Nothing .所以从那一刻起,有些东西是Left x ,然后它保持 Left x .不管我们如何绑定(bind)它。

关于haskell - 为什么不丢弃任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47336752/

相关文章:

haskell - 非确定性如何用 List monad 建模?

haskell - Haskell 中的逆向因果关系 : From Tardis to RevState

haskell - 为什么这个 Haskell 在扩展时会提示类型不明确?

performance - 为什么该程序的 F# 版本比 Haskell 版本快 6 倍?

haskell - 为什么odd.fst 不能与过滤器功能一起使用?

haskell - 关于 State 单子(monad)在 haskell 逝世的困惑

haskell - 将函数及其参数提升到不同的一元上下文

haskell - 什么是实物签名约束

haskell - 学习 Haskell : thunks returned by repeat

haskell - 在应用函数 monad 之前对输入执行转换