Possible Duplicate:
How to get every Nth element of an infinite list in Haskell?
Simple task – we have a list and want to leave only each nth element in that list.
What is the most idiomatic way to do it in haskell?
off the top of my head it is something like:
dr n [] = []
dr n (x : xs) = x : (dr n $ drop n xs)
but I have a strong feeling that I’m overcomplicating the problem.
Your solution is fine, but here are three other solutions using functions from Haskell’s base library.
Of coarse, this will never terminate (because
iteratenever terminates). So perhaps a better solution would be to useunfoldr:The function you pass to an unfold can get a bit ugly if you don’t know GHC extensions and concepts such as functors, here’s that solution again without the fancy foot-work (untested):
If you don’t like unfolds then consider a zip and a filter:
Review
Understand all these solutions are slightly different. Learning why will make you a better Haskell progammer.
dr1uses iterate and will thus never terminate (perhaps this is ok for infinite lists, but probably not a good overall solution):The
dr2solution will show everymth value by skipping values in the unfold. The unfold passes both the value to be used for the next unfolding and the result of the current unfolding in a single tuple.The
dr3solution is slightly longer but probably easier for a beginner to understand. First you tag every element in the list with a cycle of[1..n, 1..n, 1..n ...]. Second, you select only the numbers tagged with a1, effectively skippingn-1of the elements. Third you remove the tags.