Skip to content

Implement round for Ratio that doesn't explode with Naturals

taylorfausak requested to merge trac-taylorfausak/ghc:patch-2 into master

Today I was surprised to find that round does not work at all for Ratio Natural values. For example:

>>> round (1 :: Ratio Natural) :: Natural
*** Exception: arithmetic underflow

As far as I can tell it's true regardless of the value of the Ratio Natural or the result type.

>>> round (1.5 :: Ratio Natural) :: Natural
*** Exception: arithmetic underflow
>>> round (1 :: Ratio Natural) :: Integer
*** Exception: arithmetic underflow

For comparison, rounding works fine for Rational, which is an alias for Ratio Integer.

>>> round (1 :: Rational) :: Integer
1
>>> round (1.5 :: Rational) :: Integer
2
>>> round (1 :: Rational) :: Natural
1

This merge request provides an implementation of round for Ratio that does not throw an arithmetic underflow exception. It seems to work with all the values I could think to throw at it.

I'm not married to the implementation. If there's a better way to do this, I'm all ears.

I did not add a test case for this, but I probably should.

Edited by taylorfausak

Merge request reports