[Haskell-beginners] How to divide a pair of Num values?

Iustin Pop iusty at k1024.org
Wed Oct 24 12:40:22 CEST 2012


On Wed, Oct 24, 2012 at 09:01:34AM +0000, Costello, Roger L. wrote:
> Hi Folks,
> 
> Here is a function that takes a pair of Integral
> values and divides them:
> 
> divide_v1 :: Integral a => (a, a) -> a
> divide_v1 (m, n) = (m + n) `div` 2
> 
> I invoke the function with a pair of Integral
> values and it works as expected:
> 
> divide_v1 (1, 3)
> 
> Great. That's perfect if my numbers are always Integrals.
> 
> Here is a function that takes a pair of Fractional
> values and divides them:
> 
> divide_v2 :: Fractional a => (a, a) -> a
> divide_v2 (m, n) = (m + n) / 2
> 
> I invoke the function with a pair of Fractional
> values and it works as expected:
> 
> divide_v2 (1.0, 3.0)
> 
> Great. That's perfect if my numbers are always Fractionals.
> 
> I would like a function that works regardless of whether the
> numbers are Integrals or Fractionals:
> 
> divide_v3 :: Num a => (a, a) -> a
> divide_v3 (m, n) = (m + n) ___ 2
> 
> What operator do I use for ___?

As far as I know, you can't do this easily. Or rather, you can, if
you're fine to always use `div`, but not if you want different
behaviour.

If you really want to implement it, you can use a custom type-class, and
implement instances both Integral and Fractional for it, using div and
respectively (/). Something like (not tested):

class SmartDivision a where
  smartDivide :: a -> a -> a

instance (Integral a) => SmartDivision a where
  smartDivide = div

instance (Fractional a) => SmartDivision a where
  smartDivide = (/)

and your divide_v3 becomes:

divide_v3 :: (Num a, SmartDivision a) => (a, a) -> a
divide_v3 (m, n) = (m + n) `smartDivide` 2

But something doesn't sounds very right about your problem, so I'm not
sure I recommend actually implementing the above.

regards,
iustin



More information about the Beginners mailing list