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)]
错误讯息:
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.
据我了解'x'和'y'的类型。这样对吗?是方形需要Int。但是'x'和'y'是什么类型的?我认为他们是Int。
答案 0 :(得分:4)
你的类型太笼统了。您正在将x
和y
传递给isItSquare
,这是Int
,但您不知道x
和y
是Int
秒。它们可以是,但它们也可以是Integral
的任何其他实例。将签名更改为更具体的:
calc :: Int -> [(Int, Int, Int)]
或者让您的帮助函数适用于更常规的类型:
squareCheck :: (Integral a) => a -> Bool
...
答案 1 :(得分:3)
您已将sumOfSquare
,hipotenuse
,squareCheck
和isItSquare
声明为Int
。
但是,您已经说calc
可以使用任何类型a
,只要a
为Integral
。
要么像这样声明calc
:
calc :: Int -> [(Int, Int, Int)]
...或更改所有其他功能:
sumOfSquare :: (Integral a) => a -> a -> a
答案 2 :(得分:2)
calc :: (Integral a) => a -> [(a, a, a)]
calc a = [(x, y, (hipotenuse x y)) | x <- [1..a], y <-[1..a], (isItSquare x y)]
a
的类型为a
(签名明确表示如此,这是“calc
的类型签名绑定的刚性类型变量”和{{1} }取自列表x
,因此它也有[1..a]
类型(a
也相同)。