I have been trying to write a function that capilitizes the first letter and uncapitlizes the rest in haskell. For example, capitalised "mELboURNe" == "Melbourne" but I am getting errors. I have to use list comprehension.
I have tried this,
capitilized :: String -> String
capitilized = map(\x -> if length x == 1 then capitilized3 x else capitilized2 x)
capitilized2 :: Char -> Char
capitilized2 x= Char.toLower x
capitilized3 :: Char -> Char
capitilized3 x= Char.toUpper x
But I am getting this error:
• Couldn't match expected type ‘t0 a0’ with actual type ‘Char’
• In the first argument of ‘length’, namely ‘x’
In the first argument of ‘(==)’, namely ‘length x’
In the expression: length x == 1
|
21 | capitilized = map(\x -> if length x == 1 then capitilized3 x else capitilized2 x)
Can anyone help?
CodePudding user response:
A String
is a list of Char
s, but a Char
is not a list so length x
makes no sense.
You can work with pattern matching with:
capitilized :: String -> String
capitilized [] = …
capitilized (x:xs) = …
Here especially the second pattern is important since x
will bind with the first Char
acter of the string, and xs
with the remaining characters. I leave the …
parts as an exercise.