f# - 在 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)
但是,这是行不通的。有没有另一种方法来处理这个问题?
解决方案
通过使用|>
管道值发送到最右边的未绑定参数(通过管道传递的值|>
发送到 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"
推荐阅读
- python - 将xml DOM结构形式的文件转换为python中的字典
- java - 我想将用户输入与字符串进行比较,如果无效,则程序应显示菜单。我该怎么做?
- ios - 在 iPhone 应用程序启动之前,我必须等待 1 分钟,使用 Xcode 12
- swift - iOS 14 是否有一些重大更改会禁用集合视图的垂直滚动?
- android - Jetpack Compose 中按钮的背景颜色
- python - 如何用 pypy 安装 h5py?
- mysql - 如果查询中有未使用的命名窗口,则窗口函数将忽略顺序
- winapi - 我想要一个矢量格式的代码来打印和显示所有C盘文件
- node.js - Angular Http POST 更改格式值
- sql - 在 Snowflake 存储过程中生成的动态 SQL 语句的最大长度是多少?