Created
July 1, 2011 22:16
-
-
Save kmizu/1059522 to your computer and use it in GitHub Desktop.
Add grep method to any collection that holds String.
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
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) |
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.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