Logo

Programming-Idioms

History of Idiom 63 > diff from v16 to v17

Edit summary for version 17 by :

Version 16

2015-09-05, 10:21:30

Version 17

2015-09-05, 10:30:11

Idiom #63 Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.

Idiom #63 Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.

Imports
import Data.List
Imports
import Data.List
Code
replacing input pattern replacement =
 if isPrefixOf pattern input
 then replacement ++ 
        replacing (drop (length from) input) pattern replacement
 else if null input then []
 else (head input) : replacing (tail input) pattern replacement

x2 = replacing x y z
Code
allchanged [] _ _ = []
allchanged input from to = if isPrefixOf from input
  then to ++ allchanged (drop (length from) input) from to
  else head input : allchanged (tail input) from to

x2 = allchanged x y z