[英]And another one type error
sumOfSquare :: Int -> Int -> Int
sumOfSquare a b = a * a + b * b
hipotenuse :: Int -> Int -> Int
hipotenuse a b = truncate(sqrt(x))
where x = fromIntegral(sumOfSquare a b)
squareCheck :: Int -> Bool
squareCheck n = truncate(sqrt(x)) * truncate(sqrt(x)) == n
where x = fromIntegral n
isItSquare :: Int -> Int -> Bool
isItSquare a b = squareCheck (sumOfSquare a b)
calc :: (Integral a) => a -> [(a, a, a)]
calc a = [(x, y, (hipotenuse x y)) | x <- [1..a], y <-[1..a], (isItSquare x y)]
Error message: 错误信息:
Prelude> :load "some.hs"
[1 of 1] Compiling Main ( some.hs, interpreted )
some.hs:16:74:
Couldn't match expected type `Int' against inferred type `a'
`a' is a rigid type variable bound by
the type signature for `calc' at some.hs:15:18
In the first argument of `isItSquare', namely `x'
In the expression: (isItSquare x y)
In a stmt of a list comprehension: (isItSquare x y)
Failed, modules loaded: none.
As I understand the type of 'x' and 'y'. 据我了解,“ x”和“ y”的类型。 Is it right?
这样对吗? Is it square require the Int.
是否需要Int的平方。 But what is the type 'x' and 'y'?
但是“ x”和“ y”是什么类型? I thinked they are Int.
我以为他们是Int。
Your type is too general. 您的类型太笼统了。 You are passing
x
and y
to isItSquare
, which is expecing Int
s, but you don't know that x
and y
are Int
s. 你逝去的
x
和y
到isItSquare
,这是expecing Int
S,但你不知道, x
和y
是Int
秒。 They could be, but they could be any other instance of Integral
as well. 它们可以是,但也可以是
Integral
任何其他实例。 Either change the signature to the more specific: 将签名更改为更具体:
calc :: Int -> [(Int, Int, Int)]
Or have your helper functions work on more general types: 或者让您的助手功能处理更通用的类型:
squareCheck :: (Integral a) => a -> Bool
...
You've declared sumOfSquare
, hipotenuse
, squareCheck
and isItSquare
as operating on Int
. 您已将
sumOfSquare
, hipotenuse
, squareCheck
和isItSquare
为对Int
。
However, you've said that calc
can use any type a
, as long as a
is Integral
. 但是,您已经说过
calc
可以使用任何类型a
,只要a
是Integral
。
Either declare calc
like this: 可以这样声明
calc
:
calc :: Int -> [(Int, Int, Int)]
...or change all your other functions like this: ...或像这样更改所有其他功能:
sumOfSquare :: (Integral a) => a -> a -> a
calc :: (Integral a) => a -> [(a, a, a)]
calc a = [(x, y, (hipotenuse x y)) | x <- [1..a], y <-[1..a], (isItSquare x y)]
a
has type a
(the signature explicitly says so, that's what "is a rigid type variable bound by the type signature for calc
" means), and x
is taken from the list [1..a]
, so it also has type a
(and same for y
). a
具有类型a
(签名明确表示,这就是“是由calc
的类型签名绑定的刚性类型变量”的意思),并且x
从列表[1..a]
,因此它也具有类型a
(与y
相同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.