I have a list of strings ["Hi", "hELLO", "nO"]
and I want to convert everything to lowercase. I wrote a function for this:
import Data.Char(toLower)
makeSmall xs = map toLower xs
It compiles, but when I do makeSmall ["Hi", "hELLO", "nO"]
it gives me this error
<interactive>:2:12: error:
• Couldn't match expected type ‘Char’ with actual type ‘[Char]’
• In the expression: "Hi"
In the first argument of ‘makeSmall’, namely
‘["Hi", "hELLO", "nO"]’
In the expression: makeSmall ["Hi", "hELLO", "nO"]
<interactive>:2:17: error:
• Couldn't match expected type ‘Char’ with actual type ‘[Char]’
• In the expression: "hELLO"
In the first argument of ‘makeSmall’, namely
‘["Hi", "hELLO", "nO"]’
In the expression: makeSmall ["Hi", "hELLO", "nO"]
<interactive>:2:25: error:
• Couldn't match expected type ‘Char’ with actual type ‘[Char]’
• In the expression: "nO"
In the first argument of ‘makeSmall’, namely
‘["Hi", "hELLO", "nO"]’
In the expression: makeSmall ["Hi", "hELLO", "nO"]
I'm trying to understand how I can make my function work for a list of strings, instead of just a string
CodePudding user response:
toLower :: Char -> Char
maps a Char
to a Char
, this means that map toLower
will take a single String
, and it will return a String
.
If you want to handle a list of String
s, you should use a second map
:
makeSmall :: [String] -> [String]
makeSmall xs = map (map toLower) xs
or shorter:
makeSmall :: [String] -> [String]
makeSmall = map (map toLower)
We thus make a mapper that uses map toLower
as map function. This function will thus work on a single String
. Since we make thus a mapper for this, we work on a list of String
s.