1

This is an extension of this question: Haskell replace characters in string

I would like to tweak the following expression to replace a char with a string

let replaceO = map (\c -> if c=='O' then 'X'; else c)

In the end, I would the following results (XX can be a string of any length):

replaceO "HELLO WORLD"
"HELLXX WXXRLD"
3
  • 2
    You won't be able to do this with just map, take a look at concat and consider (\c -> if c == 'O' then "X" else [c]). Notice that each character gets turned into a string instead. Commented Apr 20, 2015 at 15:51
  • That looks promising, but will it work for something like this: map (\x -> if x elem guesses then x else '-') word Commented Apr 20, 2015 at 16:22
  • What are you actually trying to do? Your comment here needs more context to make enough sense. If you're trying to replace certain characters with another character then you want map. If you are trying to replace certain characters with a new string, then use concatMap. Commented Apr 20, 2015 at 16:27

2 Answers 2

3

You can use concatMap:

let replace0 = concatMap (\c -> if c=='O' then "X" else "XX")
Sign up to request clarification or add additional context in comments.

1 Comment

The introduction to Monads are Trees with Grafting gives a good overview of the general concept of replacing elements with bigger pieces.
0

You kind formulate your problem in terms of traversing and accumulating based on a condition, something like this,

replace :: String -> Char -> String -> String
replace xs c s = foldr go [] xs

 where go x acc = if x == c  then acc ++ s
                             else acc ++ [x]

For you example:

>replace "HELLO WORLD" 'O' "XXX" 
> "HELLXXX WXXXRLD"

1 Comment

AFAICS, this has quadratic complexity. Appending "on the right" is inefficient. I'd switch to foldr, or use concatMap (as @Lee suggests) instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.