在Haskel中的字符串替换函数中

时间:2016-10-28 22:15:11

标签: haskell

Haskell中是否存在一个函数,以便我可以像

那样提供它

replace "Hello" "GoodBye" "Hello World"

并返回类似

的内容

"GoodBye World"

如果不存在这样的功能,我该如何实现呢?

非常感谢!

3 个答案:

答案 0 :(得分:3)

使用Data.String.Utils提供的replace功能可以轻松完成此操作。

示例用法与您的代码段非常相似:

ghci> replace "Hello" "Goodbye" "Hello world"
"Goodbye world"

请注意,此功能是MissingH包的一部分。

最后,虽然这是第一个出现在互联网搜索引擎上的结果,Hoogle shows提供此功能的许多其他软件包,以及一些具有相同类型签名的relevant results

答案 1 :(得分:1)

哼。我觉得我真的应该回答这个糟糕的问题,但我无法抗拒。

replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace _ _ [] = []
replace old new xs@(x':xs')
  | old == front = new ++ replace old new rear
  | otherwise = x' : replace old new xs'
  where
    (front, rear) = splitLength old xs

splitLength :: [a] -> [b] -> ([b], [b])
splitLength [] ys = ([], ys)
splitLength _ [] = []
splitLength (_:xs) (y:ys) =
  let (l,r) = splitLength xs ys
  in (y:l, r)

有足够的空间来改进这种简单的实施。

答案 2 :(得分:0)

你可以使用上面提到的replace但是我决定自己实现同样的功能(可以这么说)我的比较有点不合理但是它实现了相同的结果

replace :: String -> String -> String -> String
replace x y frase = let find [] [] [] = []
                        find x' y' (h:t) = if h /= y'
                             then h ++ " "++ find x' y' t
                             else x' ++ " "++ find x' y' t
            in if y `elem` words frase
               then find x y (words frase) else frase

是迟到的,可能有些模式是多余的,你需要做的就是通过将frase制作成来自 Prelude words的单词来递归搜索匹配的字符串,如果有一个有效的工作版本,制作你自己的版本总是毫无意义,但我认为这将有助于你理解该功能如何工作,并可能实现自己的版本(为了好玩或学习)。