我想写一个函数,它接受一个字符串并用7替换字符串中的任意数字。例如,“foo123”将替换为“foo777”Haskell中这个替换函数的错误在哪里?
这是我的功能。
replace [] = []
replace (x:xs) =
if x == ['0'..'9']
then '7' : replace xs
else x : replace xs
我想写一个函数,它接受一个字符串并用7替换字符串中的任意数字。例如,“foo123”将替换为“foo777”Haskell中这个替换函数的错误在哪里?
这是我的功能。
replace [] = []
replace (x:xs) =
if x == ['0'..'9']
then '7' : replace xs
else x : replace xs
==
只测试x是否等于列表,它不是。您必须使用函数elem
,该函数将其中的一个元素和一个元素列表作为参数,如果该元素在列表中,则返回true
。所以,你的代码将是:
replace [] = []
replace (x:xs) =
if elem x ['0'..'9']
then '7' : replace xs
else x : replace xs
==
不测试,如果x
是列表中的一个元素;它检查x
是否为等于到列表中。改用elem
函数。
replace [] = []
replace (x:xs) =
if x `elem` ['0'..'9']
then '7' : replace xs
else x : replace xs
if
是一个纯粹的表达式,可以在任何地方使用,可以使用另一种表达方式,所以你不需要递归调用重复到xs
:
replace [] = []
replace (x:xs) = (if x `elem` ['0'..'9'] then '7' else x) : replace xs
最后,你可以只使用map
而不是使用显式递归。
replace xs = map (\x -> if x `elem` ['0'..'9'] then '7' else x) xs
或只是
replace = map (\x -> if x `elem` ['0'..'9'] then '7' else x)
您可能需要使用Data.Char.isDigit
代替:
import Data.Char
replace = map (\x -> if isDigit x then '7' else x)
你有什么用呢? –
这甚至不应该编译,你试图将x与列表进行比较,所以Haskell会假设你想匹配列表。 [可能的副本](http://stackoverflow.com/questions/14880299/how-can-i-replace-a-substring-of-a-string-with-another-in-haskell-without-using) – mfeineis