Reputation: 367
I want to write a function that returns every nth element of a given list but then updates the head to the second element and does this again until it has gone through all elements in the list. I know the code for going through every nth element in a list is:
everyf n [] = []
everyf n as = head as : everyf n (drop n as)
but this does not loop back. How can I get this to update head so that i get the following result:
everyf 3 [1,2,3,4,5,6,7]
returns [[1,4,7],[2,5],[3,6]]
Upvotes: 1
Views: 259
Reputation: 255095
Disclaimer: I don't know haskell (at all) :-)
listOfNths :: Int -> [a] -> [[a]]
listOfNths n xs = map (\x -> everyf n (drop x xs)) [0..n-1]
and a slightly "improved" version:
listOfNths :: Int -> [a] -> [[a]]
listOfNths n xs = map pickEveryf [0..n-1]
where pickEveryf = (everyf n) . (`drop` xs)
Upvotes: 2