繁体   English   中英

还有另一种类型错误

[英]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)]

错误信息:

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。

您的类型太笼统了。 你逝去的xyisItSquare ,这是expecing Int S,但你不知道, xyInt秒。 它们可以是,但也可以是Integral任何其他实例。 将签名更改为更具体:

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

或者让您的助手功能处理更通用的类型:

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

您已将sumOfSquarehipotenusesquareCheckisItSquare为对Int

但是,您已经说过calc可以使用任何类型a ,只要aIntegral

可以这样声明calc

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

...或像这样更改所有其他功能:

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具有类型a (签名明确表示,这就是“是由calc的类型签名绑定的刚性类型变量”的意思),并且x从列表[1..a] ,因此它也具有类型a (与y相同)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM