Home > OS >  How to capitalize the start of a string and lowercase the other characters using pattern matching in
How to capitalize the start of a string and lowercase the other characters using pattern matching in

Time:10-04

I am trying to capitalize the first letter of a string to an uppercase letter and all the other letters to lowercase. This is my code so far:

capitalize :: String -> String

capitalize word = [ toUpper x | x <- word, head` word ]

I have tried a few variations of the guard behind, but they do not work. I want to use pattern matching to separate the string into the head and tail, but am unsure how to. Is there a way, using list comprehension, to do this?

Also, can we put multiple guards in one place? Because I am under the impression that isAlpha should be one of the guards. I would be very grateful for any assistance.

CodePudding user response:

I don't think a list comprehension is a great tool for this particular function. You can do all sorts of mapping and filtering with that, but there's no easy way to treat the first element of the list differently from the others.

Personally, I think the cleanest way to write this function is with simply pattern matching:

capitalize :: String -> String
capitalize "" = ""
capitalize (x:xs) = toUpper x : map toLower xs

The capitalize "" = "" line isn't strictly necessary if you're sure you'll never try to use this on an empty string, but I prefer writing functions that can never give a runtime error, and it seems fair to say that capitalizing an empty string should give another empty string back.

The main work is done on the last line, which uses the x:xs pattern to separate the list (strings are just lists in Haskell) into the x the head (or first letter), and xs the rest of the string. Then we use toUpper to make the first letter uppercase, and map toLower to make the rest lowercase (toLower and toUpper work on characters, not strings, but a string is a list of characters so we use map to apply the function to each character in the string), and put them back together with the cons operator :.

  • Related