Home > Software design >  How to assign numbers 1-26 to letters a-z and then sum the output of a string in Haskell?
How to assign numbers 1-26 to letters a-z and then sum the output of a string in Haskell?

Time:04-14

I'm tasked with writing a Haskell program that'll prompt the user to input a string, and then the program will assign a number to each letter(e.g. a = 1, d = 4, y = 25, z = 26) and then it will sum the total from the string. Example "Hi" would equal 8 9 or 17. I've got something to do the first part but only if its in all caps, but I still can't figure out how to get the output list summed.

import Data.Char

toOrder :: [Char] -> [Int]
toOrder str = map ((\x -> x - 64) . ord) str

Ideas?

CodePudding user response:

You can use toUpper to regularize the characters, and sum to sum the list of Ints:

import Data.Char (ord, toUpper)

main = print $ score "Hi" -- 17

score :: String -> Int
score = sum . map (subtract 64 . ord . toUpper)
  • Related