How to get every Nth element of an infinite list in Haskell?

后端 未结 23 1277
再見小時候
再見小時候 2020-12-04 23:58

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

23条回答
  •  有刺的猬
    2020-12-05 00:40

    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.

提交回复
热议问题