Created
November 7, 2009 18:55
-
-
Save Raynes/228842 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns cipher | |
(:use [clojure.contrib.def :only (defnk)])) | |
(def alphabet-nums (apply hash-map (interleave (range 1 27) "abcdefghijklmnopqrstuvwxyz"))) | |
(def alphabet-chars (apply hash-map (interleave "abcdefghijklmnopqrstuvwxyz" (range 1 27)))) | |
(defn is-letter? [s] | |
(if (re-find #"(?i)[a-z]" (.toString s)) true false)) | |
(defnk shift-char | |
"Shifts the given Character down the alphabet by three. | |
Has optional arg :d which takes :fw or :bw, so it can | |
be used for deciphering as well as ciphering. If it | |
isn't provided, will default to :fw for ciphering." | |
[char :d :fw] | |
(let [num (if (= d :fw) (+ char 3) (- char 3)) | |
pred (if (= d :fw) (> num 25) (< num 2)) | |
truec (if (= d :fw) (- num 26) (+ num 26)) | |
index | |
(if (and pred (not= num (if (= d :fw) 26 1))) truec num)] | |
(alphabet-nums index))) | |
(defn trans-string | |
"Transforms a string into a vector of numbers | |
that correspond with their characters." | |
[s] | |
(for [x s] (alphabet-chars x))) | |
(defnk cipher | |
"Encrypts a string with Caesar's cipher." | |
[s :d :to] | |
(apply str | |
(let [args | |
(if (= d :from) :bw :fw)] | |
(for [x (trans-string (.toLowerCase (apply str (filter is-letter? s))))] | |
(shift-char x :d args))))) | |
(defn to-cleartext | |
"Transforms ciphertext into cleartext." | |
[s]) | |
(comment | |
cipher> (cipher "abd") | |
"deg" | |
cipher> (cipher "abd" :from) | |
; Evaluation aborted. | |
cipher> (cipher "abd" :direction :from) | |
"xya" | |
cipher> (cipher "abd" :direction :to) | |
"deg" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment