3

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?

2
  • what type does (/) have? Commented Mar 19, 2020 at 17:39
  • 3
    fromInteger is your friend. Commented Mar 19, 2020 at 17:39

1 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

You can get the good behavior of % (namely, dealing correctly with numbers too large to fit in a Double but whose ratio is small enough or vice versa) and the "good" type of divide by combining the two: divide' :: Integer -> Integer -> Double; divide' x y = fromRational (x % y).
Thank you for your answer! The signature is given from an example I need to do for university.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.