0

前の質問からの続き:

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

誰かが型エラーを説明できますか?

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 に答える