【发布时间】:2018-12-30 21:47:51
【问题描述】:
例如,假设我想读一行并按铃:
λ getLine >> putChar '\007'
How lang and dreary is the night when I am frae my Dearie.
-- Blip and `()`. The line is lost.
λ getLine >>= (\x -> putChar '\007' >> return x
I restless lie frae e'en to morn though I were ne'er sae weary.
"I restless lie frae e'en to morn though I were ne'er sae weary."
-- A line and also a blip side effect.
这个想法似乎与const 有很多共同之处,唯一的区别是给出的值是有效的,并且都被执行,即使只保留了第一个操作的值。 (与 >> 不同,它保留了第二个的值。) 我的意思是这样的:
λ constM a b = a >>= \x -> b >> return x
这是一个更复杂的例子,涉及来自Text.ParserCombinators.ReadP的解析器:
λ readP_to_S (many1 (munch1 (not . isSpace) `constM` skipSpaces ) `constM` eof) <$> getLine
How slow ye move, ye heavy hours.
[(["How","slow","ye","move,","ye","heavy","hours."],"")]
我想知道base 中是否有此功能,或者可以从base 中的其他功能轻松构造。
【问题讨论】:
-
此外,在
IO的上下文中,还有finally:hackage.haskell.org/package/base-4.11.1.0/docs/…。但这更多是与 exception 机制结合使用,因此在语义上并不完全相同。 -
@WillemVanOnsem 我可以要求您取消删除以前的 cmets,或者更好地将它们合并到 leftaroundabout 的答案中吗?它们很有价值。
-
查看 stackoverflow.com/tags/haskell/info 了解有关 hoogle 和其他常见问题的信息
标签: haskell monads standard-library