Haskell: use Data.Text.replace to replace only the first occurrence of a text value

How to replace only the first occurrence of "substring" (actually Data.Text.Text) with the value "Text" in Haskell in the most efficient way?

+3


source to share


1 answer


You can breakOn

substring,

breakOn :: Text -> Text -> (Text, Text)

      



split Text

into two on the first occurrence of the pattern, then replace the substring at the beginning of the second component:

replaceOne :: Text -> Text -> Text -> Text
replaceOne pattern substitution text
  | T.null back = text    -- pattern doesn't occur
  | otherwise = T.concat [front, substitution, T.drop (T.length pattern) back] 
    where
      (front, back) = breakOn pattern text

      

+10


source







All Articles