Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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

like image 272
tolUene Avatar asked Feb 17 '13 14:02

tolUene


1 Answers

You can breakOn the substring,

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

to split the Text into two parts at the first occurrence of the pattern, then replace the substring at the start 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
like image 124
Daniel Fischer Avatar answered Nov 01 '22 03:11

Daniel Fischer