[Haskell-cafe] Newbie: Replacing substring?

Dmitri O.Kondratiev dokondr at gmail.com
Tue Jul 22 10:26:45 EDT 2008


A few simple questions:
What standard library function can be used to replace substring in a string
(or sub-list in a list) ?
I wrote my own version,  please criticize:

-- replace all occurances of "123" with "58" in a string:
test = replStr "abc123def123gh123ikl" "123" "58"

{--
In a string replace all occurances of an 'old' substring with a 'new'
substring
--}
replStr str old new = foldr ((\newSub before after -> before ++ newSub ++
after) new) [] chunks
                      where chunks = splitStr str old

{--
Split string into a list of chunks.
Chunks are substrings located in a string between 'sub' substrings
--}
splitStr str sub = mkChunkLst str sub []
    where
      -- mkChunkLst 'src string' 'substr-to-extract' 'list of chunks'
      -- makes list of chunks located between 'substr-to-extract' pieces in
src string
      mkChunkLst [] _ chunkLst = chunkLst
      mkChunkLst str sub chunkLst = mkChunkLst after sub (chunkLst ++
[chunk])
          where
            (chunk, _, after) = takeOut str sub [] []

{--
Take out substring from a string.
String is divided into:
"before substr" ++ "match" ++ "after substr"
where 'match' is substring to split out
--}

takeOut after [] before match = (before, match, after)
takeOut [] _ before match = (before, match, [])
takeOut (x:xs) (y:ys) before match
       | x == y = takeOut xs ys before (match ++ [x])
       | otherwise = takeOut xs (y:ys) (before ++ match ++ [x]) []

-- 
Dmitri O. Kondratiev
dokondr at gmail.com
http://www.geocities.com/dkondr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080722/2cde5308/attachment.htm


More information about the Haskell-Cafe mailing list