First, letβs get the function from the replaceAll
method:
scala> val replace = (from: String, to: String) => (_:String).replaceAll(from, to) replace: (String, String) => String => java.lang.String = <function2>
Now you can use the Functor
instance for the function in scalaz. This way you can create functions using map
(or, to make it better, using unicode aliases).
It will look like this:
scala> replace("from", "to") β replace("to", "from") β replace("some", "none") res0: String => java.lang.String = <function1>
If you prefer the haskell-way layout (from right to left), use contramap
:
scala> replace("some", "none") β replace("to", "from") β replace ("from", "to") res2: String => java.lang.String = <function1>
You can also have some fun with the Category
instance :
scala> replace("from", "to") β replace("to", "from") β replace("some", "none") res5: String => java.lang.String = <function1> scala> replace("some", "none") β replace("to", "from") β replace ("from", "to") res7: String => java.lang.String = <function1>
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