简体   繁体   English

如何理解Haskell的“1.2%3.4”的错误消息?

[英]How to understand error messages for “1.2 % 3.4” for Haskell?

How to understand error messages for "1.2 % 3.4" for Haskell? 如何理解Haskell的“1.2%3.4”的错误消息?

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

<interactive>:11:1:
    No instance for (Show a0) arising from a use of ‘print’
    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> 

This type error message is a little unfriendly, me thinks. 我想,这种类型的错误信息有点不友好。

What is actually happening here is that your expression has 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 has to be integer-like, while Fractional a means that it has to be floating-point or rational-like. Integral a表示类型a必须是整数类,而Fractional a表示它必须是浮点或类似理论。 There are no types in standard Haskell which are both. 标准Haskell中没有类型都是。

When evaluating this expression in order to print it, GHCi first infers its type, with the additional restriction that it needs to printable: 在评估此表达式以进行打印时,GHCi首先推断其类型,并提供需要打印的附加限制:

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

Now since this is still too ambiguous to evaluate, GHCi tries defaulting a to either Integer or Double . 现在由于评估仍然过于模糊,GHCi尝试将a 默认IntegerDouble But neither of them fits here, each is a member of just one of the classes Integral and Fractional . 但它们都不适合这里,每个都只是IntegralFractional类中的一个。

Then, after failing at defaulting, GHCi gives an error message that tells you one of the constraints it was failing to satisfy. 然后,在默认失败后,GHCi会给出一条错误消息,告诉您它无法满足的约束条件之一 And particularly confusingly, it happens to choose the one which has nothing to do with why it failed... 特别令人困惑的是,碰巧选择与失败原因无关的那个......

Anyway, to fix your problem: % is not the function to divide two rationals, it is the function to construct a rational from an integer-like numerator and denominator. 无论如何,要解决你的问题: % 不是划分两个有理数的函数,它是从类似整数的分子和分母构造一个有理数的函数。 To divide them instead, use 要改为划分它们,请使用

4.3 / 1.2 :: Rational

The :: Rational tells GHCi that you want a rational (rather than the default Double it would otherwise choose), and floating-point notation does work to make a Rational - it is one of the features the Fractional typeclass provides. :: Rational告诉GHCi你想要一个有理的(而不是它本来会选择的默认的Double ),并且浮点符号确实可以构成一个Rational - 它是Fractional类型类提供的特性之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM