
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?

lemming:
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.
Data.ByteString.readFile is strict, and then: import qualified Data.ByteString strictReadFile :: FilePath -> IO String strictReadFile = liftM B.unpack B.readFile
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?
unsafeInterleaveIO strict reads? -- Don

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
participants (3)
-
Björn Bringert
-
dons@cse.unsw.edu.au
-
Henning Thielemann