Apply several string transformations in scala

前端 未结 5 1832
温柔的废话
温柔的废话 2020-12-09 21:18

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 ! ;

5条回答
  •  情书的邮戳
    2020-12-09 22:06

    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
    

提交回复
热议问题