在scala中应用多个字符串转换

M'λ*_*'λ' 7 functional-programming scala scalaz

我想在scala中以函数方式对字符串执行几个有序和连续的replaceAll(...,...).

什么是最优雅的解决方案?Scalaz欢迎!;)

Kai*_*ito 15

如果它只是几个调用然后链接它们.否则我想我会试试这个:

Seq("a" -> "b", "b" -> "a").foldLeft("abab"){case (z, (s,r)) => z.replaceAll(s, r)}
Run Code Online (Sandbox Code Playgroud)

或者,如果您喜欢使用令人困惑的通配符和额外闭包的更短代码:

Seq("a" -> "b", "b" -> "a").foldLeft("abab"){_.replaceAll _ tupled(_)}
Run Code Online (Sandbox Code Playgroud)


fol*_*one 13

首先,让我们从replaceAll方法中获取一个函数:

scala> val replace = (from: String, to: String) => (_:String).replaceAll(from, to)
replace: (String, String) => String => java.lang.String = <function2>
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用Functor实例for function,在scalaz中定义.通过这种方式,您可以使用map(或使用unicode别名使其看起来更好)来组合函数.

它看起来像这样:

scala> replace("from", "to") ? replace("to", "from") ? replace("some", "none")
res0: String => java.lang.String = <function1>
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢haskell-way compose(从右到左),请使用contramap:

scala> replace("some", "none") ? replace("to", "from") ? replace ("from", "to")
res2: String => java.lang.String = <function1>
Run Code Online (Sandbox Code Playgroud)

您还可以通过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>
Run Code Online (Sandbox Code Playgroud)

并应用它:

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
Run Code Online (Sandbox Code Playgroud)

  • @M'λ',如果你不想引入Scalaz依赖,你可以使用`andThen`而不是`∘`和`compose`而不是`∙`,它们都是标准库的一部分. (11认同)