在Haskell中使用分数



从上一个问题继续:

Haskell中的Power系列

我试图在haskell中写下电源系列,

e^x = 1 + x + x^2/2! + x^3/3! + ...

这样,它将输出

[1,1,1/2,1/6,...]

我已经有一个函数,该函数在没有'/(fortorial 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

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

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

为什么不将powerSrc重写为更简单?

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

无嵌套的无限发生器。

更容易理解。

最新更新