I am doing some exercises where I will generate an infinite sequence such that the nth number is the maximum power of 2 that divides into n. Hints ask me to first implement an auxiliary function interleave
which picks elements from two lists alternately. For example, interleave [1,2,3] [4,5,6]
produces [1,4,2,5,3,6]
. So I write a function mySeq n = interleave (repeat n) (mySeq (n+1))
and the desired answer is let n = 0 in mySeq n
. The overflow issue is in the implementation of interleave
.
The one that overflows is
interleave :: [a] -> [a] -> [a]
interleave [] y = y
interleave x [] = x
interleave (x:xt) (y:yt) = x : y : interleave xt yt
The one that works fine is
interleave :: [a] -> [a] -> [a]
interleave [] y = y
interleave (x:xt) y = x : interleave y xt
What causes the difference?