6

我正在尝试用 Haskell 编写幂级数,

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

这样它就会输出

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

到目前为止,我得到了:

factorial 0 = 1 
factorial n = n * factorial (n - 1)

powerSrs x = 1 : powerSrsFunc[1..] where
        powerSrsFunc ( p: xs ) = 
            p : powerSrsFunc[y | y <-xs, ( (x^y) / (factorial y) )]

但是,我知道我在这里的输入是错误的。我收到此错误:

tut08.hs:8:58:
    No instance for (Integral Bool)
      arising from a use of `^'
    Possible fix: add an instance declaration for (Integral Bool)
    In the first argument of `(/)', namely `(x ^ y)'
    In the expression: ((x ^ y) / (factorial y))

    In a stmt of a list comprehension: ((x ^ y) / (factorial y))

tut08.hs:8:62:
    No instance for (Fractional Bool)
      arising from a use of `/'
    Possible fix: add an instance declaration for (Fractional Bool)
    In the expression: ((x ^ y) / (factorial y))
    In a stmt of a list comprehension: ((x ^ y) / (factorial y))
    In the first argument of `powerSrsFunc', namely
      `[y | y <- xs, ((x ^ y) / (factorial y))]'

1)如何在 Haskell 中编写分数,使其输出类似于“1/2”?

2) 当他们说 (Integral Bool) 和 (Fractional Bool) 没有实例时是什么意思?

它是指两个类型为 Integral 和 Bool 的参数吗?

不需要积分和积分吗?

4

2 回答 2

9

在列表理解语法中,您具有三个主要部分。以您的代码为例

[y | y <-xs, ( (x^y) / (factorial y) )]

从左边开始,您可以看到结果列表中的每个元素应该是什么。在您的情况下,只需 y。在竖线字符 (|) 之后,您将继续指定如何迭代输入列表。用英文“for each y in xs”。

最后一部分,也是你的问题,是过滤器。您可以放置​​一个逗号分隔的条件列表,这些条件都需要为真,以便列表推导不过滤掉当前的 y。与其在此处放置条件(是真还是假),不如在此处放置一个表达式,该表达式会产生一个数字。但是,我假设您实际上并不想过滤任何内容。相反,您希望输出该表达式的结果。所以它需要在管道字符的左侧。

[(x^y) / (factorial y) | y <-xs]

至于显示有理数,请查看 Data.Ratio 包http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Ratio.html

于 2012-10-21T14:32:37.523 回答
2

如果您有兴趣在 Haskell 中使用幂级数做更多事情,您应该查看 Douglas McIlroy(以 UNIX 闻名)的一篇精彩论文:www.cs.dartmouth.edu/~doug/pearl.ps.gz

在那里,他定义了幂级数的代数,允许您通过键入以下内容来定义幂:

expx = 1 + (integral expx)

并且还涉及其他很酷的东西,比如生成函数。

于 2012-10-23T23:58:15.497 回答