I have a string with some tokens in it like this:
"There are two things to be replaced. {Thing1} and {Thing2}"
I want to replace each token with different values so the final result looks like this:
"There are two things to be replaced. Don and Jon"
I created a function that chains String.Replace like this
let doReplacement (message:string) (thing1:string) (thing2:string) =
message.Replace("{Thing1}", thing1).Replace("{Thing2}", thing2)
the problem is that when I chain .Replace, the values have to stay on the same line. Doing this does not work:
let doReplacement (message:string) (thing1:string) (thing2:string) =
message
.Replace("{Thing1}", thing1)
.Replace("{Thing2}", thing2)
To allow me to do a multi-line chain, I was thinking of something like this:
message
|> replaceString "{Thing1}" thing1
|> replaceString "{Thing2}" thing2
with a supporting function like this:
let replaceString (message:string) (oldValue:string) (newValue:string) =
message.Replace(oldValue, newValue)
However, that does not work. Is there another way to handle the problem?
By using |>
the piped value is send to the rightmost unbound parameter (value piped by |>
is send to thing2).
By reversing the order of parameters it works as expected.
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"
It compiles if you indent the method calls:
let doReplacement (message:string) (thing1:string) (thing2:string) =
message
.Replace("{Thing1}", thing1)
.Replace("{Thing2}", thing2)
This is a style I have often seen in C# and it seems pretty logical to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With