本文介绍了在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撰写(从右到左),请使用反转图

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

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

这篇关于在scala中应用几个字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 05:54