在Haskell中使用分数

时间:2012-10-21 16:19:35

标签: haskell fractions rational-numbers

继续上一个问题:

Power Series in Haskell

我正在尝试在Haskell中编写幂函数,

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

这样它会输出

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

我已经有了一个没有'/(factorial 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

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

1 个答案:

答案 0 :(得分:3)

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

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

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

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