【问题标题】:Is there a standard function like `>>`, but returning the result of the first operand?有没有像`>>`这样的标准函数,但返回第一个操作数的结果?
【发布时间】: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 的上下文中,还有finallyhackage.haskell.org/package/base-4.11.1.0/docs/…。但这更多是与 exception 机制结合使用,因此在语义上并不完全相同。
  • @WillemVanOnsem 我可以要求您取消删除以前的 cmets,或者更好地将它们合并到 leftaroundabout 的答案中吗?它们很有价值。
  • 查看 stackoverflow.com/tags/haskell/info 了解有关 hoogle 和其他常见问题的信息

标签: haskell monads standard-library


【解决方案1】:

(<*) :: Applicative f => f a -> f b -> f a

【讨论】:

  • 请解释一下,这有帮助。
  • @Prateek 对于“什么标准函数相当于\a b -&gt; a &gt;&gt;= \x -&gt; b &gt;&gt; return x”的问题,如果可以用“(&lt;*) 是”来完全回答,我不明白该解释什么。实际上,我觉得这个对一个微不足道的问题的微不足道的答案得到了如此多的支持,这有点愚蠢,但我们开始吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 2015-02-04
  • 1970-01-01
  • 2013-06-21
  • 2011-10-05
相关资源
最近更新 更多