Selectively replace multiple instances of a character within a string: Difference between revisions

Content added Content deleted
Line 192: Line 192:


nthCharsReplaced :: M.Map Char [Maybe Char] -> String -> String
nthCharsReplaced :: M.Map Char [Maybe Char] -> String -> String
nthCharsReplaced ruleMap = snd . mapAccumL go M.empty
nthCharsReplaced ruleMap = snd . mapAccumL go ruleMap
where
where
go a c =
go a c =
case M.lookup c ruleMap of
case M.lookup c a of
Nothing -> (a, c)
Nothing -> (a, c)
Just ds ->
Just ds ->
let i = fromMaybe 0 (M.lookup c a)
if null ds
in ( M.insert c (succ i) a,
then (a, c)
if i < length ds
else
then fromMaybe c (ds !! i)
( M.adjust tail c a,
else c
fromMaybe c (head ds)
)
)