[Haskell-cafe] How to catch exception within the Get monad (the Binary package)

Henning Thielemann lemming at henning-thielemann.de
Sun Sep 5 03:30:53 EDT 2010

On Sun, 5 Sep 2010, Dimitry Golubovsky wrote:

> Hi,
> The following function* is supposed to decode a list of some
> serialized objects following each other in a lazy Bytestring:
> many :: Get a -> Get [a]
> many prs = many' [] where
>  many' a = do
>    s <- prs
>    r <- isEmpty
>    case r of
>      True -> return (reverse a)
>      False -> many' (s:a)
> prs is a "parser" to decode a single object.

It is more efficient to call
    fmap (s:) (many prs)
  in the recursion in order to avoid the final 'reverse'. The way you have 
implemented the loop, the complete list must be hold in memory, even if it 
is consumed lazily.

The trick to catch exceptions lazily is to make them explicit, either by 
  with an enclosed list. The latter solution is the more general one, but 
unfortunately it causes a space leak in GHC.

More information about the Haskell-Cafe mailing list