Thursday, July 24, 2014

Exercism: "Meetup in Clojure"

This is my solution to the Meetup problem in Clojure.

This is the first version:


To make it more interesting I decided to implement the date logic myself instead of using a Date library.

What I really didn't like about this version was that I had to generate one by one a lot of functions.

I commented in my solution that I wasn't happy with the result and that I would love to find out a way to dynamically generate all the functions that the tests were using.

Yesterday I received a nitpick from moog just saying:
"intern is your friend"
So I started to google a way to use intern to solve my problem. After a while I found this post: Metaprogramming with Clojure explaining how to use intern to dynamically generate bindings in a given namespace.

I had to do several trials in the REPL and remember to force the evaluation of a sequence with doall before getting it to work using map and a list comprehension.

This is the new version in which I managed to remove the clutter by dynamically generating all the functions that the tests use (look at the two calls to doall nearly at the end of the code). It is around 30 lines shorter:



I'm glad because I've learned about a lot of new Clojure functions, symbol, resolve, name, intern and doall, and also used a list comprehension with for.

I'd like to thank moog for giving me a passage into a new Clojure territory.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Wednesday, July 23, 2014

A bit about JavaScript functions

Yesterday, I gave a talk about JavaScript functions in Vilanova i la Geltrú.

These are the talk slides.

The talk focused in introducing the following concepts:
  • Functions as first class entities
  • Closures
  • Higher-order functions

It was based on the readings I've done lately to learn JavaScript:

Here is the code of the examples used in the talk. Most of them were taken from Reginald Braithwaite's wonderful book. I also used an example from this other post of this blog: Strategy pattern and higher-order functions?.

I'm a shy person and it's difficult for me to talk in public but in the end I enjoyed the experience. I feel that trying to share what I've learned has improved my understanding of the topic.

I hope that the talk has somehow awaken a bit of interest for functional techniques in JavaScript among the attendants.

I'd like to thank you José Carlos for talking me into giving this talk to share what I have been learning lately about JavaScript functions and functional programming.

I'd also like to thank Edgar Costilla for letting us use Espai Feedback great facilities.

Finally, I'd like to thank the attendants for their interest and questions.

Thursday, July 17, 2014

Kata: Rotate an array in place in JavaScript

Álvaro García and I were pairing yesterday after work.

We practised coding the Rotate an array in place kata in Python.

It was great fun and we discussed about naming, scaffolding tests, closures, free variables and deleting tests.

Once back at home, I redid the kata in JavaScript. You can see the resulting code in GitHub. I commited every time I got to green and after every refactoring so you can follow the process.

In this post I just want to highlight what Álvaro and I did to optimize the code a bit.

These are the tests we kept after having a first working version of the code:


and this is the corresponding code:


This code worked also for steps greater or equal that the array size, only that in that particular case it would do more work than necessary. To avoid that extra work you just need to realize that a rotation by k steps yields the same result as a rotation by n * k steps, where n is a positive integer.

Since we were practising our TDD skills, we wanted to write first a failing test that forced us to write that optimization. Not that TDD should be used for that. It was only a way to set ourselves a tiny challenge for us to practise.

We realized that we could use an assertion on the number of calls to the swap helper to force the desired change, but first we had to make the function swap accessible from the outside:


in order to spy on it:


The last test was now failing, as we intended, for making to many calls to swap.

It took just a small change to the code to make the test pass:


This way we could assert that a rotation by k steps yielded the same result as a rotation by n * k steps, where n is a positive integer.

Once we had that optimization in place, we made swap private again:


for which we had to stop spying on it from the tests:


Next we examined the tests to see which ones were overlapped and could be removed. They had been useful as scaffolding to build the functionality, but once there they weren't adding much value. In our opinion keeping these scaffolding tests or not, is something that needs to be ponder in a case by case basis.

After removing those tests, I renamed the remaining tests and played a bit with augmenting the Array object prototype to finally get to the following tests:


I think that although this kata is very simple, you can make a lot from it and have fun.

Thanks Álvaro for the great pairing experience, I hope we'll go on having fun with other katas.

Thursday, July 10, 2014

Exercism: "Grains in Clojure"

This is my solution to the Grains problem in Clojure.


This solution is probably not idiomatic at all. I just wanted to use a stream like in my previous Racket solution to see how different would that be in Clojure.

This was the Racket version:


As you see they are quite different.

letfn is somehow equivalent to Racket's letrec.

My biggest problem was with cons because they behave different.

