Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining string.replace in F#

Tags:

f#

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?

like image 298
Jamie Dixon Avatar asked Jun 18 '18 10:06

Jamie Dixon


2 Answers

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"
like image 119
ZiggZagg Avatar answered Nov 17 '22 16:11

ZiggZagg


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.

like image 7
TheQuickBrownFox Avatar answered Nov 17 '22 16:11

TheQuickBrownFox