Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 297
Hellnar Avatar asked Mar 21 '10 13:03

Hellnar


1 Answers

You can define a list of ones up to a certain number and then sum the first to the second by keeping the former intact (and so on) like this:

ones :: Integer -> [Integer]
ones n
  | n <= 0    = []
  | otherwise = one n []
    where
      one 1 a = (1:a)
      one n a = one (n-k) (one k a)
        where
          k = (n-1)

sumOf :: [Integer] -> [Integer]
sumOf l = sof l []
  where
    sof [] a = a
    sof (x:[]) a = (x:a)
    sof (x:y:zs) a = sof (x:a) (sof ((x+y):zs) a)

Since they're all ones, you can increment them in any way that you feel like, from left to right, to a middle point and so on, by changing the order of their sum. You can test this up to one hundred (or more) by using:

(sumOf . ones) 100

Edit: for its simplification, read the comments below by Will Ness.

like image 114
Marco_O Avatar answered Sep 22 '22 21:09

Marco_O