Whereas in Racket you can do:
> (cons 1 2)
'(1 . 2)
in Clojure an exception is raised when you try the same:
user=> (cons 1 2)
IllegalArgumentException 
Don't know how to create ISeq from: 
java.lang.Long  clojure.lang.RT.seqFrom (RT.java:505)
You need to write this instead:
user=> (cons 1 (cons 2 nil))
(1 2)
So in the end I used seq:
user=> (seq [1 2])
(1 2)

Another difference is that you have an integer overflow in Clojure unless you use BigInt, whereas in Racket number can be arbitrarily large.

Well, now that I've tried this. I'll try writing a more idiomatic version.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Grains problem in Racket using a home-made stream

I did the Grains problem in Racket using a home-made stream:


The stream is the function grains which returns a pair containing the first value and the generator of the rest of the stream.

The stream-for-n-steps helper gets n values from the stream.

Probably there is a function to do this directly in Racket but I wanted to remember what we did in the Coursera Programming Languages course.

Now I want to do something similar in Clojure.

Tuesday, July 8, 2014

Exercism: "Space Age in Clojure"

This is my solution to the Space Age problem in Clojure.

In the first working iteration I made all "on-planet" functions use the on-earth function.
I also used let forms to avoid magic numbers.
It has a lot of duplication:


In the next iteration I played with comp and partial to write the make-on-planet-function factory that can create "on-planet" functions as compositions of the on-earth function:


Finally for the last version, I wrote a somehow more readable version of make-on-planet-function:


You can nitpick my solution here or see all the exercises I've done so far in this repository.

Saturday, July 5, 2014

Exercism: "Extract-Transform-Load in Clojure"

This is my solution to the Extract-Transform-Load problem in Clojure.

I wrote several working versions in the REPL but this is the one that I finally submitted to Exercism as my first iteration:


I used destructuring to extract the letters and score from the key-value pair which reduce was passing to the anonymous helper.

It works but it's not very readable.

In the second iteration I introduced a helper function, assoc-pairs, to improve its readability but the naming was still bad:


So I renamed some parameters and helper functions for the third iteration:


I find that, even though, using the let form to create the local bindings that gave names to the internal helper functions, associate-score-to-letters and associate-score-to-letter helps to reveal the intention of each helper function, it also creates a "parentheses vortex" that can obscure the code at the same time.

I wish Clojure would let me define these local functions just nesting the function definitions inside the enclosing function, like the functions sqrt_iter, good_enough? and improve defined inside custom_sqrt in this Scheme example (I coded it using DrRacket):


I think that a feature like that would help to make my Clojure solution easier to read.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Exercism: "Leap year in Clojure"

This is my solution to the Leap Year problem in Clojure:


I created a local helper, divisible-by?, using comp and partial to make the code more readable.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Friday, July 4, 2014

Exercism: "Robot name in Clojure"

This is my solution to the Robot name problem in Clojure:


This is the first exercise in which I've used some mutable state features of Clojure, atom in this case.

It also helped me to discover the repeatedly function.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

--------------------------------

Update:

After learning some new stuff, I've been able to simplify the code a bit more:


I used the :private true metadata key value pair to make capital-letters private, the special defn- macro instead of defn to make random-name private and the random-nth function.

You can nitpick this new version here.

Kata: Reverse Polish Notation Calculator in Clojure with Midje

I've just done the Reverse Polish Notation Calculator kata in Clojure using Midje.

These are the tests:


I really love how readable tests are when using Midje.

And this is the final version of the code:


I used a mix of TDD and REPL-driven development, as I did before for the Berlin Clock kata.

Again I commited the code after every passing test and every refactor and also commited the .lein-repl-history file to document all the micro-tests I did on the REPL.

Take a look at the code and commits in this GitHub repository.

Thursday, July 3, 2014

Exercism: "Grade School in Clojure"

This is my solution to the Grade School problem in Clojure:

The first working version:


Trying to improve its readability I introduced two local helpers in the sorted function:
sort-by-grades and sort-students-by-name.

This is the resulting version:


Finally, I experimented with the -> macro to see its effect on readability and got to this last version:


I think the -> macro is great.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Exercism: "Phone Number in Clojure"

This is my solution to the Phone Number problem in Clojure:

The first version:


And then a second one:


In this second version I removed some duplication with the help of the partial and comp functions and I also tried to make the code more readable by introducing several new helper functions.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Interesting Talk: "Failure for Fun and Profit!"

I've just watched this great talk by Kerri Miller:

Wednesday, July 2, 2014

Exercism: "Point Mutations (Hamming distance) in Clojure"

This is my solution to the Point Mutations problem in Clojure:


Compare it with the solution to the same exercise in Ruby:


The version in Clojure is simpler because its map function accepts more than one collection and also takes care of the cases in which the collections have different lengths.

You can nitpick my solution here or see all the exercises I've done so far in this repository.