【问题标题】:IO sequence HaskellIO 序列 Haskell
【发布时间】:2017-04-22 11:31:14
【问题描述】:

我有这个功能:

sequence :: [IO a] -> IO [a]
sequence [] = pure []
sequence (op:ops) = do
    x <- op
    xs <- sequence ops
    return (x:xs)

它只是写了一系列 IO 动作。

问题是我想编写相同的函数,但根本不使用“do notation”,而是使用运算符 >> 和 >>=。

我已经有这个版本了:

mySequence:: [IO a]-> IO [a]
mySequence [] = pure []
mySequence (op:ops) =
    op >> sequence ops

但它不适用于例如输入 [ pure 1 , pure 2 ]。

谁能帮我解决这个问题?

提前致谢。

【问题讨论】:

  • do 版本中,您有2 个绑定和一个return 语句。在没有do 的版本中,您使用&gt;&gt;,它会丢弃其左操作数的结果,并且您唯一返回的是[]do 版本还使用: 运算符,do-less 版本没有。

标签: haskell io


【解决方案1】:

在应用符号中,它非常简单:

sequence (op:ops) = (:) <$> op <*> sequence ops

我是一元符号,只翻译do,同时保持其结构:

sequence (op:ops) =
   op             >>= \x ->
   sequence ops   >>= \xs ->
   return (x:xs)

大致上,x &lt;- action; ... 变为 action &gt;&gt;= \x -&gt; ...。请注意,上面的 lambdas 的范围一直延伸到表达式的最后。带显式括号:

sequence (op:ops) =
   op >>= (\x -> sequence ops >>= (\xs -> return (x:xs)))

【讨论】:

  • 感谢您的回答。如果我们像这样调用函数:sequence [ putStr "hi" , pure 4] ,这不起作用,为什么?
  • @AntonioSerrano [ putStr "hi", pure 4] 的类型是什么? putStr "hi"pure 4 有不兼容的类型,你不能把它们放在同一个列表中(除非你创建一个 instance Num (),我想)。
  • 好的,我知道了,但是为什么示例 [pure 1, pure 2] 仍然不起作用? @sepp2k
  • @AntonioSerrano sequence [pure 1, pure 2] 产生 pure [1, 2]。是什么让你说它不起作用?
  • 首先,试试这个:sequence (op:ops) = op >>= (\x -> sequence ops >>= (\xs -> return (x:xs))) with sequence [ pure 1, pure 2] ,控制台显示“main: main.hs:7:1-78: Non-exhaustive patterns in function mysequence”。其次,当我解决这个问题时,控制台没有显示任何内容,这就是我说它不起作用的原因。你得到什么结果?谢谢@sepp2k
猜你喜欢
  • 2019-03-28
  • 2016-03-04
  • 1970-01-01
  • 2020-02-03
  • 2012-03-28
  • 2015-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多