Haskell中的电源系列

ali*_*ali 6 haskell power-series

我正在尝试在Haskell中编写电源系列,

e^x = 1 + x + x^2/2! + x^3/3! + ...
Run Code Online (Sandbox Code Playgroud)

这样就可以了

[1,1,1/2,1/6,...]
Run Code Online (Sandbox Code Playgroud)

到目前为止我得到了:

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) )]
Run Code Online (Sandbox Code Playgroud)

但是,据我所知,我在这里打字是错误的.我收到此错误:

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))]'
Run Code Online (Sandbox Code Playgroud)

1)如何在Haskell中编写分数,使其输出为"1/2"?

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

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

它不是积分和积分吗?

Joh*_*son 9

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

[y | y <-xs, ( (x^y) / (factorial y) )]
Run Code Online (Sandbox Code Playgroud)

从左侧开始,您将获得结果列表中每个元素的内容.在你的情况下,简单地说.在管道字符(|)之后,您继续指定如何迭代输入列表.用英语"for x in x".

最后一部分和您的问题是过滤器.您可以将逗号分隔的条件列表放在列表推导中,而不是过滤掉当前的y.而不是在那里放置一个条件(某些事情是真或假),你在那里放一个表达式,产生一个数字.但是,我认为你实际上并不想过滤任何东西.相反,您想要输出该表达式的结果.所以它需要在管道角色的左边.

[(x^y) / (factorial y) | y <-xs]
Run Code Online (Sandbox Code Playgroud)

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