tags:

views:

139

answers:

1

I'm a C# guy trying to teach myself Haskell from Erik Meijer's Channel 9 webcasts. I came across an interesting puzzle which involved skipping every 'n' elements of a list using zip and mod.

every :: Int -> [a] -> [a]
every _ [] = []
every n xs = [x | (x,i) <- zip xs [1..], i `mod` n == 0]

I've been thinking it might be more efficient (for really large lists, or streams) if we could avoid using mod.

I thought about lazily creating a repeating list of integers so we can simply compare the value of i to n.

repeatInts :: Int -> [Int]

such that calling repeatInts 3 returns [1,2,3,1,2,3,1,2,3,1,2,3,..] ad infinitum.

Given this, we could redefine every like so:

every :: Int -> [a] -> [a]
every _ [] = []
every n xs = [x | (x,i) <- zip xs (repeatInts n), i == n]

So my questions is: how would you implement repeatInts?

+9  A: 

Use cycle:

cycle :: [a] -> [a]  

cycle ties a finite list into a circular one, or equivalently, the infinite repetition of the original list. It is the identity on infinite lists.

You could define repeatInts in terms of cycle:

*Main> let repeatInts n = cycle [1..n]
*Main> :t repeatInts
repeatInts :: (Num t, Enum t) => t -> [t]
*Main> take 10 $ repeatInts 3
[1,2,3,1,2,3,1,2,3,1]
Greg Bacon
Thanks, gbacon. Somehow I knew there'd be a simple answer! Now I can dig into the workings of `cycle`.
Damian Powell
`cycle xs = xs ++ cycle xs` I'd guess ;-)
THC4k
The doc for `cycle` has a link to its source: http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/src/GHC-List.html#cycle
Greg Bacon
Somewhat strangely, `cycle` is standard Haskell '98, even though cyclic lists are not. See what the source (above) says about it - you might or might not get a cyclic list...
Charles Stewart