Wednesday, August 5, 2015

Kata: Print Diamond in Clojure

Yesterday we did the Print Diamond kata in the Clojure Developers Barcelona group.

I paired with Rafa Gómez. We managed to complete a recursive solution to the problem using our usual mix of TDD and REPL-driven development.

Later, we showed our solution and realize that, even though, it worked fine, we had to improve the names of some helper functions we had created to make our solution easier to understand.

After that, Samuel Lê, presented on the whiteboard (we couldn't connect his laptop to the projector) a completely different and very elegant approach.

I'll try to explain it:

Say, for instance, that you're trying to create the diamond for D.

You first create the following sequence repeating the string "DCBABCD" as many times as lines there are in the diamond:

Only one letter is allowed to appear in each line of the diamond.

Let's represent this in a table:

Now the only thing we have to do to get the correct diamond lines is to substitute by a space (we used an underscore to make it easier to visualize) every letter of the line that is different from the allowed letter for that line:

This is a very elegant approach that only uses sequences functions.

When I got back home I redid the kata again using both approaches: the recursive one and the one that Samuel had explained on the whiteboard.

These are the tests I used to test drive the recursive code (sorry I can't show the REPL history because I haven't found where Cursive saves it):

I'm using an underscore instead of a space to make the results easier to visualize.

This is the recursive code:

Then I deleted the recursive code and started playing in the REPL to build a new solution following Samuel's approach and using the previous tests as acceptance tests to know when I was done.

Once I had it working again:

I refactored the code a bit introducing some helpers to separate responsibilities and make the code more readable and renamed some bindings.

This is the resulting code:

You can find all the code in this GitHub repository.

As usual the Clojure meetup and the conversations having a drink afterwards have been both great fun and very interesting.

We also met Alejandro Gómez which is writing this great ClojureScript book and has recently moved to Barcelona.

No comments:

Post a Comment