[Haskell-cafe] Hiding side effects in a data structure

Ketil Malde ketil+haskell at ii.uib.no
Sun Oct 21 03:59:57 EDT 2007


I've done something similar, I think.  Often, I want to output some
kind of progress indicator, just to show that the program is working.
Typically, the program works by lazily evaluating a list (lines from
an input file, say); each element of the list is wrapped with an IO
action that outputs the status when evaluated -- which typically
happens lazily from pure code. 

> countIO :: String -> String -> Int -> [a] -> IO [a]
> countIO msg post step xs = sequence $ map unsafeInterleaveIO ((blank >> outmsg (0::Int) >> c):cs)
>    where (c:cs) = ct 0 xs
>          output   = hPutStr stderr
>          blank    = output ('\r':take 70 (repeat ' '))
>          outmsg x = output ('\r':msg++show x) >> hFlush stderr
>          ct s ys = let (a,b) = splitAt (step-1) ys
>                        next  = s+step
>                    in case b of [b1] -> map return a ++ [outmsg (s+step) >> hPutStr stderr post >> return b1]
>                                 []   -> map return (init a) ++ [outmsg (s+length a) >> hPutStr stderr post >> return (last a)]
>                                 _ -> map return a ++ [outmsg s >> return (head b)] ++ ct next (tail b)

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants


More information about the Haskell-Cafe mailing list