In other words: -.– .- -.– / ..-. / … …. .- .-. .–.
As I was explaining Morse Code to a young mind, I started thinking. It is fine to explain the encoding and uses, but experiencing the audial component makes the lessons stick better. Enter F#. Yes, I know I could use any of a hundred phone apps or websites that produce sound, but what’s the fun in that? For me, this is the perfect opportunity to hack out a quick text to morse code translator.
Getting started, I setup a Map
as the codebook for letter/number to morse code translation. It’s not meant to be comprehensive, but enough to play with. Then I code in some constants and helpers to make my life easier later.
1 | open System |
This is the translation and audio portion. The approach is basically: string -> char -> code -> dot/dash -> sound. I do lookups in the codebook with TryFind
. This allows me to leverage Some
and None
. For illustrative purposes, the character is displayed as its going audio. Then the character’s code is fed into the morseToSound function. Here the code is broken apart and the dots (.) and dashes (-) are translated into audio sounds. Luckily I can just just use Console.Beep
for easy tone creation. I code spaces as a word seperator and visibilty display unknown characters and patterns with a ‘!’.
1 | // Convert the dot/dash to sound |
This is a test snippet to make sure it all works.
1 | let input = "Hello World" |
I want to allow this experience to be more interactive. It doesn’t have to be anything fancy so I just set up a loop that takes a line at a time and does translations. An empty line exits the program.
1 | let rec main() = |
This mini project is pretty basic. But it was a quick and fun way to whip up an experimentation tool, and use F# in the process.