Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick elements in even index and odd index?

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?

like image 988
Leo Zhang Avatar asked Apr 09 '18 20:04

Leo Zhang


People also ask

How do you find the odd indexed elements of a 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.

How do you determine odd and even?

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.


1 Answers

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]).

like image 62
Elmex80s Avatar answered Sep 22 '22 11:09

Elmex80s