Rot13 (Haskell)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Haskell | Java | Python | Scheme | Sed

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 charecters 13 over. For instance, A becomes N, B becomes O, P becomes C (past Z the charecter 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 Char

lSet = ['a'..'m'] ++ ['A'..'M'] ++ ['0'..'4']
rSet = ['n'..'z'] ++ ['N'..'Z'] ++ ['5'..'9']

charMap = (zip lSet rSet) ++ (zip rSet lSet)

findInList myList myChar = if myList == [] then myChar else
  (if (fst (head myList)) == myChar then (snd (head myList)) else (findInList (tail myList) myChar))

rot13 string = map (findInList charMap) string

First we generate 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 findInList function will find a char in the charMap list and return the encrypted charecter. If the charecter 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.

[edit] References

Digital Gemstones

Download code
hijacker
hijacker
hijacker
hijacker