Skip to content

Instantly share code, notes, and snippets.

@jedws
Created September 28, 2011 03:03
Show Gist options
  • Save jedws/1246880 to your computer and use it in GitHub Desktop.
Save jedws/1246880 to your computer and use it in GitHub Desktop.
ZipWith adds a zipWith(f: A => B): C[(A, B)] to any collection
object ZipWith {
implicit def pimpToZipWith[A, CC[A] <: Iterable[A]](cc: CC[A]) = new ZipWith(cc)
class ZipWith[A, CC[A] <: Iterable[A]](cc: CC[A]) {
import collection.generic.CanBuildFrom
def zipWith[B](f: A => B)(implicit cbf: CanBuildFrom[CC[A], (A, B), CC[(A, B)]]): CC[(A, B)] = {
val builder = cbf()
cc foreach { a => builder += (a -> f(a)) }
builder.result
}
}
}
usage:
scala> import ZipWith._
import ZipWith._
scala> val is = List(1, 2, 3)
is: List[Int] = List(1, 2, 3)
scala> is zipWith (_ + 100)
res0: List[(Int, Int)] = List((1,101), (2,102), (3,103))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment