stcol
stcol

Reputation: 141

What is the correct way to use fromIntegral to convert an Integer to real-fractional types?

I am trying to use fromIntegral to convert from Integer to a real-fractional type. The idea is to have a helper method to later be used for the comparison between two instances of a Fraction (whether they are the same).

I have read some of the documentation related to:

fromIntegral :: (Integral a, Num b) => a -> b
realToFrac :: (Real a, Fractional b) => a -> b

Where I am having trouble is taking the concept and make an implementation of the helper method that takes a Num data type with fractions (numerator and denominator) and returns what I think is a real-fractional type value. Here is what I have been able to do so far:

data Num = Fraction {numerator :: Integer, denominator :: Integer}

helper :: Num -> Fractional
helper (Fraction num denom) = realToFrac(num/denom)

Upvotes: 1

Views: 315

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120751

You need to learn about the difference between types and type classes. In OO languages, both are kind of the same concept, but in Haskell they're not.

  • A type contains concrete values. E.g. the type Bool contains the value True.
  • A class contains types. E.g. the Ord class doesn't contain any values, but it does contain the types which contain values that can be compared.

In case of numbers in Haskell it's a bit confusing that you can't really tell from the name whether you're dealing with a type or a class. Fractional is a class, whereas Rational is a type (which is an instance of Fractional, but so is e.g. Float).

In your example... first let's give that type a better name

data MyRational = Fraction {numerator :: Integer, denominator :: Integer}

...you have two possibilities what helper could actually do: convert to a concrete Rational value

helper' :: MyRational -> Rational

or a generic Fractional-type one

helper'' :: Fractional r => MyRational -> r

The latter is strictly more general, because Rational is an instance of Fractional (i.e. you can in fact use helper'' as a MyRational -> Rational function, but also as a MyRational -> Double function).

In either case,

helper (Fraction num denom) = realToFrac(num/denom)

does not work because you're trying to carry out the division on integer values and only then converting the result. Instead, you need to convert the integers to something fractional and then carry out the division in that type.

Upvotes: 3

Related Questions