2014-09-19 102 views
1

我試圖計算ch值而不使用cosh函數。無法匹配預期類型Double與實際Int

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))` 

我猜我試圖分裂雙,但我有整型。我如何解決這個問題?

非常感謝!

+0

可能重複[哈斯克爾,乘以INT和函數內浮動(http://stackoverflow.com/questions/19019093/ Haskell的倍增-INT-和浮子中之函數) – amalloy 2014-09-19 22:43:03

回答

3

的問題是,算術運算符+*-有型

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 
相關問題