More specifically, how do I generate a new list of every Nth element from an existing infinite list?
E.g. if the list is [5, 3, 0, 1, 8, 0, 3, 4, 0, 93, 211, 0
A lot of answers here already use Data.List.unfoldr, but I wanted to bring up an interesting way of writing the somewhat annoying unfold that may be helpful in other contexts:
{-# LANGUAGE TupleSections #-}
import Data.List (unfoldr)
import Data.Maybe (listToMaybe)
every n = unfoldr f . drop (n - 1)
where f xs = (,drop n xs) <$> listToMaybe xs
When the list is null, listToMaybe
returns a Nothing
, and fmap
similarly will then be Nothing
. However, if a Just
is produced, then the proper tuple is constructed by turning the head of the list into a tuple of the head and the rest of the values to use in the next iteration.