我的递归 haskell 代码有什么问题?

What is the problem with my recurvise haskell code?

Implement the password :: [Char] -> [Char] function, which is a string replaces all characters with *.

测试:

密码“akacfa2”==“*******”

密码“hunter1234”==“**********”

密码['a'] == ['*']

密码[]==[]

password :: [Char] -> [Char]
password [] = []
password (x: xs) = ["*" + password xs]

它不适用于 + 号。可以用什么代替?

password :: [Char] -> [Char]
password [] = []
password (x:xs) = "*" ++ password xs

根据您提供的代码,我猜这是您的意图。 String 属于 [Char] 类型,这只是它的同义词。您不需要将它们放在额外​​的 [] 中,因为它们已经是 []Char 了。此外,Strings 的串联运算符是 ++.

附带说明一下,这不是解决此问题的正确方法,即使您需要使用显式递归并且不使用任何辅助函数来完成也是如此。

您可以利用 String 是字符列表这一事实,只需将 * 字符添加到您在输入密码中遇到的每个字符的列表中。类似于以下内容:

password :: [Char] -> [Char]
password [] = []
password (x:xs) = '*' : password xs

显式递归,如

password [] = []
password (x:xs) = '*' : password xs

这里不需要。您可以使用 map 将每个字符替换为 '*'.

password xs = map (\x -> '*') xs

由于列表是仿函数,您可以使用 fmap 代替:

password xs = fmap (\x -> '*') xs

map 只是 fmap 专用于列表。)

Functor 类型 class 为这种用相同值替换每个元素的特殊情况提供了一种额外的方法:

password xs = '*' <$ xs