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

Donn Cave donn at avvanta.com
Tue Sep 7 16:16:17 EDT 2010

Quoth Dimitry Golubovsky <golubovsky at gmail.com>,

> I see another solution: are there any hidden problems?
> I found an interesting package, ChasingBottoms which contains a
> function testing a value to be bottom and returning a Boolean (of
> course it cannot be done without unsafePerformIO).
> I borrowed the idea from that package, and wrote two functions:
> unThrow :: (Exception e) => a -> Either e a
> unThrow a = unsafePerformIO $ (E.evaluate a >>= return . Right) `E.catch`
>                                                (\e -> return $ Left e)

Like Henning, I'm not going to try to predict a specific problem
with it, but I don't like it.

Have you had a chance to look at cereal (Data.Serialize)?  I frankly
couldn't make it do what you need, as written, but I could make it
work if I modify Serialize.Get to export "Get(..)" instead of "Get".
>From there I wrote a variant of the Get (>>=) function with an
additional end-value-on-failure parameter, [] in your program:

 ebind m g e = Get (\ s0 f k -> unGet m s0 (\ _ _ -> k B.empty e)
			(\ s a -> unGet (g a) s f k))

... so to get your error bounded array of Int,

  getx = ebind get (\ a -> getx >>= return . (:) a) []

I think it's very likely there's a simpler way to do this with
Data.Serial as written, I am just a little backwards with state
monads and that kind of thing.

	Donn Cave, donn at avvanta.com

More information about the Haskell-Cafe mailing list