1
votes

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]]
1
[everyf 3 xs, everyf 3 (tail xs), everyf 3 (drop 2 xs)]? Which generalization looks like [everyf 3 (drop 0 xs), everyf 3 (drop 1 xs), everyf 3 (drop 2 xs)] - zerkms
@zerkms sorry for being unclear, but i want this to work for any nth element, not just 3. I updated my question. - Chalupa

1 Answers

2
votes

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)