2010-12-02 58 views
1
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'?我认为他们是诠释。

+0

哪一行是第16行? – luqui 2010-12-02 10:46:05

回答

4

你的类型太笼统。您正在通过xyisItSquare,这是Int s,但您不知道xyInt s。他们可能是,但他们也可以是Integral的任何其他实例。无论是签名更改为更为具体:

calc :: Int -> [(Int, Int, Int)] 

或你的辅助功能上更普遍的工种:

squareCheck :: (Integral a) => a -> Bool 
... 
3

您已声明sumOfSquare,hipotenuse,squareCheckisItSquareInt上操作。

但是,您所说的calc可以使用任何类型的a,只要aIntegral

要么宣布calc这样的:

calc :: Int -> [(Int, Int, Int)] 

...或者改变您的其他所有功能,像这样:

sumOfSquare :: (Integral a) => a -> a -> a 
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的类型签名绑定的刚性类型变量”的意思),并且x取自列表[1..a],所以它也具有类型a(并且与相同)。

相关问题