Useful Numeric Functions

Ashley Yakeley ashley at
Mon Mar 14 05:45:55 EST 2005

I'm thinking something like these should be in the standard libraries in 
some form. The first (fromReal) is pretty straightforward.

The others come from the observation that there's no reason why the 
arguments to div and mod should be integers. The basic formulae are 

  a `div` b = floor (a/b)

  a `mod` b = a - (a div b) * b

As you can see, div should return an integer (because that's what floor 
does), but everything else generalises to real.

I suspect my implementations are not optimal.

-- | similar idea to "fromIntegral"
fromReal :: (Real a,Fractional b) => a -> b
fromReal = fromRational . toRational

-- | like "div", but with a more useful type
div' :: (Real a,Integral b) => a -> a -> b
div' n d = floor ((toRational n) / (toRational d))

-- | like "divMod", but with a more useful type
divMod' :: (Real a,Integral b) => a -> a -> (b,a)
divMod' n d = (f,n - (fromIntegral f) * d) where
    f = div' n d

-- | like "mod", but with a more useful type
mod' :: (Real a) => a -> a -> a
mod' n d = n - (fromInteger f) * d where
    f = div' n d

Ashley Yakeley, Seattle WA

More information about the Libraries mailing list