Question

I am trying to write the power series in Haskell,

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

such that it will out put

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

so far I got:

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

However, I understand that my typing here is wrong. I am getting this error:

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) How do you write fractions in Haskell such that it is output like '1/2'?

2) What does it mean when they say No instance for (Integral Bool) and (Fractional Bool)?

Is it referring to two arguments that are of type Integral and Bool?

Does it not take Integral and Integral?

Was it helpful?

Solution

In list comprehension syntax you have three main parts. Taking your code as example

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

Beginning from the left, you have what each element in the resulting list should be. In your case, simply y. After the pipe character (|) you continue by specifying how to iterate over the input list. In English "for each y in xs".

The last part, and your problem, is the filters. You can put a comma separated list of conditions that all need to be true for the list comprehension not to filter out the current y. Instead of putting a condition there (something that is true or false) you put an expression there that results in a number. However, I assume you dont actually want to filter on anything. Rather, you want to output the result of that expression. So it needs to be to the left of the pipe character.

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

As far as displaying rational numbers, take a look at the Data.Ratio package http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Ratio.html

OTHER TIPS

If you are interested in doing more with power series in Haskell you should check out a great paper by Douglas McIlroy (of UNIX fame): www.cs.dartmouth.edu/~doug/pearl.ps.gz

There he defines an algebra over power series which allows you to define exponentiation by typing:

expx = 1 + (integral expx)

and also goes into other cool stuff like generating functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top