rlperez
rlperez

Reputation: 1328

List of Tuples (key, val), replace all instances in a string where key exists with val

I know I can do this in an imperative manner pretty easily. What I want to figure out is how to do this in a functional manner. I feel like I should be able to accomplish this with either fold or map but I just can't work it out. Its been a long time since I have had education on functional programming.

Say I have tuples like (arbitrary length):

[|("X", 2);("Y", 3)|]

And a string like:

"X + Y"

I want a result of:

"2 + 3"

Thanks in advance.

Upvotes: 2

Views: 60

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243096

As you correctly guessed, you can do this using fold:

[|("X", 2);("Y", 3)|]
|> Seq.fold (fun (str:string) (orig, repl) -> 
     str.Replace(orig, string repl)) "X + Y"

The idea is that we use the string as the state (initial state is "X + Y"). The fold then iterates over all the replacements and, for every replacement, we return a new string. To do that, we replace the orig value with the new value repl, which is done by str.Replace(orig, string repl).

One thing that makes this tricky is that we need type annotation for str in order to call Replace (without this, F# would not know that str is a string).

Upvotes: 3

Related Questions