[Haskell-cafe] Make strict (IO String) lazy

Björn Bringert bringert at cs.chalmers.se
Thu Mar 15 10:11:02 EDT 2007


Henning Thielemann wrote:
>  On the one hand, in the standard libraries there are functions like
> readFile, getContents, hGetContents which read a file lazily. This is
> often a nice feature, but sometimes lead to unexpected results, say when
> reading a file and overwriting it with modified contents. Unfortunately
> the standard libraries provide no functions for strict reading, and one
> has to do this manually.
>  On the other hand, when I write some IO function that returns a String, I
> easily end up with a function which produces the String in a strict way.
> (Say I call some shell commands and concatenate their outputs.)
>  What is the preferred way to turn a strict (IO String) into a lazy one?
> forkIO? forkOS? How would one derive readFile from a hypothetical
> strictReadFile?

Perhaps I misunderstood you, but wouldn't using fork* just make it 
nondeterministic, not lazy? unsafeInterleaveIO is the way to go, though 
it won't allow you to write readFile using strictReadFile. Rather, it 
allows you to write readFile using hGetChar. unsafeInterleaveIO . 
strictReadFile is not lazy enough, since it reads the whole file when 
you force the head of the string.

/Björn


More information about the Haskell-Cafe mailing list