A
A
Anton @ Lyalin2017-11-25 10:26:28
Haskell
Anton @ Lyalin, 2017-11-25 10:26:28

How to replace a pair of characters with other pairs of characters in a string?

A string is entered, you need to replace a pair of characters in this line with another pair of characters, for example,
Such a string is "ababbbbaaa"
And replace ab with ba in Haskell

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2017-11-25
@toxa_1995

one-liner

f :: String -> String -> String -> String
f str a b = let n = length a in if take n str == a then b ++ f (drop n str) a b else if str == "" then "" else head str : f (tail str) a b

Solution properties: lazy, works with infinite strings, replaces the first occurrence of substring a with b in case of ambiguous replacement (e.g., f "aaa" "a" "b" == "ba"), time complexity O(N) in N = length(str).
What can be improved: 1) handling the tail of length < length(b), 2) formatting the code as a multi-line readable function, 3) making the \s -> fsab function local, or even changing the original order of the arguments.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question