实现密码::[Char] ->[Char]函数,它是一个字符串,用*替换所有字符。
测试:
密码"akacfa2"= ="* * * * * * *">
密码"hunter1234"= =" ;**********& ">
password ['a'] == ['*']
password [] == []
password :: [Char] -> [Char]
password [] = []
password (x: xs) = ["*" + password xs]
不能使用+号。可以用什么代替呢?
password :: [Char] -> [Char]
password [] = []
password (x:xs) = "*" ++ password xs
我猜这是你的意图从你提供的代码。String
的类型是[Char]
,这只是它的同义词。你不需要把它们放在额外的[]
中,因为它们已经是Char
中的[]
了。另外,String
s的连接操作符为++
。
您可以利用String
s是字符列表的事实,只需将*
的字符添加到您在输入密码中遇到的每个字符的列表中。如下所示:
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
类型类为这种用相同值替换每个元素的特殊情况提供了一个额外的方法:
password xs = '*' <$ xs