Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting lowercase letters to capitals

Tags:

haskell

I am a newbie in Haskell and have some problem of defining a function that would convert all small letters to capital and leave the rest intact.

I tried solving this question in my book so far:

capitalise :: String -> String
capitalise xs = [capitalise2 ch| ch<-xs]

capitalise2 :: Char -> Char
capitalise2 ch 
    | isLower ch    = chr (ord ch - 32)
    | otherwise    = ch

I am getting errors:

p3.hs:6:7: Not in scope: `isLower'
p3.hs:6:23: Not in scope: `chr'
p3.hs:6:28: Not in scope: `ord'

Any help would be much appreciated.

like image 242
Amjad Avatar asked Nov 27 '22 11:11

Amjad


1 Answers

First, you need to import Data.Char to use those functions it is complaining about.

Right, you are missing the otherwise case in the new function. Try it with an if .. then .. else construct. Experienced Haskellers do not use that construct very much; I would probably do it with a helper function:

capitalize cs = [ toUpper c | c <- cs ]
    where
    toUpper ...

which is pretty much the same as what you already have, the main difference being the scope of the helper function.

See also Data.Char.toUpper.

This may also be a good opportunity to break free of list comprehensions and start to play with higher order functions. Try writing this function with map instead of a list comprehension.

like image 185
luqui Avatar answered Dec 10 '22 13:12

luqui