Substitution Cipher in Haskell Learn You a Haskell presents the Caesar Cipher:


  The Caesar cipher is a primitive method of encoding messages by
  shifting each character in them by a fixed number of positions in the
  alphabet


EDIT

Since I'm not limiting this cipher to letters, it's not actually the Caesarian Cipher.
Thanks to Anonymous. This implementation is only a Substitution Cipher.

Here's my implementation:

import Data.Char (ord, chr)

encode :: Int -&gt; String -&gt; String
encode n = map $ shift' n
                 where shift' x =  chr . (+ x) . ord

decode :: Int -&gt; String -&gt; String
decode n = map $ shift' n
                 where shift' x =  chr . abs . ((-) x) . ord


Test:

*Main Data.Char&gt; encode 1 "AAA"
"BBB"
*Main Data.Char&gt;
*Main Data.Char&gt; decode 1 "BBB"
"AAA"


I don't like that I'm using abs in my decode. How can I write a function (through currying) that will subtract X from it?

Also, please critique my implementation.
This is a legitimate substitution cipher, but it's not a Caesarean cipher. A Caesarian cipher affects only letters, and it's modulo the alphabet size: caesar 13 "Hello, world!" ⇒ "Urzzb, jbeyq!"

encode and decode can be the same function (caesar?) called with opposite shifts. (Or with the same shift, when it's 13.)

There's no need for a shift' helper.


  How can I write a function (through currying) that will subtract X from it?


(x -)