Sunday, 5 June 2016

Haskell: Convert every character of string to uppercase


StringUtil.hs
import Data.Char (toUpper)

stringToUpper :: [Char] -> [Char]
stringToUpper [] = []
stringToUpper (x:xs) = (toUpper x) : (stringToUpper xs)

*Main> :load StringUtil.hs
[1 of 1] Compiling Main             ( StringUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> stringToUpper "abcdEFGH"
"ABCDEFGH"
*Main> stringToUpper "abcdEFGHijkm"
"ABCDEFGHIJKM"
*Main> 


We can rewrite the above functionality using map function like below. ‘map’ function takes a function and list as inputs and applies the function to every element of the list.
*Main> :m Data.Char
Prelude Data.Char> 
Prelude Data.Char> let stringToUpper xs = map toUpper xs
Prelude Data.Char> 
Prelude Data.Char> stringToUpper "abcdEFGH"
"ABCDEFGH"
Prelude Data.Char> stringToUpper "abcdEFGHijkm"
"ABCDEFGHIJKM"
Prelude Data.Char> 



Previous                                                 Next                                                 Home

No comments:

Post a Comment