findReplace :: [String] -> [Char] -> [Char]-> String
findReplace [] _ _ = []
findReplace (h:t) x y
|h == x = y : findReplace t --recursion, if the 'letter' == 'x' replace it with y
|otherwise = h : findReplace t
大家好,我是 Haskell 的一名新学生,我试图用给定的字符替换字符串中的字符,但我的代码缺少一些我无法弄清楚的东西。
答案 0 :(得分:3)
你的函数签名不正确,一个字符串已经是一个字符列表,所以你不需要列表的方括号。
对于 findReplace
函数的递归调用,您还需要指定所有参数:
findReplace :: String -> Char -> Char -> String
findReplace [] _ _ = []
findReplace (h:t) x y
|h == x = y : findReplace t x y
|otherwise = h : findReplace t x y
避免重复在递归调用中不变的参数的常见模式是使用本地辅助函数,该函数通常命名为 go
。然后参数 x 和 y 由 findReplace
函数绑定,并且可以在 go
函数内部使用。
findReplace :: String -> Char -> Char -> String
findReplace s x y = go s
where
go [] = []
go (h : t)
| h == x = y : go t
| otherwise = h : go t