user1203803
user1203803

Reputation:

Replacing multiple substrings with respective replacements

I have a String that contains several tags in the form ${...} (where ... can be any string that doesn't contain a } character), for example foo ${bar} baz ${qux}.

I would like to replace these tags, but to do that I need a function in the form:

replace :: [String] -> [String] -> String -> String
--           tags    replacements  target    result
replace ["${bar}", "${qux}"] ["abc", "def"] "foo ${bar} baz ${qux}" == "foo abc baz def"

(This is similar to PHP's str_replace function when given arrays as arguments.)

I couldn't find such a replace function in any package. Is there such a function, and if there isn't how would I write it (pointing in the right direction is enough; I'm learning Haskell)?

Upvotes: 3

Views: 374

Answers (1)

lbolla
lbolla

Reputation: 5411

As a one-liner:

Prelude Data.Text> Prelude.foldr (uncurry Data.Text.replace) "foo ${bar} baz ${qux}" $ Prelude.zip ["${bar}", "${qux}"] ["abc", "def"]
"foo abc baz def"

In other words:

replace as bs x = Prelude.foldr (uncurry Data.Text.replace) x $  Prelude.zip as bs

Upvotes: 4

Related Questions