:m +Data.R...">

How to understand error messages for "1.2% 3.4" for Haskell?

How to understand error messages for "1.2% 3.4" for Haskell?

Prelude> :m +Data.Ratio
Prelude Data.Ratio> 4.3 % 1.2

<interactive>:11:1:
    No instance for (Show a0) arising from a use ofprint
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance Show Double -- Defined in ‘GHC.Float’
      instance Show Float -- Defined in ‘GHC.Float’
      instance (Integral a, Show a) => Show (Ratio a)
        -- Defined in ‘GHC.Real’
      ...plus 23 others
    In a stmt of an interactive GHCi command: print it
Prelude Data.Ratio> 

      

+3


source to share


1 answer


This type error message is a bit unfriendly I guess.

What actually happens here is that your expression is of type

Prelude Data.Ratio> :t 4.3 % 1.2
4.3 % 1.2 :: (Integral a, Fractional a) => Ratio a

      

Integral a

means your type a

must be an integer, which Fractional a

means that it must be float or rational. There are no types in standard Haskell that are both.

When evaluating this expression to print it, GHCi first infers its type, with the additional constraint required to print it:

(Integral a, Fractional a, Show a) => Ratio a

      



Now, since it is still too ambiguous to estimate, GHCi tries to default a

either Integer

or Double

. But none of them fit here, each of them is a member of only one of the classes Integral

and Fractional

.

Then, after failing by default, GHCi gives an error message that tells you one of the constraints it was unable to satisfy. And especially vaguely, it happens that he chooses the one that has nothing to do with why he failed ...

Anyway, to fix your problem: %

not a function to separate two rational, this is a function to construct a rational from an integer numerator and a denominator. To separate them use

4.3 / 1.2 :: Rational

      

:: Rational

tells GHCi that you want to use rational (and not the default Double

, which it would otherwise choose), and the floating point notation is working on Rational

- this is one of the Fractional

typeclass functions .

+5


source







All Articles