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"])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With