View vs LazyList

153 views Asked by At
val patterns = Seq(
  "the name and age are ([a-z]+), ([0-9]+)".r,
  "name:([a-z]+),age:([0-9]+)".r,
  "n=([a-z]+),a=([0-9]+)".r
)
def transform(subject: String): Option[String] = {
  patterns.map(_.unapplySeq(subject)).collectFirst { case Some(List(name, age)) => s"$name$age" }
}
println(transform("name:joe,age:42")) // Some(joe42)

This code that finds and transforms the first match in a list of regexes can be improved by returning early for the average case

What is the best way to make patterns a lazy collection taking into consideration performance and thread safety? Can a view be reused by multiple threads or should a new view be created for each invocation of transform?

  1. patterns.view
  2. patterns.to(LazyList)
1

There are 1 answers

2
jwvh On BEST ANSWER

I still feel that there could be advantages when using a single regex pattern.

val pattern = List("the name and age are (\\w+), (\\d+)"
                  ,"name:(\\w+),age:(\\d+)"
                  // add more as needed
                  ,"n=(\\w+),a=(\\d+)"
                  ).mkString("|").r

def transform(subject: String): Option[String] =
  pattern.findFirstMatchIn(subject)
         .map(_.subgroups.filter(_ != null).mkString)