First attempt at Haskell: Converting lower case letters to upper case
functional-programming, haskell
Solution
Firstly, if/else is generally seen as a crutch in functional programming languages, precisely because they aren't really supposed to be used as branch operations, but as functions. Also remember that lists don't know their own lengths in Haskell, and so calculating it is an `O(n)` step. This is particularly bad for infinite lists.
I would write it more like this (if I didn't import any libraries):
uppercase :: String -> String
uppercase = map (\c -> if c >= 'a' && c <= 'z' then toEnum (fromEnum c - 32) else c)
Let me explain. This code makes use of the `Enum` and `Ord` typeclasses that `Char` satisfies. `fromEnum c` translates `c` to its ASCII code and `toEnum` takes ASCII codes to their equivalent characters. The function I supply to `map` simply checks that the character is lowercase and subtracts 32 (the difference between 'A' and 'a') if it is, and leaves it alone otherwise.
Of course, you could always just write:
import Data.Char
uppercase :: String -> String
uppercase = map toUpper
Hope this helps!
Problem
I have recently started learning Haskell, and I've tried creating a function in order to convert a lower case word to an upper case word, it works, but I don't know how good it is and I have some questions. Code: ``` lowerToUpperImpl element list litereMari litereMici = do if not (null list) then if (head list) == element then ['A'..'Z'] !! (length ['A'..'Z'] - length (tail list ) -1) else lowerToUpperImpl element (tail list) litereMari litereMici else '0' --never to be reached lowerToUpper element = lowerToUpperImpl element ['a'..'z'] ['A'..'Z'] ['a'..'z'] lowerToUpperWordImpl word = do if not (null word) then lowerToUpper (head (word)):(lowerToUpperWordImpl (tail word)) else "" ``` - I don't like the way I have passed the upper case and lower case letters , couldn't I just declare a global variables or something? - What would your approach be in filling the dead else branch? What would your suggestions on improving this be?