TheLeonKing
TheLeonKing

Reputation: 3601

Haskell: Different ways to convert division of Integers to Double

Say I want to divide 5 (Integer) by 3 (Integer), and I want my answer to be a Double. What different ways are there to do this in Haskell?

Upvotes: 1

Views: 1122

Answers (2)

user824425
user824425

Reputation:

The most common approaches involve converting the Integers to Doubles and then dividing them. You can do this through fromIntegral :: (Integral a, Num b) => a -> b, which takes any value of an integer-like type (e.g. Integer) and turns it into any number-like type (e.g. Double).

let five, three :: Double
    five = fromIntegral (5 :: Integer)
    three = fromIntegral (3 :: Integer)
in five / three

Note that fromIntegral = fromInteger . toInteger, where toInteger is part of the Integral class (toInteger turns a value of an integer-like type into the corresponding Integer value), and fromInteger is part of the Num class (fromInteger turns an Integer value into a value of any desired number-like type). In this case, because you already have an Integer value, you could use fromInteger instead of fromIntegral.

A much less common approach would be to somehow create a Rational number and converting it:

let five, three, fiveThirds :: Rational
    five = toRational (5 :: Integer)
    three = toRational (3 :: Integer)
    fiveThirds = five / three
in fromRational fiveThirds

The other way to do create Rationals (somehow) depends on which standard you're using. If you've imported Ratio (Haskell 98) or Data.Ratio (Haskell 2010), you can also use the (%) :: (Integral a) => a -> a -> Ratio a operator:

let five, three :: Integer
    fiveThirds :: Rational
    five = 5
    three = 3
    fiveThirds = five % three
in (fromRational fiveThirds :: Double)

Upvotes: 3

aochagavia
aochagavia

Reputation: 6246

The type signature of / is:

(/) :: Fractional a => a -> a -> a

This means that, if you want to get a Double from / you will need to provide doubles, not integers. Therefore, I would suggest using a function such as fromIntegral, as shown below:

fromIntegral (5 :: Integer) / fromIntegral (2 :: Integer) == 2.5

Upvotes: 1

Related Questions