musings of a Software Developer

Seven languages in seven weeks : My solutions for clojure day 2


Day 2 in clojure is about macro’s, sequences, protocols and records.

The first exercise deals with macro’s, the assignment is to extend the unless example from the book with an else body.
It is a fairly straight forward exercise, and there is not much to say about my implementation.

The second exercise is about the protocols and records in clojure.
The definition of a protocol on the website of clojure is : “A protocol is a named set of named methods and their signatures”.
For java programmers it can best be compared with interfaces.

For this exercise I will implement a simple cipher protocol, once with a ceasarcipher and once with a simple keybased substitution cipher.
uml diagram

So I started with a simple protocol definition:

For the implementation of the ciphers I needed a couple of functions, and because you can only define functions on a record that are also defined on the protocols it implements I just defined them in the script

It basically defines the alphabet, creates an infinite sequence of the alphabet, and allows to search for the index of a letter in a key, or the alphabet.
I really love the concept of infinite sequences, and it saves us some code that you would normally write around the shift in the caesar cipher. (if ((23+ shift > 26) { (26-23) + shift}).

Here is my caesar cipher:

And here is the substitution cipher:

Ok this was all for today

Leave a Reply

Required fields are marked *.