views:

197

answers:

1

Hi, 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 question 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)?

+8  A: 

The ord function in the Data.Char module gives an integer code for each character. Given that, this would be the function you're looking for:

import Data.Char

replace :: Char -> Int
replace c = ord c - ord 'A' + 1

I'm not sure if ord c will 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 add 1 because we want the alphabet to start at 1 instead of 0.

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 ord is the second result when searching for Char -> Int.

Tom Lokhorst