如何在Haskell中使用另一个字符串替换字符串的子字符串而不使用像MissingH这样的外部库? [英] How can I replace a substring of a string with another in Haskell without using external Libraries like MissingH?
问题描述
我想用Haskell中的一个字符串替换一个子字符串,而不使用外部库,并且如果可能的话,性能良好。
I would like to replace a substring with a string in Haskell, without using external libraries, and, if it is possible, with good performance.
我想过使用 数据。 Text
替换函数,但我不想移植我的整个程序来使用 Text
类型,而不是字符串
。将 String
打包成一个 Text
值,然后替换我想要的内容,然后将该文本值解包为 String
对很多字符串
很慢。
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
?
推荐答案
试试这个(未经测试):
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
将改变你的程序使用 Text
s而不是 String
s。
But in general you will get performance gains from switching your program to use Text
s instead of String
s.
这篇关于如何在Haskell中使用另一个字符串替换字符串的子字符串而不使用像MissingH这样的外部库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!