Ege Gülce
Ege Gülce

Reputation: 15

Haskell function to uppercase the first letter and lowercase the rest of the letters in a word

I have been trying to write a function that capitalizes the first letter and uncapitalized the rest in Haskell. For example, capitalized "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?

Upvotes: 1

Views: 171

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

A String is a list of Chars, 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 Character of the string, and xs with the remaining characters. I leave the parts as an exercise.

Upvotes: 3

Related Questions