3

Let's say I have a string I want to modify:

str = "I have several paints. For example, red, green, and blue." 

I want to turn it into: I have several paints. For example, XXX, XXX, and blue.

So I have a list of words to replace with XXX:

colors = ["red", "green"]

I want to replace the colors from colors in str. Here's what I have so far:

  • First, a function to replace something with "xxx": subColor pat str = subRegex (mkRegex pat) str "xxx"
  • Next, I'm trying to map that or fold it over the list of colors. But I'm stuck: map just returns copies of the string, each with a single word replaced, and I've been getting errors with foldl. What am I doing wrong?

Edit: I should also say that I will sometimes have multi-line words, so using words (as suggested in another similar question's answers) isn't really practical for me.

Edit2: I should add that one big regex pattern, like blue|red probably wouldn't work for me either, since I actually have several thousand of these things to replace.

2
  • 3
    Why does "several thousand things to replace" imply "one big regex pattern wouldn't work"? Commented Aug 22, 2019 at 4:29
  • Really really looks like a foldl(/foldr) type of problem. With your order of the arguments in subCOlot (pat before str) I guess foldr just fits? foldr subColor str colors Commented Aug 22, 2019 at 12:54

1 Answer 1

3

What you want isn't map over several pats and get a list of new strs, but apply subColor pat for each pat and combine these functions and apply it to str:

subColors :: [String] -> String -> String
subColors pats str = foldMap (Endo . subColor) pats str

In above code, the foldMap use the instance Monoid (Endo a), which is same as foldr (.) id.

And, I still suggest you try the "one big regex pattern" solution, since a regex engine should do more optmization than you do, but that depends on the implementation of the regex engine, so if performance matters, you need to have a test first.

Sign up to request clarification or add additional context in comments.

3 Comments

Why complicate it? Why not just foldr subColor pats str?
@JosephSible You mean foldr subColor str pats ? That is a good idea !
Yep, I got them backwards. That's what I meant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.