我现在正试图解决Project Euler的第9个问题,但是Haskell不会停止对我说不匹配的类型。问题是,ghci告诉我它期望的类型与函数类型定义中给出的类型不同。
以下是代码:
solvePyth :: Int -> Int -> Float
solvePyth x y
|valid = x * y * z
|otherwise = if y < x then solvePyth x (y + 1) else solvePyth (x + 1) 1
where z = sqrt $ fromIntegral $ x^2 + y^2
valid = (x^2 + y^2 == z^2) && (x + y + z == 1000)
以下是我得到的错误:
Prelude> :l debug
[1 of 1] Compiling Main ( debug.hs, interpreted )
debug.hs:3:14:
Couldn't match expected type `Float' with actual type `Int'
In the first argument of `(*)', namely `x'
In the first argument of `(*)', namely `x * y'
debug.hs:3:18:
Couldn't match expected type `Float' with actual type `Int'
In the second argument of `(*)', namely `y'
In the first argument of `(*)', namely `x * y'
debug.hs:6:33:
Couldn't match expected type `Int' with actual type `Float'
In the first argument of `(^)', namely `z'
In the second argument of `(==)', namely `z ^ 2'
Failed, modules loaded: none.
我不明白为什么(*)
和(^)
期待Floats和Ints,在检查他们使用:t
输入ghci时显示他们的争论只需要被视为Nums。