Take elements on even positions from the list

后端 未结 4 1192
感情败类
感情败类 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
    
    0 讨论(0)
  • 2020-12-21 08:03

    You can just zip the above together with a sequence of numbers, like:

    evenOnly :: [a] -> [a]
    evenOnly = foldr (\(c, x) -> if c then (x:) else id) [] . zip (cycle [False, True])

    Here cycle [False, True] thus generates an infinite list of [False, True, False, True, …]. In the foldr we check the corresponding value c that originates from the cycle [False, True]. If it is True, then we prepend the list with x, otherwise we just pass the result of the recursive call with id.

    Or we can omit this, and use:

    evenOnly :: [a] -> [a]
    evenOnly = foldr (uncurry ($)) [] . zip (cycle [const id, (:)])
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题