bobjohnson
bobjohnson

Reputation: 11

How to implement an infinite list of functions in Haskell

I am using a version of the Fibonacci function g where:

g :: Integer -> Integer -> Integer
g i n  |  i==0   = 0
       |  i==1   = n
       |  i>1    = (n*( (g (i-1) n) + (g (i-2) n) ))

...such that g i n is the value of gi(n) and the partial definition g i is gi

I now want to define an infinite list of functions: gs :: [ Integer -> Integer ], such that (gs !! i) is gi.

I want take 5 $ [ g 3 | g <- gs] to give me [0,3,9,36,135].

Can anyone help me define this infinite list?

Upvotes: 1

Views: 1379

Answers (1)

sepp2k
sepp2k

Reputation: 370455

You can get a list of all numbers starting at 0 using [0 ..]. Once you have that, it's just a matter of applying g to each of them.

You can do this using a list comprehension like you did in your example usage:

gs = [g i | i <- [0 ..]]

Or using map:

gs = map g [0 ..]

Upvotes: 4

Related Questions