Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (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"
- )
Add Comment
Please, Sign In to add comment