0

继续上一个问题:

Haskell 中的幂级数

我正在尝试用 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

有人可以解释类型错误吗?

4

1 回答 1

3

在 的第一轮生成器之后powerSrsFunc, 的输入powerSrsFunc不再是 [2, 3..]。相反,输入将变为 [1%2, 1%6, ..]。显然它不能是 的输入factorial

为什么不重写powerSrc更简单的呢?

powerSrs x = [ (x^y) % (factorial y) | y <- [0..] ]

没有嵌套的无穷大生成器。更容易理解。

于 2012-10-21T17:00:14.123 回答