Skip to content

Instantly share code, notes, and snippets.

@diversit
Created April 17, 2018 09:26
Show Gist options
  • Save diversit/2d18b372eddd06f9c325c05635f81e95 to your computer and use it in GitHub Desktop.
Save diversit/2d18b372eddd06f9c325c05635f81e95 to your computer and use it in GitHub Desktop.
Split a Seq[A] into (Seq[B], Seq[C]) so can retrieve multiple Seq's while just looping over the Seq just once.
/**
* Extend [[Seq]] with a function to seperate an element into multiple parts.
* This allows to go over the [[Seq]] only once and retrieve multiple [[Seq]]s as a result.
* Convenient for changing a Seq of [[Tuple2]] into 2 Seq's of the tuple elements.
*/
implicit class SeqWithSplitOn[A](val seq: Seq[A]) extends AnyVal {
/**
* Split an element into 2 parts using function `f`.
* Note: simply use the [[identity()]] function for splitting a [[Tuple2]] element.
*
* @param f Function to apply to each element.
* @tparam B Type of first part.
* @tparam C Type of second part.
* @return Two sequences of B's and C's.
*/
def splitElement[B,C](f: A => (B, C)): (Seq[B], Seq[C]) = {
seq.foldLeft((Seq.empty[B], Seq.empty[C])) {
case ((seqB, seqC), elem) =>
val (b, c) = f(elem) // seperate the element into 2 parts
(seqB :+ b, seqC :+ c)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment