samol samol - 1 month ago 9
Scala Question

How to chain operations in idiomatic scala

I want to apply a list of regex to a string. My current approach is not very functional

My current code:

val stopWords = List[String](
"the",
"restaurant",
"bar",
"[^a-zA-Z -]"
)

def CanonicalName(name: String): String = {
var nameM = name
for (reg <- stopWords) {
nameM = nameM.replaceAll(reg, "")
}

nameM = nameM.replaceAll(" +", " ").trim
return nameM
}

Answer

I think this does what you're looking for.

def CanonicalName(name: String): String = {
  val stopWords = List("the", "restaurant", "bar", "[^a-zA-Z -]")
  stopWords.foldLeft(name)(_.replaceAll(_, "")).replaceAll(" +"," ").trim
}
Comments