I would like to replace a substring with a string in Haskell, without using external libraries, and, if it is possible, with good performance.
I thought about using
Try this (untested):
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace needle replacement haystack
= case begins haystack needle of
Just remains -> replacement ++ remains
Nothing -> case haystack of
[] -> []
x : xs -> x : replace needle replacement xs
begins :: Eq a => [a] -> [a] -> Maybe [a]
begins haystack [] = Just haystack
begins (x : xs) (y : ys) | x == y = begins xs ys
begins _ _ = Nothing
But in general you will get performance gains from switching your program to use Text
s instead of String
s.
Here is my solution
import Data.List (intercalate)
import Data.List.Split (splitOn)
replace from to = intercalate to . splitOn from
Example
replace "squirrel" "platypus" "Daddy, I want a squirrel !"
Daddy, I want a platypus !