Home > Software engineering >  What is the problem with my recurvise haskell code?
What is the problem with my recurvise haskell code?

Time:10-23

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

Test:

password "akacfa2" == "*******"

password "hunter1234" == "**********"

password ['a'] == ['*']

password [] == []

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

It is not working with the sign. What can be used instead?

CodePudding user response:

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

I guess that was your intent from the code you have provided. String is of type [Char] which is just a synonym for it. You don't need to put them in an additional [] because they are already a [] of Chars. In addition, the concatenation operator for Strings is .

On a side note, this is not the proper way to solve this problem, even if you are required to do it with explicit recursion and without using any helper functions.

You can make use of the fact that Strings are lists of characters and just add characters of * to the list for each character you encounter in the input password. Something like the following:

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

CodePudding user response:

Explicit recursion, like

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

isn't needed here. You can use map to replace each character with a '*'.

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

Since a list is a functor, you can use fmap instead:

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

(map is just fmap specialized to lists.)

The Functor type class provides an additional method for this special case of replacing each element with the same value:

password xs = '*' <$ xs
  • Related