我有下面的代码很好用
replacePointsWithZeros :: Eq a => a -> a -> [a] -> [a]
replacePointsWithZeros _ _ [] = []
replacePointsWithZeros replacee replacer (x:xs)
| replacee == x = replacer:replacePointsWithZeros replacee replacer xs
| otherwise = x:replacePointsWithZeros replacee replacer xs
但是我想用默认值替换replacee和replacer参数,所以本质上我想要的是
replacePointsWithZeros :: Eq a => [a] -> [a]
replacePointsWithZeros [] = []
replacePointsWithZeros (x:xs)
| '.' == x = '0':replacePointsWithZeros xs
| otherwise = x:replacePointsWithZeros xs
但是,当我尝试使用某种消息来抱怨类型时,我并不十分了解,因为我对Haskell非常陌生。我在做什么错,我该如何解决?
我假设问题出在行
replacePointsWithZeros :: Eq a => [a] -> [a]
以及我使用a代替Char但我将a切换为Char的事实,Eq语句出现问题
答案 0 :(得分:4)
自从您编写'.' == x
以来,这意味着x
是Char
,因此(x:xs)
是Char
的列表,因此{{ 1}}或[Char]
。
此外,您将String
和'0':
写为输出,因此这意味着输出也包含x:
的列表。因此,这意味着Char
的签名是:
replacePointsWithZeros
通过将条件放在映射函数中,可以使以上内容变得更懒:
replacePointsWithZeros :: String -> String
replacePointsWithZeros [] = []
replacePointsWithZeros (x:xs)
| '.' == x = '0':replacePointsWithZeros xs
| otherwise = x:replacePointsWithZeros xs
,我们可以使用replacePointsWithZeros :: String -> String
replacePointsWithZeros [] = []
replacePointsWithZeros (x:xs) = f x : replacePointsWithZeros xs
where f '.' = '0'
f x = x
函数代替显式递归:
map