在 Scala 中应用多个字符串转换 [英] Apply several string transformations in scala
问题描述
我想在 Scala 中以函数方式对字符串执行多个有序且连续的 replaceAll(...,...).
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 ! ;)
推荐答案
首先,让我们从 replaceAll
方法中取出一个函数:
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 = <function2>
现在您可以使用 Functor
实例作为函数,在 scalaz 中定义.这样你就可以使用 map
来组合函数(或者为了让它看起来更好,使用 unicode 别名).
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).
它看起来像这样:
scala> replace("from", "to") ∘ replace("to", "from") ∘ replace("some", "none")
res0: String => java.lang.String = <function1>
如果你更喜欢 haskell-way compose(从右到左),使用 contramap
:
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 = <function1>
你也可以通过 Category
获得一些乐趣 实例:
You can also have some fun with 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>
并应用它:
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
这篇关于在 Scala 中应用多个字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!