Streaming with side-effects
Lists are pure, but the streaming property is still useful also in impure I/O settings. Although lazy I/O has its share of problems, it isn't the only streaming I/O technique in Haskell. It's fully possible to use explicit buffers, for example, to read and process iteratively using the low-level functions in System.IO. This program uses a pointer to an integer to stream random numbers from `
-- file: ptr.hsimport System.IO
import Foreign.Ptr (Ptr)
import Foreign.Storable (Storable(sizeOf, peek))
import Foreign.Marshal (alloca)
main = withBinaryFile "/dev/random" ReadMode $ alloca . process
where
process :: Handle -> Ptr Int -> IO ()
process h ptr = go where
go = do
count <- hGetBuf h ptr (sizeOf (undefined :: Int))
if count > 0
then do num <- peek ptr
print num
go
else return ()As can be seen, this program is pretty verbose. The same program...