listhaskellstreamlazy-evaluation

Haskell, list of natural number


I am an absolute newbie in Haskell yet trying to understand how it works.

I want to write my own lazy list of integers such as [1,2,3,4,5...].

For list of ones I have written

ones = 1 : ones

and when tried, works fine:

*Main> take 10 ones
[1,1,1,1,1,1,1,1,1,1]

How can I do the same for increasing integers ?

I have tried this but it indeed fails:

int  = 1 : head[ int + 1]

And after that how can I make a method that multiplies two streams? such as:

mulstream s1 s2 = head[s1] * head[s2] : mulstream [tail s1] [tail s2]

Solution

  • The reasons that int = 1 : head [ int + 1] doesn't work are:

    The easiest way to create the list counting up from 1 to infinity is [1..]

    To count in steps other than 1 you can use [firstElement, secondElement ..], e.g. to create a list of all positive odd integers: [1, 3 ..]

    To get infinite lists of the form [x, f x, f (f x), f (f (f x)),...] you can use iterate f x, e.g. iterate (*2) 1 will return the list [1, 2, 4, 16,...].

    To apply an operation pairwise on each pair of elements of two list, use zipWith:

    mulstream s1 s2 = zipWith (*) s1 s2
    

    To make this definition more concise you can use the point-free form:

    mulstream = zipWith (*)