IO序列Haskell

时间:2017-04-22 11:31:15

标签: haskell io

我有这个功能:

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

只是写了一系列IO动作。

问题在于我想编写相同的功能,但根本没有使用'do notation',只需使用运算符&gt;&gt;和&gt;&gt; =代替。

我已经有了这个版本:

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

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

有人可以帮我吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

在应用符号中,它很简单:

do

我是monadic符号,只需翻译sequence (op:ops) = op >>= \x -> sequence ops >>= \xs -> return (x:xs) ,同时保持其结构:

x <- action; ...

粗略地说,action >>= \x -> ...变为sequence (op:ops) = op >>= (\x -> sequence ops >>= (\xs -> return (x:xs))) 。请注意,上面的lambda范围一直延伸到表达式的最后。使用明确的括号:

request(url, method: .post, parameters:params).validate().responseObject{(response:
        DataResponse<objectMapperclass>)in

        switch response.result{

        case.success(let data): 
        let objects = data 

        case.faliure(_): 
   }
}