Skip to content

Instantly share code, notes, and snippets.

@gakuzzzz
Created July 3, 2011 12:05
Show Gist options
  • Save gakuzzzz/1062188 to your computer and use it in GitHub Desktop.
Save gakuzzzz/1062188 to your computer and use it in GitHub Desktop.
object PimpGrepToCollection {
implicit def toGrepCallable(list: Traversable[String]) = new {
def grep[A](regex: String)(func: String => A = identity _) =
list.collect {
case s if regex.r.findFirstIn(s).isDefined => func(s)
}
}
def main(args: Array[String]) {
println(List("aaa","123").grep("\\d"){_.toInt * 2}) // List(246)
println(Set("123", "456", "XXX").grep("\\d"){_.toInt}) // Set(123, 456)
println(Vector("A", "100", "XXX").grep("\\d"){_.toInt}) // Vector(100)
println(List(10, 100, 200).grep("\\d"){_.toInt}) // コンパイルエラー
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment