The Kitchen Sink and Other Oddities

Atabey Kaygun

A Morse Code Translator

When I was a child, one of the things I was fascinated with was the Morse Code. At one time, during that 15 minutes I walked to school from home, I would transcribe random sentences to Morse Code in my head.

Today, I will write a two silly functions to encode and decode strings from and to Morse Code.

First, the conversion tables:

(defvar morse-code-table
  '((#\a . ".-")
    (#\b . "-...")
    (#\c . "-.-.")
    (#\d . "-..")
    (#\e . ".")
    (#\f . "..-.")
    (#\g . "--.")
    (#\h . "....")
    (#\i . "..")
    (#\j . ".---")
    (#\k . "-.-")
    (#\l . ".-..")
    (#\m . "--")
    (#\n . "-.")
    (#\o . "---")
    (#\p . ".--.")
    (#\q . "--.-")
    (#\r . ".-.")
    (#\s . "...")
    (#\t . "-")
    (#\u . "..-")
    (#\v . "...-")
    (#\w . ".--")
    (#\x . "-..-")
    (#\y . "-.--")
    (#\z . "--..")
    (#\0 . "-----")
    (#\1 . ".----")
    (#\4 . "....-")
    (#\5 . ".....")
    (#\6 . "-....")
    (#\7 . "--...")
    (#\8 . "---..")
    (#\9 . "----.")
    (#\. . ".-.-.-")
    (#\, . "--..--")
    (#\: . "---...")
    (#\? . "..--..")
    (#\' . ".----.")
    (#\! . "-.-.--")
    (#\- . "-....-")
    (#\/ . "-..-.")
    (#$ . "-.--.")
    (#$ . "-.--.-")
    (#\& . ".-...")
    (#\@ . ".--.-.")
    (#\= . "-...-")
    (#\" . ".-..-.")
    (#\Space . "|")))

MORSE-CODE-TABLE

(defvar reverse-morse-code-table 
    (mapcar (lambda (x) (cons (cdr x) (car x)))
            morse-code-table))

REVERSE-MORSE-CODE-TABLE

and the text to Morse conversion function:

(defun text-to-morse (word)
   (reduce (lambda (x y) (concatenate 'string x " " y))
           (mapcar (lambda (x) (or (cdr (assoc x morse-code-table))
                                   x))
                   (coerce (string-downcase word) 'list))))

TEXT-TO-MORSE

(text-to-morse "Here we go.")

.... . .-. . | .-- . | --. --- .-.-.-

and the Morse to text conversion function:

(defun morse-to-text (sequence)
   (coerce (mapcar (lambda (x) (cdr (assoc x reverse-morse-code-table :test 'equal)))
                   (ppcre:split " " sequence))
           'string))

MORSE-TO-TEXT

(morse-to-text (text-to-morse "Here we go again."))

here we go again.