[Haskell-cafe] Re: Exception handling in numeric computations

wren ng thornton wren at freegeek.org
Thu Mar 26 21:57:39 EDT 2009


Jonathan Cast wrote:
> Xiao-Yong Jin wrote:
> > > Xiao-Yong Jin wrote:
> > > > So I have another question.  Is the following function safe
> > > > and legitimate?
> > > >
> > > >> safeDiv :: (Exception e, Integral a) =>
> > > >>            a -> a -> Either e a
> > > >> safeDiv x y = unsafePerformIO . try . evaluate $ div x y
> >
> >> safeDiv' :: (Exception e, Integral a) =>
> >>             a -> a -> Either e a
> >> safeDiv' _ 0 = Left e
> >> safeDiv' x y = Right $ div x y
> 
> [...]
> Other than that, I think the imprecise exceptions paper guarantees that
> these two functions are equivalent (albeit unwisely: see below).

I don't think so. The evaluation of x and y may throw errors before we 
get around to div.

* safeDiv' will evaluate y (to pattern match against 0) and may return 
an error, e, whereas safeDiv will return Left e if div is strict in y.

* safeDiv' postpones evaluating x and so may return Right e, whereas 
safeDiv will return Left e if div is strict in x.


-- 
Live well,
~wren


More information about the Haskell-Cafe mailing list