tolUene
tolUene

Reputation: 584

How can I replace a substring of a string with another in Haskell without using external Libraries like MissingH?

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 the Data.Text replace functions, but I don't want to port my entire program to use the Text type instead of Strings. Would packing the String into a Text value, then replacing what I wanted to, then unpacking that Text value to a String be slow on a lot of Strings?

Upvotes: 3

Views: 4184

Answers (2)

Santa Claus
Santa Claus

Reputation: 1002

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 !

Upvotes: 6

dave4420
dave4420

Reputation: 47062

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 Texts instead of Strings.

Upvotes: 8

Related Questions