[Haskell-cafe] Lazy read

Neil Mitchell ndmitchell at gmail.com
Thu Feb 16 09:05:52 EST 2006


I have a nice big data structure that I serialise to a file using
"show", and read back in using "read". This data structure has
deriving (Read, Show), which makes it all nice and easy to save and
load this data structure, without worrying about parsing code etc.

The problem is that this data structure can become quite big, and
while show operates lazily, read does not. I understand the reason for
this - that it internally calls reads and that on a parse error reads
will not return a result - i.e. it has to get to the end to determine
whether the parse was valid or not. However, in my particular case, I
know the data structure is valid, and if it isn't then I'm quite happy
with the parser throwing an error half way through - after having
lazily returned half of the data.

A short example, which shows up the exact same issue is:

head ((read $ show [1..n]) :: [Int])

The time of this operation is dependant on n, because of the strictness of read.

What is the best way to modify the code to have read operate lazily?
Is there any method that doesn't require writing a custom parser? Is
there any standard way for solving a problem like this?



More information about the Haskell-Cafe mailing list