Warm tip: This article is reproduced from serverfault.com, please click

How to capitalize the first letter of a string and lowercase the rest in Haskell

发布于 2013-11-20 10:27:03

I have to write a function which uppercase the FIRST letter of a string and also LOWERCASE the rest of the string (This string contains random uppercased or lowercased letters).

So far, I have managed to do this:

capitalised :: String->String
capitalised [] = []
capitalised x
            | length x == 1 = map toUpper x
            | otherwise = capitalised (init x): map toLower (last x)

and all other sort of weird functions, and I still could not figure it out.

Please help! Tx in advance!

Forgot to mention, the problem states that I need to write a recursive solution!

Questioner
donkey
Viewed
0
Nikita Volkov 2013-11-21 06:54:13

Remember that a String is just a type synonym for [Char]? Here we utilize that:

import qualified Data.Char as Char

capitalized :: String -> String
capitalized (head:tail) = Char.toUpper head : map Char.toLower tail
capitalized [] = []

Here is a recursive version:

capitalized :: String -> String
capitalized [] = []
capitalized (head:tail) = Char.toUpper head : lowered tail
  where
    lowered [] = []
    lowered (head:tail) = Char.toLower head : lowered tail