[Haskell-cafe] Newbie: Replacing substring?

Chaddaï Fouché chaddai.fouche at gmail.com
Wed Jul 23 09:20:58 EDT 2008

2008/7/22 Ronald Guida <oddron at gmail.com>:
> 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.

Your idea but expressed in a more elegant fashion (maybe...) :
replace :: (Eq a) => [a] -> [a] -> [a] -> [a]
replace _ _ [] = []
replace old new xs@(y:ys) =
  case stripPrefix old xs of
    Nothing -> y : replace old new ys
    Just ys' -> new ++ replace old new ys'


More information about the Haskell-Cafe mailing list