2

I know that infinite sequences are possible in Haskell - however, I'm not entirely sure how to generate one

Given a method

generate::Integer->Integer

which take an integer and produces the next integer in the sequence, how would I build an infinite sequence out of this?

sth
  • 222,467
  • 53
  • 283
  • 367
Martin
  • 12,469
  • 13
  • 64
  • 128

3 Answers3

14

If you want your sequence to start from 1 then it is -

iterate generate 1

Please notice that first letter of function is lowercase, not uppercase. Otherwise it would be data type, not function.

//edit: I just realized not just data types start with capital, it could be data constructor or type class as well, but that wasn't the point. :)

Martin Jonáš
  • 2,309
  • 15
  • 12
13

Adding to Matajon's answer: a way to discover the iterate function other than asking here would be to use Hoogle.

Hoogle's first answer for the query (a -> a) -> [a] is iterate.

Update (2023): Hoogle's scoring appears to have changed and iterate is no longer given with this query. It's full type has another a parameter and with the full type it is given in the results.

yairchu
  • 23,680
  • 7
  • 69
  • 109
7

There are several ways to do it, but one is:

gen :: (a -> a) -> a -> [a]
gen f s = s : gen f (f s)

This function takes a functon f and some valus s and returns s, after wich it calls itself with that same f, and the result of f s. Demonstration:

Prelude> :t succ
succ :: (Enum a) => a -> a
Prelude> let gen f s = s : gen f (f s)
Prelude> take 10 $ gen succ 3
[3,4,5,6,7,8,9,10,11,12]

In the above example succ acts as the function generate :: Integer -> Integer which you mention. But observe that gen will work with any function of type a -> a.

Edit: and indeed, gen is identical to the function iterate from the Prelude (and Data.List).

Stephan202
  • 59,965
  • 13
  • 127
  • 133