[Haskell-cafe] [IO Int] -> IO [Int]

Phlex Phlex at telenet.be
Fri May 4 20:43:16 EDT 2007


Daniel Fischer wrote:
> On 5/4/07, Phlex <Phlex at telenet.be> wrote:
>   
>> I'm trying to write a function with the signature [IO Int] -> IO [Int]
>>
>>
>> Control.Monad has a function (called "sequence") that does this for you. In fact, "sequence" is a more generic solution since its signature is (
>> Monad m => [m a] -> m [a]).
>>     
>
> Unfortunately, this won't work for infinite lists either, for those you'd need an 'unsafe' action, namely 'unsafeInterleaveIO', like
>
>
> import System.IO.Unsafe
>
> conv :: [IO a] -> IO [a]
> conv [] = return []
> conv (x:xs) = do a <- x
>                  as <- unsafeInterleaveIO (conv xs)
>                  return (a:as)
>
>
> *Test> :set -fno-print-bind-result
> *Test> xs <- conv $ map return [1 .. ]
> *Test> take 20 xs
> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
>   
> HTH,
> Daniel
>   
Thank you all for the very good answers.

Sacha


More information about the Haskell-Cafe mailing list