查看与 LazyList

View vs LazyList

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)

这段查找并转换正则表达式列表中的第一个匹配项的代码可以通过提前返回平均情况来改进

考虑到性能线程安全,使patterns成为惰性集合的最佳方法是什么?视图可以被多个线程重用还是应该为每次调用创建一个新视图 transform?

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

我仍然觉得使用单个正则表达式模式可能会有优势。

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)