Take elements on even positions from the list

后端 未结 4 1208
感情败类
感情败类 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:04

    (.) is function composition but zip g xs is a list not a function. You can just apply the resulting list as the argument to foldr directly. Note you have the arguments g and xs in the wrong order:

    evenOnly :: [a] -> [a]
    evenOnly xs = let g = iterate (\x -> (x + 1) `mod` 2) 0
      in
      foldr (\ (x, n) s -> if n == 1 then x : s else s) [] (zip xs g)
    

提交回复
热议问题