Created
September 29, 2016 20:42
-
-
Save ShaneDelmore/6441e9f3dac4330a2c0995c9705d0160 to your computer and use it in GitHub Desktop.
CanBuildFrom example
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
| 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