无法将预期类型Double与实际Int匹配

时间:2014-09-19 13:20:20

标签: haskell math haskell-platform

我试图在不使用cosh函数的情况下计算ch值。

ch :: Double -> Int -> Double
ch' :: Double -> Int -> Integer -> Double -> Double

fac :: Integer -> Integer
fac 0 = 1
fac k | k > 0 = k * fac (k-1)

taylor :: Double -> Int -> Double
taylor x n = ((x^2*n))/ (2*(fac n))

ch x iter = ch' x iter 0 1
ch' x iter n sum | iter == fromIntegral n = sum
                 | iter /= fromIntegral n = ch' x iter (n+1) (sum + (taylor x n))

但我有错误:

Couldn't match expected type `Double` with actual type `Integer`
In the second argument of `(*)`, namely `n`
In the first argument of `(/)`, namely `((x ^ 2 * n))`

Couldn't match expected type `Double` with actual type `Integer`
In the second argument of `(*)`, namely `fac n`
In the first argument of `(/)`, namely `(2 *(fac n))`

我想我试图划分Double,但我已经得到了Integer。我怎么能解决这个问题?

非常感谢!

1 个答案:

答案 0 :(得分:3)

问题是算术运算符+*-具有类型

Num a => a -> a -> a

运营商双方的Num a必须相同的 aDoubleInteger都会实现Num,但您无法直接添加它们。相反,您必须将值转换为正确的类型。由于您从Double返回taylor,我猜测您要将Integer值转换为Double值。您可以使用fromInteger(实际上是Num类型类中的函数)轻松完成此操作:

taylor x n = (x^2 * fromInteger n) / (2 * fromInteger (fac n))

请注意,您必须在此计算中转换Integer个值。如果这看起来有点混乱,您可以随时使用where子句:

taylor x n = (x^2 * n')/ (2 * facn)
    where
        n' = fromInteger n
        facn = fromInteger $ fac n