Take elements on even positions from the list

后端 未结 4 1217
感情败类
感情败类 2020-12-21 07:11

Problem: using fold, take from the list elements which are on the even positions:

GHCi> evenOnly [1..10]
 [2,4,6,8,10]
GHCi> evenOnly [\'a\'..         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 08:08

    Pattern matching is a perfectly reasonable approach:

    evenOnly :: [a] -> [a]
    evenOnly (_ : a : as) = a : evenOnly as
    evenOnly _ = []
    

    Another option is to use a list comprehension:

    evenOnly as = [a | (a, True) <- zip as (cycle [False, True])]
    

    The list comprehension version will likely be a bit more efficient if it fuses with other list processing functions.

提交回复
热议问题