Skip to content

Instantly share code, notes, and snippets.

@ShaneDelmore
Created September 29, 2016 20:42
Show Gist options
  • Select an option

  • Save ShaneDelmore/6441e9f3dac4330a2c0995c9705d0160 to your computer and use it in GitHub Desktop.

Select an option

Save ShaneDelmore/6441e9f3dac4330a2c0995c9705d0160 to your computer and use it in GitHub Desktop.
CanBuildFrom example
import scala.collection._
import scala.collection.generic._
implicit class TraversableLikeOps[+T, +Repr](val seq: SeqLike[T, Repr]) {
def zipWithNext[That](implicit c: CanBuildFrom[Repr, (T, T), That]): That = {
val builder = c(seq.repr)
val is = seq.toIndexedSeq
builder ++= is.zip(is.drop(1))
builder.result
}
def zipWithNextImperitive[That](implicit c: CanBuildFrom[Repr, (T, T), That]): That = {
val builder = c(seq.repr)
val second = seq.toIterator.drop(1)
seq.foreach{ elem =>
if (second.hasNext) builder += (elem -> second.next())
}
builder.result
}
}
println(Vector(1, 2, 3).zipWithNext)
println(Vector(1, 2, 3).zipWithNextImperitive)
println(List(1, 2, 3).zipWithNext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment