This is a noob question.
I'd like to write a function which provides a lazy stream of images, presumably something like:
imageStream :: [IO Image]
Unfortunately, the function which reads images can fail, so it looks like:
readImage :: IO (Maybe Image)
So, the function I can write looks like:
maybeImageStream :: [IO (Maybe Image)]
How do I implement a function such as the following, while still keeping lazy IO?
flattenImageStream :: [IO (Maybe Image)] -> [IO Image]
Semantically, when you ask flattenImageStream
for the next image, it should iterate through the list and attempt to read each image. It does this until it finds an image that loads, and returns it.
EDIT: There seems to be some disagreement in the answers.
Some have suggested solutions that use sequence
, but I'm pretty sure I tested that and found it destroys laziness.
(I'll test it again to be sure when I get back to my computer.)
Someone also suggested using unsafeInterleaveIO
.
From the documentation for that function, it seems it would work, but obviously I want to respect the type system as much as possible.
You can use
ListT
frompipes
, which provides a safer alternative to lazyIO
that does the right thing in this case.The way you model your lazy stream of potentially failing images is:
Assuming that you had some image loading function of type:
.. then the way you build such a stream would be something like:
If you use the
dirstream
library, then you can even lazily stream over the directory contents, too.The function that filters out only the successful results would have this type:
Notice that this function works for any base monad,
m
. There is nothingIO
-specific about it. It also preserves laziness!Applying
flattenImage
toimageStream
, gives us something of type:Now let's say that you have some function that consumes these images, of type:
If you want to process the final
ListT
using theuseImage
function, you just write:That will then lazily consume the image stream.
Of course, you could also play code golf and combine all of that into the following much shorter version:
I'm also thinking of adding a
fail
definition forListT
so that you could just write: