Rot13 (Haskell)
From LiteratePrograms
Rot13 is a simplistic cryptographic function (note this has absolutely no real encryption value and should not be used to protect data) which takes a string and moves all alpha characters 13 over. For instance, A becomes N, B becomes O, P becomes C (past Z the character loops back to A) and Z becomes M. This specific function deals with both upper and lower case letters, and also maps numbers. The numbers move by 5 places, rather than 13, so 0 becomes 5, 2 becomes 7, and the like. If passed a non alpha-numeric character, it will be returned unchanged.
For more information on Rot13, visit the Wikipedia Article.
<<rot13.hs>>= module Rot13 where import qualified Data.Map as M lSet = ['a'..'m'] ++ ['A'..'M'] ++ ['0'..'4'] rSet = ['n'..'z'] ++ ['N'..'Z'] ++ ['5'..'9'] charMap = M.fromList $ zip lSet rSet ++ zip rSet lSet findInMap charMap myChar = M.findWithDefault myChar myChar charMap rot13 string = map (findInMap charMap) string
First we generate a Map from a list of tuples, where each character is mapped to its encrypted character. So the beginning of the list is: [('a','n'),('b','o'),('c','p'),('d','q'),('e','r')...] From there, the findInMap function will find a char in the charMap list and return the encrypted character. If the character is not found in the list, it is returned. Then that function is mapped to a string using rot13, since strings in Haskell are simply list of chars.
References
Digital Gemstones
Download code |