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!
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
This should be the most concise and correct(and fast) answer to my question. I have to appreciate your help a lot. However, I forgot to mention some keywords in my question. The funct should be written recursively. Is there a solution to do just that? TXX!
So it's a homework? I'd really rather try to solve it on my own if I were you. Besides, it's really as trivial as it gets. Anyway, see the updates.
Yep, in fact I have just solved it myself. I still accept your answer for your continued help. But I think you should take a look at this solution as well for it processes the string backwards instead
capitalised :: String->String capitalised (x:[]) = [toUpper x] capitalised x = capitalised $ init x ++ [toLower $ last x] capitalised x = capitalised $ init x ++ [toLower $ last x]
@oasisweng You'll get an awful performance with your proposed implementation, because both the
last
and theinit
operations require traversal of the whole list, in other words, they both have a time complexity ofO(n)
. Also you call those functions on each step of iteration, so summarily you get a time complexity ofO(n * (n + n))
for your function. A cons operation (:
) on the other hand has complexity ofO(1)
, so both my solutions have a resulting complexity of justO(n)
.Very well explained, tx!