I have a list, I want to break the list into two, one with elements in the even indexes, and the other from the odd indexes.
breakByIndexes :: [a] -> ([a], [a])
For example:
> breakByIndexes ["A", "B", "C", "D"]
(["A", "C"], ["B", "D"]
> breakByIndexes ["A", "B", "C", "D", "E"]
(["A", "C", "E"], ["B", "D"]
I got a solution like this
breakByIndexes [] = ([], [])
breakByIndexes [e] = ([e], [])
breakByIndexes (e:o:xs) =
let (es, os) = breakByIndexes xs
in (e : es, o : os)
But I'm curious is it possible to implement without using recursion?
And is it possible to implement by composing existing functions from Data.List
?
One way is using the range() function, such that it starts at the first odd index, 1 , and has a step value of 2 , so that it returns the odd indices 1, 3, 5, ... . Another way to obtain the odd indices of a list is using list comprehension, in which you can use a condition that will only include the odd indices.
If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd.
Yes you are right, using the partition
function from Data.List
.
Prelude Data.List> (s, u) = partition (even . fst) (zip [0 .. ] "ABCD")
Prelude Data.List> (_, s2) = unzip s
Prelude Data.List> (_, u2) = unzip u
Prelude Data.List> (s2, u2)
("AC","BD")
How I found this? Go to Hoogle and fill in [a] -> ([a], [a])
.
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