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

Dimitry Golubovsky golubovsky at gmail.com
Sun Sep 5 00:01:25 EDT 2010


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.

If however something goes wrong, and prs fails, the whole function
fails (error is thrown). Since [a] (result of decoding) is a lazy
list, actual exception may be thrown at any moment the list is being
processed, and exception handler may not be properly set.

Is there any way to catch/detect failures inside the Get monad? It is
not an instance of MonadError, so catchError does not work.

Ideally, the function would keep decoding as long as it is possible,
and upon the first failure of the parser, return whatever has been


* there is one intentional inaccuracy in this function: isEmpty is
called _after_ decoding is tried, so an empty ByteString would cause
parser failure and exception right away; this is used as a test case.

Dimitry Golubovsky

Anywhere on the Web

More information about the Haskell-Cafe mailing list