Created
February 25, 2010 22:03
-
-
Save machisuji/315088 to your computer and use it in GitHub Desktop.
Splitting a list into two lists containing alternating elements of the original list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// way faster than split2m | |
def split2f[T](list: Seq[T]): (Seq[T], Seq[T]) = { | |
val it = Iterator.iterate(true)(!_) | |
list.partition(_ => it.next) | |
} | |
// next approach, incredibly slow | |
// @TODO learn functional programming | |
def split2m[T](list: Seq[T]): (Seq[T], Seq[T]) = | |
list.foldLeft((Seq[T](), Seq[T]())) { | |
(tuple: (Seq[T], Seq[T]), element: T) => | |
if (tuple._1.size <= tuple._2.size) (tuple._1 :+ element, tuple._2) | |
else (tuple._1, tuple._2 :+ element) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment