首页 > 解决方案 > 在 F# 中链接 string.replace

问题描述

我有一个带有一些标记的字符串,如下所示:

"There are two things to be replaced.  {Thing1} and {Thing2}"

我想用不同的值替换每个标记,所以最终结果如下所示:

"There are two things to be replaced.  Don and Jon"

我创建了一个像这样链接 String.Replace 的函数

let doReplacement (message:string) (thing1:string) (thing2:string) =
    message.Replace("{Thing1}", thing1).Replace("{Thing2}", thing2)

问题是当我链接 .Replace 时,这些值必须保持在同一行。这样做不起作用:

let doReplacement (message:string) (thing1:string) (thing2:string) =
    message
    .Replace("{Thing1}", thing1)
    .Replace("{Thing2}", thing2)

为了让我做一个多线链,我在想这样的事情:

message
|> replaceString "{Thing1}" thing1
|> replaceString "{Thing2}" thing2

具有这样的支持功能:

let replaceString (message:string) (oldValue:string) (newValue:string) =
    message.Replace(oldValue, newValue)

但是,这是行不通的。有没有另一种方法来处理这个问题?

标签: f#

解决方案


通过使用|>管道值发送到最右边的未绑定参数(通过管道传递的值|>发送到 thing2)。通过颠倒参数的顺序,它可以按预期工作。

let replaceString (oldValue:string) (newValue:string) (message:string) =
    message.Replace(oldValue, newValue)

let message = "There are two things to be replaced.  {Thing1} and {Thing2}"
let thing1 = "Don"
let thing2 = "Jon"

message
|> replaceString "{Thing1}" thing1
|> replaceString "{Thing2}" thing2
|> printfn "%s"

推荐阅读