Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

elm

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"])
like image 356
ocupe Avatar asked Dec 22 '22 21:12

ocupe


1 Answers

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.

like image 63
glennsl Avatar answered Mar 04 '23 19:03

glennsl