haskell - 从 Reader monad 中获取 Monadic 代码

标签 haskell monads

我使用阅读器 monad 编写了一些 Monadic 代码,我想知道是否有任何方法可以使用 do-notation 进行编写:

m = Map.fromList [("This","is"), ("is","the"), ("the","secret")]
f x m = fromMaybe "default" $ Map.lookup x m

r :: String -> Reader (Map String String) String)
r x = reader $ \m1 -> f x m1

runReader ((r "This") >>= r >>= r) m
-- "secret"

现在你会如何用 do 表示法编写最后一条语句。

我有一种感觉,所有使用 runX 函数的“扩展单子(monad)”并不能真正借用 do-notation。

最佳答案

你可以做

runReader threeRs m where
  threeRs = do
   a <- r "This"
   b <- r a
   r b

虽然我不推荐这个。在这种情况下,使用绑定(bind) (>>=) 运算符非常适合实际的链接。

恕我直言,当对一元操作进行排序时,不需要所有结果,应该组合结果,或者在两者之间使用纯函数,do 表示法最有用。另请参阅Should do-notation be avoided in Haskell?

关于haskell - 从 Reader monad 中获取 Monadic 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44770317/

相关文章:

Scala 等价于 Haskell 单子(monad)

haskell - 简化 Haskell 类型签名

haskell - 使用列表理解代替递归

haskell - 更多 rmonad 库?

haskell,IO Monoid 关联性被打破了吗?

haskell - 如何使用 >>= 运算符编写以下函数

Haskell 循环函数

haskell - Cabal 无法解决依赖关系

javascript - 单子(monad)组合练习错误

haskell - 如何将图像转换为颜色矩阵?