简体   繁体   中英

Replacing characters with numbers in Haskell

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 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM