We have the following function:
repartir [a] -> ([a],[a])
So partition should partition the main list into two lists by taking the elements like this:
repartir [1,2,3,4,5]
---> ([1,3,5],[2,4])
repartir "hola"
---> ("hl","oa")
We can only import:import Data.List
Greetings and thank you
A more efficient solution, without using module functions
Data.List
and going through the list only once, could be this:In these cases it is best to go step by step simplifying the problem.
You can see the cast as two separate cases (the two elements of the tuple). The first takes two from the list discarding the second and the second from the tuple also takes two but discards the first.
For the first:
But...
The obvious is missing, the closing case. Now it would be:
Now fails on odd:
Easy to fix. You add this case:
Case 2 is the same but you discard the first item and keep the second. With odd amount of elements you ignore it.
And finally you put the two cases together.
Optimization is left to the student. ;-)
A direct way:
The operator
!!
is not very efficient on lists, so don't overuse it. A more efficient version:PS: It was not necessary to import the module
Data.List
since the necessary functions are included in thePrelude
There is a better solution using types
Either
. The downside is that you need to import the moduleData.Either
: