[Haskell-cafe] Newbie: Replacing substring?

Roberto Zunino zunino at di.unipi.it
Tue Jul 22 11:39:40 EDT 2008


Dmitri O.Kondratiev wrote:
> I wrote my own version,  please criticize:
> 
> -- replace all occurances of "123" with "58" in a string:
> test = replStr "abc123def123gh123ikl" "123" "58"

This is a tricky problem: first of all, you fail your own test! ;-)

*Main> test
"abc58def58gh58ikl58"

(Note the extra 58 at the end.)

Other common pitfalls:

*Main> replStr "abc1123def" "123" "58"
"abc1158def58"

(extra 1 ?)

*Main> replStr "abc12123def" "123" "58"
"abc121258def58"

(extra 12 ?)

A useful function from Data.List: stripPrefix

(Of course, there are more efficient string match algorithms)

Regards,
Zun.


More information about the Haskell-Cafe mailing list