Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Divide Integer by Integer and get Double

I want to write a Haskell function which takes two Integers divedes them and outputs a Double.

The signature should look like this:

divide :: Integer -> Integer -> Double

The function I would like to have is:

divide x y = x / y

The error message I get wit this function is:

Couldn't match expected type ‘Double’ with actual type ‘Integer’

How to get a correct double result for this function?

like image 833
eugenkaltenegger Avatar asked Sep 17 '26 07:09

eugenkaltenegger


1 Answers

Haskell is a strongly typed language. That means that no implicit conversions re done. You can first convert the two numbers to a Double, for example with fromIntegral :: (Integral a, Num b) => a -> b, and then use (/) :: Fractional a => a -> a -> a:

divide :: Integer -> Integer -> Double
divide x y = fromIntegral x / fromIntegral y

Convertin a number to a Double can result in loss of precision however.

It might be better to return a Ratio, and thus use fractions, for example with the (%) :: Integral i => i -> i -> Ratio i, so then divide is just divide = (%).

You can, like @DanielWagner says use fromRational to covert the Rational to any Fractional type:

import Data.Ratio((%))

divide :: Fractional a => Integer -> Integer -> a
divide x y = fromRational (x % y)

So then you can still convert it to a Double:

Prelude Data.Ratio> divide 5 2 :: Double
2.5
like image 169
Willem Van Onsem Avatar answered Sep 20 '26 02:09

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!