powers_of :: (Integral a) => a -> [Integer]
powers_of n = sequence
where
sequence = 1 : next sequence
next (first : rest) = (n * first) : next rest
This get me:
Could not deduce (a ~ Integer)
from the context (Integral a)
bound by the type signature for
powers_of :: Integral a => a -> [Integer]
at Triangle.hs:(10,1)-(13,61)
`a' is a rigid type variable bound by
the type signature for powers_of :: Integral a => a -> [Integer]
at Triangle.hs:10:1
Expected type: [Integer]
Actual type: [a]
In the expression: sequence
In an equation for `powers_of':
powers_of n
= sequence
where
sequence = 1 : next sequence
next (first : rest) = (n * first) : next rest
当我去掉Integral
类型类并使签名仅为Integer -> [Integer]
时,一切都很好。为什么会这样?是类型推断系统的某种故障吗?
这绝对不是推理系统的故障。这是一个成功的推理系统。
观察到(*) :: Num a => a -> a -> a
。注意到(*)
的第一个论点必须与powers_of
的论点统一。观察到(*)
的结果必须与powers_of
的结果列表的元素类型一致。
这三件事加在一起,说明powers_of
的实参类型必须与结果列表的元素类型相同。
错误消息告诉您,它没有任何上下文来证明a
和Integer
是相同的类型,这是函数进行类型检查所需要的
你的类型签名应该是:
powers_of :: (Integral a) => a -> [a]
或
powers_of :: (Num a) => a -> [a]
1
的类型是Num a => a
, (*)
的类型是Num a => a -> a -> a
,所以你可以提供任何Num
实例并生成该类型的列表。
没有办法隐式地将Num
实例转换为Integer
实例。如果需要,可以显式地这样做:
powers_of :: (Integral a) => a -> [Integer]
powers_of n = sequence
where
sequence = 1 : next sequence
next (first : rest) = ((fromIntegral n) * first) : next rest