I have started to do the questions on Project Euler regarding lists of names which need to be replaced with their corresponding position in the alphabet. In Problem 22 I need to replace, the letters with numbers:
names = ["MARY","PATRICIA","LINDA"....
replace = ??????
char2num a = map replace a
score (a,b) = a * (sum $ map char2num b)
answer = sum $ map score (zip [1..] (sort names))
What I cannot find is how to replace the characters with their place in the alphabet. How would I go about making something to do the replace function (preferably not regex)?
The
ordfunction in theData.Charmodule gives an integer code for each character. Given that, this would be the function you’re looking for:I’m not sure if
ord cwill return the ASCII code for a character, or the unicode codepoint, or if the result is machine dependent. To abstract from that, we simply subtract the code for'A'from the result, and add1because we want the alphabet to start at1instead of0.An easy way to find to find such a function is Hoogle.
There you can search for functions in the standard Haskell packages by entering its type. In this case
ordis the second result when searching forChar -> Int.