2008/7/22 Dmitri O.Kondratiev <[EMAIL PROTECTED]>:
> 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
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to