[Haskell-cafe] Newbie: Replacing substring?

Ronald Guida oddron at gmail.com
Tue Jul 22 16:38:53 EDT 2008


2008/7/22 Dmitri O.Kondratiev <dokondr at gmail.com>:
> On the side: The more I use Haskell - the more I like it ! It helps me think
> about the problem I solve much more clearly then when I use imperative
> language.

If I want to replace a substring in a string, then I would search my
string left to right, looking for any occurrence of the substring.  If
I find such an occurrence, I would replace it and continue searching
from immediately after the replacement.  This algorithm can be
directly expressed in Haskell.  More efficient algorithms do exist.

replaceStr :: String -> String -> String -> String
replaceStr [] old new = []
replaceStr str old new = loop str
  where
    loop [] = []
    loop str =
      let (prefix, rest) = splitAt n str
      in
        if old == prefix                -- found an occurrence?
        then new ++ loop rest           -- yes: replace it
        else head str : loop (tail str) -- no: keep looking
    n = length old


More information about the Haskell-Cafe mailing list