Haskell Replace characters in string with string

2019-09-06 12:20发布

问题:

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"

回答1:

You can use concatMap:

let replace0 = concatMap (\c -> if c=='O' then "X" else "XX")


回答2:

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"