是否有像`>>`这样的标准函数,但是返回第一个操作数的结果?

时间:2018-07-23 12:29:29

标签: haskell monads standard-library

例如,假设我想读一行并且还按一下铃铛:

λ 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中的其他功能轻松构造。

1 个答案:

答案 0 :(得分:13)