Take elements on even positions from the list

后端 未结 4 1191
感情败类
感情败类 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 07:50

    One ought not to calculate anything that doesn't need calculating. The choice is positional, it is already known in advance. Calculating the modulos, comparing with Booleans, is all superfluous work.

    Instead, do this, then do that, and go on switching like that; using foldr, as asked:

    evenly :: [t] -> [t]
    evenly xs = foldr c z xs f g
       where
       c x r f g = f x (r g f)
    

    Next we finish up the definitions, according to how each is used:

       z _ _  = []
       f _ xs = xs
       g x xs = x : xs
    

提交回复
热议问题