我正在创建一个带有三个字符串值w1,w2和s的函数,并返回s但是所有出现的字符串w1都被w2替换。
我已经完成了,但是有一个错误。如果w1只在字符串s中一次,它工作正常。但如果它多次出现,它就不起作用。例如:
Main> swapwords "turtles" "goats" "more turtles are becoming blind"
"more goats are becoming blind"
swapwords "turtles" "goats" "the blue turtles, dislike the green turtles"
"the blue turtles, dislike the green goats"
这是当前的代码:
split :: String -> Char -> String -> [String]
split "" _ "" = []
split "" _ r = [r]
split (x:xs) c ""
| x == c = [[c]] ++ split xs c ""
| otherwise = split xs c [x]
split (x:xs) c r
| x == c = r : [[c]] ++ split xs c ""
| otherwise = split xs c (r ++ [x])
swap :: String -> String -> [String] -> [String]
swap a b [] = []
swap a b (x:xs)
|x==a = [b] ++ xs
|x/=a = [x] ++ swap a b (xs)
join :: [String] -> String
join [] = ""
join (x:xs) = x ++ join (xs)
swapwords :: String -> String -> String -> String
swapwords a b "" = []
swapwords a b c = join (swap a b d)
where d = split c ' ' []
如果有人知道解决方案,它会帮助我加载。感谢
答案 0 :(得分:2)
您的错误在这里:
swap :: String -> String -> [String] -> [String]
swap a b [] = []
swap a b (x:xs)
|x==a = [b] ++ xs -- <<< here
|x/=a = [x] ++ swap a b (xs)
当您找到单词a
时,您将其替换为b
,但之后您想继续交换列表的其余部分。