Using Fractions in Haskell

3.2k views Asked by At

Continuing from the previous question:

Power Series in Haskell

I am trying to write the power series in Haskell,

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

such that it will output

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

I already have a function here which works without the '/ (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 ]

However I am getting an error when I run

>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)

So again, it is a type error, which I do not understand.

I was told by @eakron to use the Data.Ratio package, but the (%) will print a ratio as so:

2%3

but I want

2/3

Could someone explain the type errors?

1

There are 1 answers

0
HKTonyLee On BEST ANSWER

After the first round of generator of powerSrsFunc, the input to the powerSrsFunc is not [2, 3..] anymore. Instead the input will become [1%2, 1%6, ..]. Obviously it can't be the input of factorial.

Why not rewriting the powerSrc to simpler one?

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

No nested infinity generator. Easier to understand.