getNames 'A' [('A', "Smith"), ('J', "Brown")] -> ["A.Smith", "A.Taylor"]
I try to add just char to every string element in list. My code is:
addForEvery :: Char -> [String] -> [String]
addForEvery a (x:xs) = [a] x : addForEvery a xs
print(addForEvery 'a' ["fa"])
But I get the following error:
jdoodle.hs:6:32: error:
• Couldn't match type ‘[Char]’ with ‘Char’
Expected type: [Char]
Actual type: [String]
• In the second argument of ‘( )’, namely ‘x : addForEvery a xs’
In the expression: [a] x : addForEvery a xs
In the expression: [[a] x : addForEvery a xs]
|
6 | addForEvery a (x:xs) = [[a] x : addForEvery a xs]
| ^^^^^^^^^^^^^^^^^^^^
CodePudding user response:
Did it!
getNames :: Char -> [(Char, String)] -> [String]
getNames a [] = []
getNames a ((z, b):xs) = ([a] ['.'] b) : getNames a xs
CodePudding user response:
The problem is that [a] x : addForEvery a xs
is interpreted as [a] (x : addForEvery a xs)
. This makes not much sense since [a]
is a String
, it expects x : addForEvery a xs
, but that is a list of String
s.
You can use map :: (a -> b) -> [a] -> [b]
to apply the same function to all items in the list. We thus can implement this as:
getNames :: [(Char, String)] -> [String]
getNames = map toFullName
where toFullName fn ln = fn : '.' : ln