Int类与整型类的实例 [英] Int vs Integer in class instance
问题描述
class Visible a where
toString :: a -> String
size :: a -> Int
intToString :: (Integral t) => t -> String
intToString 0 = "0"
intToString 1 = "1"
intToString 2 = "2"
intToString 3 = "3"
intToString 4 = "4"
intToString 5 = "5"
intToString 6 = "6"
intToString 7 = "7"
intToString 8 = "8"
intToString 9 = "9"
intToString n
| ((div n 10) == 0) = (intToString (mod n 10))
| otherwise = (intToString (div n 10)) ++ (intToString (mod n 10))
现在
Now
instance Visible Int where
toString = intToString
size n = length (toString n)
在提示符下给我一个关于模糊类型变量的错误,如果我输入类似的东西(toString 55)
gives me an error about an ambiguous type variable at the prompt if I type something like (toString 55)
但是
but
instance Visible Integer where
toString = intToString
size n = length (toString n)
不。
给出了什么?
推荐答案
这里有两件事情。请记住,Haskell中的数字文字是多态的。即:
There are two things going on here. Remember that numeric literals in Haskell are polymorphic. That is:
x = 55
确实意味着
really means
x :: Num a => a
x = fromIntegral 55
对于编写它们的任何地方都是如此。这可能会很麻烦,所以GHCi实现了缺省类型:它假设裸数为整数
或双精度
if
This is true for all numbers anywhere you write them. This can be awkward to work with, so GHCi implements type defaulting: it assumes that bare numbers are Integers
or Doubles
if the type is ambiguous.
当您在GHCi提示符下输入 toString 55
时,GHCi推断类型(可见a,数字a)=>如果你只有
Visible Int
作为范围,那么缺省类型为 Integer
不起作用,因为它没有满足类约束(没有 Visible Integer
),所以GHCi抱怨模糊的类型变量,因为它不知道为表达式实例化的类型。如果你在范围内有 Visible Integer
,Integer类型的默认值就可以工作了。
When you write toString 55
at the GHCi prompt, GHCi infers the type (Visible a, Num a) => a
for the number 55. If you only have Visible Int
in scope, the type default of Integer
doesn't work because it doesn't fulfill the class constraint (there's no Visible Integer
), so GHCi complains about the ambiguous type variable because it doesn't know which type to instantiate for the expression. If you do have Visible Integer
in scope, the type default of Integer works just fine.
如果你想使用除Integer以外的类型,可以使用显式类型,如 toString(55 :: Int)
If you want to use a type other than Integer, you can use an explicit type as in toString (55 :: Int)
这篇关于Int类与整型类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!