In Haskell, what is the most common way to apply a function to every Nth element of a list?

Very often, when I come across some list of xs elements and want to do something with every Nth element. The simplest example is a sieve or Erastothenes, where you want to “knock out” each short given prime. Two ways I could do this would be explicit recursion going through the counter variable; or zipWith ($) (cycle (replicate (n-1) id ++ f)) . So, which way is better / more elegant / more often used, or is there some library function, for example mapEveryN :: (a -> a) -> Int -> [a] -> [a] , which I did not find?

+6
source share
1 answer

As you and bheklilr mention, cycle provides a good way to accomplish this. You can use the tape a bit though:

 mapEvery :: Int -> (a -> a) -> [a] -> [a] mapEvery nf = zipWith ($) (drop 1 . cycle . take n $ f : repeat id) 

Using zipWith and cycle seems more idiomatic (complex behavior consisting of simpler behavior) than a manual recursive function combining both tasks.

Note: tail here makes this function undefined for n = 0 , so drop 1 is preferred.

There is no library function that I know of for this.

+2
source

Source: https://habr.com/ru/post/975836/


All Articles