我使用阅读器 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/