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

前端 未结 2 636
误落风尘
误落风尘 2020-12-19 22:17

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

相关标签:
2条回答
  • 2020-12-19 22:40

    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.

    0 讨论(0)
  • 2020-12-19 22:52

    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 !

    0 讨论(0)
提交回复
热议问题