Replace in Haskell
Haskell seems to be missing a String replace function. Text.Regex.subRegex seemed like overkill. So I wrote one. It actually works on any list, not just Strings.
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace [] _ _ = []
replace s find repl =
if take (length find) s == find
then repl ++ (replace (drop (length find) s) find repl)
else [head s] ++ (replace (tail s) find repl)
Some examples:
*Main> replace "hello" "h" "" "ello" *Main> replace "hello" "l" "" "heo" *Main> replace "hello" "x" "" "hello" *Main> replace "100,000,000" "," "hello" "100hello000hello000" *Main> replace "100,000,000" "," "" "100000000" *Main> replace [1,2,3] [1] [9] [9,2,3] *Main> replace [4,5,6,1,2,3,7,8,9,2,3,6,5,4,1,2,3] [1,2,3] [10] [4,5,6,10,7,8,9,2,3,6,5,4,10]
If this function is already in the standard libraries somewhere or if this can be improved in some way please leave a comment to let me know. Thanks!
About this entry
You’re currently reading “ Replace in Haskell ,” an entry on bluebones.net
- Published:
- 2007.01.16
- Category:
- Programming
5 Comments
Jump to comment form | comments rss [?] | trackback uri [?]