Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created July 1, 2011 22:16
Show Gist options
  • Save kmizu/1059522 to your computer and use it in GitHub Desktop.
Save kmizu/1059522 to your computer and use it in GitHub Desktop.
Add grep method to any collection that holds String.
scala> import PimpGrepToCollection._
import PimpGrepToCollection._
scala> List("123", "156", "C").grep("\\d"){_.toInt}
res0: List[Int] = List(123, 156)
scala> Set("123", "456", "XXX").grep("\\d"){_.toInt}
res1: scala.collection.immutable.Set[Int] = Set(123, 456)
scala> Vector("A", "100", "XXX").grep("\\d"){_.toInt}
res2: scala.collection.immutable.Vector[Int] = Vector(100)
import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
object PimpGrepToCollection {
class GrepCallable[C[X] <: TraversableLike[X, C[X]]](tr: C[String]){
def grep[A](regex:String)(func:String => A = identity _)(implicit bf: CanBuildFrom[C[String], A, C[A]]):C[A] =
tr.collect[A, C[A]]{
case s if regex.r.findFirstIn(s).isDefined => func(s)
}
}
implicit def toGrepCallable[C[X] <: TraversableLike[X, C[X]]](tr: C[String]): GrepCallable[C] = new GrepCallable[C](tr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment