I want to perform several ordered and successive replaceAll(...,...) on a string in a functional way in scala.
What\'s the most elegant solution ? Scalaz welcome ! ;
First, let's get a function out of the replaceAll method:
scala> val replace = (from: String, to: String) => (_:String).replaceAll(from, to)
replace: (String, String) => String => java.lang.String =
Now you can use Functor instance for function, defined in scalaz. That way you can compose functions, using map (or to make it look better, using unicode aliases).
It will look like this:
scala> replace("from", "to") ∘ replace("to", "from") ∘ replace("some", "none")
res0: String => java.lang.String =
If you prefer haskell-way compose (right to left), use contramap:
scala> replace("some", "none") ∙ replace("to", "from") ∙ replace ("from", "to")
res2: String => java.lang.String =
You can also have some fun with Category instance:
scala> replace("from", "to") ⋙ replace("to", "from") ⋙ replace("some", "none")
res5: String => java.lang.String =
scala> replace("some", "none") ⋘ replace("to", "from") ⋘ replace ("from", "to")
res7: String => java.lang.String =
And applying it:
scala> "somestringfromto" |> res0
res3: java.lang.String = nonestringfromfrom
scala> res2("somestringfromto")
res4: java.lang.String = nonestringfromfrom
scala> "somestringfromto" |> res5
res6: java.lang.String = nonestringfromfrom
scala> res7("somestringfromto")
res8: java.lang.String = nonestringfromfrom