Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>“Caesar simply replaced each letter in the message by the letter three places further down the alphabet, wrapping around at the end of the alphabet.” We can simply write it in Haskell. In fact we can avoid <code>let2num</code> and <code>num2let</code> altogether.</p> <p>So let's start with defining a table to map plain text alphabet to the cipher text alphabet:</p> <pre><code>cipher = let abc = ['a'..'z'] code = drop 3 abc ++ take 3 abc in zip abc code </code></pre> <p>It will look like</p> <pre><code>[('a','d'),('b','e'),('c','f'),('d','g'), ... ] </code></pre> <p>Now we can encrypt a symbol, if we simply <code>lookup</code> the letter in this dictionary:</p> <pre><code>ghci&gt; lookup 'a' cipher Just 'd' </code></pre> <p><code>lookup</code> returns a <code>Maybe Char</code> value, we need to convert it to simply a <code>Char</code>, and for this I use <code>maybe</code> function, using <code>'?'</code> for symbols which were not found in the cipher, and <code>id</code> (identity function = no changes) to found symbols:</p> <pre><code>ghci&gt; maybe '?' id (lookup 'a' cipher) 'd' </code></pre> <p>Now we can write an <code>encrypt</code> function to encode just one symbol, it will leave missing characters, like a space, unencrypted:</p> <pre><code>encrypt c = maybe c id (lookup c cipher) </code></pre> <p>To encrypt an entire string:</p> <pre><code>ghci&gt; map encrypt "haskell is fun" "kdvnhoo lv ixq" </code></pre> <p>So we can put it all together:</p> <pre><code>encrypt c = maybe c id (lookup c cipher) where cipher = let abc = ['a'..'z'] code = drop 3 abc ++ take 3 abc in zip abc code </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload