Search code examples
listelm

How to split a list into two lists by even and odd positions?


I want to split a arbirtray list of elements by position into two new lists containing all the even and odd elements.

Example: With a list like this:

["a", "b", "c", "d", "e"]

how can I get two lists like this:

(["a", "c", "e"], ["b", "d"])

Solution

  • Single pass and much less code:

    evensAndOdds : List a -> (List a, List a)
    evensAndOdds =
      List.foldr (\item (a, b) -> (item :: b, a)) ([], [])
    

    The trick here is to switch the position of the elements of the returned tuple on each iteration, thereby alternating which one is appended to without having to keep track of the index.