0
繼續從前面的問題:使用餾分
我試圖寫在Haskell冪級數,
e^x = 1 + x + x^2/2! + x^3/3! + ...
,使得其輸出
[1,1,1/2,1/6,...]
我已經在這裏有一個函數沒有'/(階乘y)'
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
powerSrs x = 1 : powerSrsFunc[1..] where
powerSrsFunc (p: xs) =
p : powerSrsFunc[ (x^y)%(factorial y) | y <-xs ]
然而,當我運行
>take 5 (powerSrs 1)
<interactive>:34:9:
Ambiguous type variable `a0' in the constraints:
(Fractional a0)
arising from a use of `powerSrs' at <interactive>:34:9-16
(Integral a0)
arising from a use of `powerSrs' at <interactive>:34:9-16
(Num a0) arising from the literal `1' at <interactive>:34:18
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `take', namely `(powerSrs 1)'
In the expression: take 5 (powerSrs 1)
In an equation for `it': it = take 5 (powerSrs 1)
所以我再次得到一個錯誤,這是一種錯誤,我不明白。
我被告知@eakron使用Data.Ratio包,但(%)將打印的比例爲這樣:
2%3
,但我想
2/3
有人能解釋類型錯誤?
你的方法有點混亂和緩慢。更聰明的方法是'e x = map fst $ iterate(\(t,n) - >(t * x/n,n + 1))(1,1)'。這個想法是,要在系列中找到一個術語,就足以知道它的索引和它之前的術語。 –