【问题标题】:Couldn't match expexted type Double with actual Int无法将扩展类型 Double 与实际 Int 匹配
【发布时间】:2014-09-19 13:20:20
【问题描述】:

我尝试在不使用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。我该如何解决这个问题?

非常感谢!

【问题讨论】:

标签: haskell math haskell-platform


【解决方案1】:

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

Num a => a -> a -> a

Num a 必须相同 a 在运算符两侧。 DoubleInteger 都实现了Num,但不能直接添加。相反,您必须将值转换为正确的类型。由于您从taylor 返回Double,我猜您想将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

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2019-04-23
    • 1970-01-01
    • 2016-11-21
    • 2012-09-14
    相关资源
    最近更新 更多