Vigenère cipher: Difference between revisions

(Updated D code)
Line 1,887:
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|TXR}}==
 
{{trans|Perl 6}}
 
Well, not exactly a translation but similar. The mapcar function vectorizes the operation over the characters, like Perl 6 hyper-operators. The repetition of the vigenere key is performed by a lazy list created by vig-pad. Perl 6 hyper-operators have this repetition behavior built-in, evidently.
 
<lang txr>@(next :args)
@(do
(defun str-to-list (str)
(for ((i 0) l) ((< i (length str)) (nreverse l)) ((inc i))
(push (chr-str str i) l)))
(defun vig-pad (key)
(let ((i 0) (m (length key)))
(make-lazy-cons (lambda (lcons)
(rplaca lcons (chr-str key i))
(rplacd lcons (make-lazy-cons (lcons-fun lcons)))
(set i (mod (+ i 1) m))))))
(defun chrmod (func)
(lambda (a b) (+ #\A (mod (call func (- a #\A) (- b #\A)) 26))))
(defun vig (msg key encrypt)
(let ((op (if encrypt (fun +) (fun -))))
(cat-str (mapcar (chrmod op) (str-to-list msg) (vig-pad key)) ""))))
@(coll)@{key /[A-Za-z]/}@(end)
@(coll)@{msg /[A-Za-z]/}@(end)
@(cat key "")
@(filter :upcase key)
@(cat msg "")
@(filter :upcase msg)
@(bind encoded @(vig msg key t))
@(bind decoded @(vig msg key nil))
@(bind check @(vig decoded key nil))
@(output)
text: @msg
key: @key
enc: @encoded
dec: @decoded
check: @check
@(end)</lang>
 
<pre>$ ./txr -l vigenere.txr 'vigenere cipher' 'Beware the Jabberwock... The jaws that... the claws that catch!'
text: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH
key: VIGENERECIPHER
enc: WMCEEIKLGRPIFVMEUGXXYILILZXYVBZLRGCEYAIOEKXIZGU
dec: GWQWEACDCBLUXNWOIYXPQAHSHLPQFLNDRYUWUKEAWCHSNYU
check: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH</pre>
 
{{omit from|GUISS|An application would be needed to be installed that could do this}}
Anonymous user