Friday, January 30, 2015

Kata: Happy Numbers in Clojure

I've just dome the Happy Numbers kata in Clojure.

It's a simple kata that can be a lot of fun.

I used a mix of TDD and REPL-driven development to code it.

These are the resulting tests in Midje:

(ns happy-numbers.core-test
(:use midje.sweet)
(:use [happy-numbers.core]))
(facts
(facts
"about detecting happy numbers"
(happy? 1) => true
(happy? 4) => false
(happy? 7) => true
(happy? 10) => true
(happy? 31) => true)
(facts
"about happy numbers under a given number
(see http://mathworld.wolfram.com/HappyNumber.html)"
(happy-numbers-under 100) =>
'(1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97)))
and this is the code:

(ns happy-numbers.core)
(defn- parse-int [ch]
(Integer/parseInt (str ch)))
(def ^:private square
(partial map #(* % %)))
(defn- digits-in [n]
(map parse-int (str n)))
(defn- sum-squares-of [digits]
(reduce + (square digits)))
(defn- one-digit? [n]
(= 1 (count (digits-in n))))
(defn- happy-num? [n]
(let [sum-squared-digits (sum-squares-of (digits-in n))]
(if (one-digit? sum-squared-digits)
(= sum-squared-digits 1)
(recur sum-squared-digits))))
(def happy? (memoize happy-num?))
(defn happy-numbers-under [n]
(filter happy? (range 1 n)))
To document the process I commited the code after every passing test and every refactoring. I also commited the REPL history.

You can find the commits step by step here and the code in this repository in GitHub.

I used memoize to avoid repeated computations.

In the next days I will try other suggested optimizations based on the properties of happy numbers.

Interesting Talk: "Concurrency"

I've just watched this two lectures about concurrency from the CS 61A course from Berkeley University:

Monday, January 26, 2015

Refactoring Conway's Game of Life in Java

I've recently revisited the Java version of Conway's Game of Life that I did nearly a year ago, to refactor it using some of the ideas I used in my more recent Clojure version.

This is the UML for the refactored design:


I eliminated the LivingCells class that appeared in the previous design.

I pushed a lot of code from the GameOfLife class into Generation to eliminate a bit of feature envy. This is GameOfLife's code now:

package game;
public class GameOfLife {
private Generation currentGeneration;
public GameOfLife(Generation initialGeneration) {
this.currentGeneration = initialGeneration;
}
public void run(int steps) {
currentGeneration = evolve(steps, currentGeneration);
}
private Generation evolve(int steps, Generation currentGeneration) {
if (isOver(steps)) {
return currentGeneration;
}
return evolve(
steps - 1,
currentGeneration.produceNextGeneration());
}
private boolean isOver(int steps) {
return steps == 0 || currentGeneration.extinct();
}
public Generation currentGeneration() {
return currentGeneration;
}
}
and this is Generation's one:

package game;
public class Generation {
private Rules rules;
private Cells aliveCells;
public Generation(Rules rules, Cell... aliveCells) {
this(rules, new Cells(aliveCells));
}
public Generation(Rules rules, Cells aliveCells) {
this.rules = rules;
this.aliveCells = aliveCells;
}
public Generation produceNextGeneration() {
Cells nextGeneration = new Cells();
for (Cell neighbor : aliveCells.getNeighbors()) {
if (inNextGeneration(neighbor)) {
nextGeneration.add(neighbor);
}
}
return new Generation(rules, nextGeneration);
}
private boolean inNextGeneration(Cell neighbor) {
return rules.inNextGeneration(
isAlive(neighbor),
aliveNeighborsNumberFor(neighbor));
}
private int aliveNeighborsNumberFor(Cell cell) {
int res = 0;
for (Cell neighbor : cell.neighbors()) {
if (isAlive(neighbor)) {
res++;
}
}
return res;
}
private boolean isAlive(Cell cell) {
return aliveCells.contains(cell);
}
public boolean extinct() {
return aliveCells.empty();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Generation other = (Generation) obj;
if (aliveCells == null) {
if (other.aliveCells != null)
return false;
} else if (!aliveCells.equals(other.aliveCells))
return false;
return true;
}
}
I also refactored the tests eliminating all the checks based on strings and using constructors with variadic parameters.

Following the idea in the Clojure version I managed to simplify the Rules interface a lot:

package game;
public interface Rules {
public boolean inNextGeneration(
boolean alive,
int numberOfNeighbors);
}
Most of the other changes are just renaming of methods, variables and parameters.

This new code keeps the functionality and characteristics of the previous version but it's much simpler.

Sunday, January 25, 2015

Kata: Bank Account in Java

Álvaro and I have been pairing lately to do a subset of the Bank Account kata that Sandro Mancuso proposed as an exercise in his Crafting Code course.

We had to write and make the following acceptance test pass using Outside-In TDD:
Given a client makes a deposit of 1000.00 on 01/04/2014
And a withdrawal of 100.00 on 02/04/2014
And a deposit of 500.00 on 10/04/2014
When she prints her bank statement
Then she would see

DATE | AMOUNT | BALANCE
10/04/2014 | 500.00 | 1400.00
02/04/2014 | -100.00 | 900.00
01/04/2014 | 1000.00 | 1000.00
The goal of the exercise was to understand the outside-in or London-school TDD style.

After the course Álvaro and I continued working on the exercise.

We had many difficulties to get used to this style for several sessions because we weren't used to test behavior instead of state. We struggled a lot because we were working outside of our comfort zone. In one of the sessions, we rushed too much trying to move forward and make the acceptance test pass, which resulted in allocating some of the responsibilities very badly.

In the end, we managed to get out of the mess we got in by slowly refactoring it to a better design.

All in all, it's been a great experience and we've learned a lot pushing our limits a bit further.

Unfortunately, we didn't commit the code after each tiny step this time, only at the end of each pairing session.
You can find the resulting code in this GitHub repository.

As usual, it's been great pairing with Álvaro, thanks mate!

Thursday, January 22, 2015

Refactored Numbers Spelling kata in Clojure

I've refactored the Numbers Spelling kata I recently did in Clojure to remove some duplication.

Before refactoring it, I had to make the old spell-out-number-over-99 and spell-out-number-up-to-99 functions similar enough for the duplication pattern to emerge.

Then I could use the same function for both cases and also made some other minor changes such as using when-not form and renaming several bindings and arguments.

This is the refactored code:

(ns number-spelling.core)
(declare
one-word-numbers
num-digits
pow
number-spelling)
(defn spell-out [number]
(if-let [one-word-number (get one-word-numbers number)]
one-word-number
(let [num-digits (num-digits number)]
(cond
(> num-digits 9)
(number-spelling number 1 9 " billion" ", ")
(> num-digits 6)
(number-spelling number 1 6 " million" ", ")
(> num-digits 3)
(number-spelling number 1 3 " thousand" ", ")
(> num-digits 2)
(number-spelling number 1 2 " hundred" " and ")
:else
(number-spelling number 10 1 "" " ")))))
(defn- number-spelling [number factor exp separator1 separator2]
(let [power-of-ten (pow 10 exp)
close-number (* factor (quot number power-of-ten))
rest-of-number (rem number power-of-ten)]
(str (spell-out close-number)
separator1
(when-not (zero? rest-of-number)
(str separator2 (spell-out rest-of-number))))))
(defn- pow [base exp]
(reduce * (repeat exp base)))
(defn- num-digits [number]
(count (str number)))
(def ^:private one-word-numbers
{0 "zero"
1 "one"
2 "two"
3 "three"
4 "four"
5 "five"
6 "six"
7 "seven"
8 "eight"
9 "nine"
10 "ten"
11 "eleven"
12 "twelve"
13 "thirteen"
14 "fourteen"
15 "fifteen"
16 "sixteen"
17 "seventeen"
18 "eightteen"
19 "nineteen"
20 "twenty"
30 "thirty"
40 "forty"
50 "fifty"
60 "sixty"
70 "seventy"
80 "eighty"
90 "ninety"})

You can find the code in this repository in GitHub.

Tuesday, January 20, 2015

Kata: Numbers Spelling in Clojure

I've just done the Numbers Spelling kata in Clojure:

These are the tests using Midje:

(ns number-spelling.core-test
(:use midje.sweet)
(:use [number-spelling.core]))
(facts
"about number-spelling"
(fact
"it can spell out one-digit numbers"
(spell-out 0) => "zero"
(spell-out 1) => "one"
(spell-out 9) => "nine")
(fact
"it can spell out two-digit numbers"
(spell-out 10) => "ten"
(spell-out 11) => "eleven"
(spell-out 19) => "nineteen"
(spell-out 20) => "twenty"
(spell-out 21) => "twenty one"
(spell-out 30) => "thirty"
(spell-out 39) => "thirty nine"
(spell-out 95) => "ninety five")
(fact
"it can spell out three-digit numbers"
(spell-out 100) => "one hundred"
(spell-out 103) => "one hundred and three"
(spell-out 199) => "one hundred and ninety nine"
(spell-out 999) => "nine hundred and ninety nine")
(fact
"it can spell out four-digit numbers"
(spell-out 1000) => "one thousand"
(spell-out 1501) => "one thousand, five hundred and one"
(spell-out 9000) => "nine thousand"
(spell-out 9999) => "nine thousand, nine hundred and ninety nine")
(fact
"it can spell out five-digit numbers"
(spell-out 21501) => "twenty one thousand, five hundred and one"
(spell-out 99999) =>
"ninety nine thousand, nine hundred and ninety nine")
(fact
"it can spell out six-digit numbers"
(spell-out 999999) =>
"nine hundred and ninety nine thousand, nine hundred and ninety nine")
(fact
"it can spell out seven-digit numbers"
(spell-out 9999999) =>
"nine million, nine hundred and ninety nine thousand, nine hundred and ninety nine")
(fact
"it can spell out eight-digit numbers"
(spell-out 99999999) =>
"ninety nine million, nine hundred and ninety nine thousand, nine hundred and ninety nine")
(fact
"it can spell out nine-digit numbers"
(spell-out 999999999) =>
"nine hundred and ninety nine million, nine hundred and ninety nine thousand, nine hundred and ninety nine")
(fact
"it can spell out ten-digit numbers"
(spell-out 9999999999) =>
"nine billion, nine hundred and ninety nine million, nine hundred and ninety nine thousand, nine hundred and ninety nine")
(fact
"it can spell out a lot of billions!"
(spell-out 9999999999999) =>
"nine thousand, nine hundred and ninety nine billion, nine hundred and ninety nine million, nine hundred and ninety nine thousand, nine hundred and ninety nine"))
and this is the code:

(ns number-spelling.core)
(declare
one-word-numbers
num-digits
pow
spell-out-number-over-99
spell-out-number-up-to-99)
(defn spell-out [number]
(cond
(> (num-digits number) 9)
(spell-out-number-over-99 number 9 " billion" ", ")
(> (num-digits number) 6)
(spell-out-number-over-99 number 6 " million" ", ")
(> (num-digits number) 3)
(spell-out-number-over-99 number 3 " thousand" ", ")
(> (num-digits number) 2)
(spell-out-number-over-99 number 2 " hundred" " and ")
:else
(spell-out-number-up-to-99 number)))
(defn- spell-out-number-over-99 [number digits separator1 separator2]
(let [power-of-ten (pow 10 digits)
over-power-of-ten (rem number power-of-ten)]
(str (spell-out (quot number power-of-ten))
separator1
(if (zero? over-power-of-ten)
""
(str separator2 (spell-out over-power-of-ten))))))
(defn- spell-out-number-up-to-99 [number]
(if-let [one-word-number (get one-word-numbers number)]
one-word-number
(str (spell-out (* (quot number 10) 10))
(if (zero? (rem number 10))
""
(str " " (spell-out (rem number 10)))))))
(defn- pow [base exp]
(reduce * (repeat exp base)))
(def ^:private one-word-numbers
{0 "zero"
1 "one"
2 "two"
3 "three"
4 "four"
5 "five"
6 "six"
7 "seven"
8 "eight"
9 "nine"
10 "ten"
11 "eleven"
12 "twelve"
13 "thirteen"
14 "fourteen"
15 "fifteen"
16 "sixteen"
17 "seventeen"
18 "eightteen"
19 "nineteen"
20 "twenty"
30 "thirty"
40 "forty"
50 "fifty"
60 "sixty"
70 "seventy"
80 "eighty"
90 "ninety"})
(defn- num-digits [number]
(count (str number)))
To document the TDD process I commited the code after every passing test and every refactor. You can find the commits step by step here.

If you look at the commits, you'll notice that it took me some time to find a simple algorithm using TDD but once I found it I could simplify the code quite a bit.

You can find the code in this repository in GitHub.

Saturday, January 17, 2015

Interesting Paper: "Design Patterns in Dynamic Programming"

I've just read the slides of a very interesting talk by Peter Norvig:

Reading GOOS (XI)

These are the links mentioned in our last conversation about the 15th chapter:

Clojure Developers Barcelona: Reverse Polish Notation Calculator kata

Last Tuesday I facilitated a kata for the Clojure Developers Barcelona Group hosted by Akamon.

We've been doing several Clojure katas and talks during the last two months within a small study group (mainly composed of people who work in Akamon) as a preparation to bring back to life the Clojure Developers Barcelona Group.

This kata was the first one we did as Clojure Developers Barcelona Group.

We did the Reverse Polish Notation Calculator kata which is a very nice kata to practice.

Although 10 people had RSVPed that they were coming, in the end we were seven people: 4 Akamon workers, 2 people non-related to Akamon (a second-timer and a newcomer) and me. We formed 3 pairs and worked in the kata from 18:30 to 21:00.

I had a great time facilitating the kata, solving doubts and talking about Clojure.

If you like you can share your solution in the Clojure-Barcelona Google+ community. At the moment of writing this post, you'd find there two solutions: Rafa's and mine.

To finish I'd like to thank Akamon for hosting our events and all the attendants (Jorge, Jordi, Sergi, Álvaro, Rafa and Eloi) for their enthusiasm to learn and share in an afternoon of Clojure.

Saturday, January 10, 2015

Conferences in 2014

These are the conferences I attended last year:
* I was part of the team that organized it.
** I co-chaired the Dev Practices & Craftsmanship track.