DEV Community

Discussion on: Daily Challenge #47 - Alphabets

Collapse
 
avalander profile image
Avalander

Haskell

Some function composition sorcery in Haskell.

import Data.Char (isLetter, toUpper, ord)

alphabet_position :: String -> String
alphabet_position = unwords . map (show . (flip (-)) 64 . ord . toUpper) . filter isLetter

Explanation

The . operator composes functions, so they will be applied from right to left.

  1. filter isLetter will remove all characters that are not letters from the string.
  2. map (show . (flip (-)) 64 . ord . toUpper) Transforms each character to its position in the alphabet.
    1. toUpper transforms the character to uppercase, so that we can substract 64 from it's code to know the position.
    2. ord maps a character to its ASCII code.
    3. (flip (-) 64) subtracts 64 from the character code. Since the code for 'A' is 65, this will give us the position in the alphabet starting at index 1. The way it works is it partially applies the second argument of the subtract operator to 64, i.e., this is equivalent to (\x -> x - 64) but fancier.
    4. show maps any type deriving from Show (Int in this case) to String.
  3. unwords joins a list of strings using space as a separator.