Thursday, November 27, 2014

Quick sort in Clojure

(defn quicksort [coll]
(if (empty? coll)
'()
(let [el (first coll)
smaller (filter #(<= % el) (rest coll))
greater (filter #(> % el) (rest coll))]
(concat (quicksort smaller)
(cons el (quicksort greater))))))
view raw quicksort.clj hosted with ❤ by GitHub
Compare it with the same algorithm implemented in Haskell.

Tuesday, November 25, 2014

Validating credit card numbers in Clojure

(ns valid-credid-card)
(defn- parse-int [s]
(Integer. (re-find #"\d+" (str s))))
(defn- to-digits [n]
(map parse-int (str n)))
(def ^:private to-digits-rev
(comp reverse
(partial to-digits)))
(defn- double-second [coll]
(map-indexed
#(if (zero? (mod (+ %1 1) 2))
(* 2 %2)
%2)
coll))
(def ^:private sum-digits
(partial reduce #(+ %1 (reduce + (to-digits %2)))))
(defn is-valid? [num-credit-card]
(zero?
(mod
(->>
num-credit-card
to-digits-rev
double-second
sum-digits)
10)))

Sunday, November 23, 2014

Kata: FizzBuzz with no conditionals in Clojure

I've just done the FizzBuzz kata with the restriction of not using any kind of conditional.

This is the result after playing a bit in the REPL:

(def naturals (drop 1 (range)))
(def fizz-buzz-seq
(map #(clojure.string/replace (str %1 %2) #"^$" (str %3))
(cycle '("" "" "Fizz"))
(cycle '("" "" "" "" "Buzz"))
naturals))
(defn fizz-buzz [n]
(clojure.string/join " " (take n fizz-buzz-seq)))

Validating credit card numbers in Haskell

This Haskell code can validate a credit card number:

import Data.Char
toDigits :: Integer -> [Integer]
toDigits n = map (\ x -> toInteger (digitToInt x)) (show n)
toDigitsRev :: Integer -> [Integer]
toDigitsRev n = reverse (toDigits n)
doubleSecond :: [Integer] -> [Integer]
doubleSecond [] = []
doubleSecond [a] = a : []
doubleSecond (b : c : xs) = b : 2 * c : doubleSecond xs
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x : xs) = sum (toDigits x) + sumDigits xs
isValid :: Integer -> Bool
isValid n = mod (sumDigits (doubleSecond (toDigitsRev n))) 10 == 0

Interesting Talk: "Silex, desarrollo web ágil y profesional con PHP"

I've just watched this great talk by Javier Eguiluz:

Saturday, November 22, 2014

Interesting Talk: "Silex: An implementation detail"

I've just watched this great talk by Dave Marshall: It's about DDD, BDD, Ports and Adapters and the Entity-Control-Boundary Pattern (EBC).

You can find the source code of the examples in this GitHub repository.

Merge sort in Haskell

merge [] ys = ys
merge xs [] = xs
merge (x : xs) (y : ys) =
if x <= y then x : merge xs (y : ys) else y : merge (x : xs) ys
halve xs = splitAt (length xs `div` 2) xs
msort [] = []
msort [x] = [x]
msort xs = merge (msort ys) (msort zs)
where (ys, zs) = halve xs
view raw mergesort.hs hosted with ❤ by GitHub

Reading GOOS (VIII)

These are the links mentioned in this week's conversation about the 10th and 11th chapters:
  1. Code samples
  2. Posts and Papers
  3. Talks

Quick sort in Haskell

Haskell can be very beautiful:

quicksort [] = []
quicksort (x:xs) = quicksort smaller ++ [x] ++ quicksort greater
where
smaller = [a | a <- xs, a <= x]
greater = [b | b <- xs, b > x]
view raw quicksort.hs hosted with ❤ by GitHub

Thursday, November 20, 2014

Refactoring Conway's Game of Life in Clojure

In the previous post I presented a solution of Conway's Game of Life in Clojure.

I've refactored that code in order to eliminate some duplication from the game rules.

First of all, I coded using TDD a new function will-have-a-cell? that later substituted both will-go-on-being-a-cell? and will-be-a-cell?.

These are the tests for the game rules after deleting the obsolete functions (will-go-on-being-a-cell? and will-be-a-cell?):

;...
(facts
"about game of life rules"
(fact
"a location with a cell will have a cell in next generation
if it has the right number of neighbors"
(will-have-cell? [1 2] [[1 2] [1 1] [1 3]]) => true
(will-have-cell? [1 2] [[1 2] [1 1]]) => false
(will-have-cell? [1 2] [[1 2] [1 1] [1 3] [2 2]]) => true
(will-have-cell? [1 2] [[1 2] [0 2] [1 1] [1 3] [2 2]]) => false)
(fact
"a location without a cell will have a cell in next generation
if it has the right number of neighbors"
(will-have-cell? [1 2] [[1 1] [1 3]]) => false
(will-have-cell? [1 2] [[1 1] [1 3] [2 2]]) => true
(will-have-cell? [1 2] [[1 1]]) => false))
;...
and this is the new function's code:

; ...
(defn num-neighbors-being-a-cell [cell cells]
(count (filter (neighbors cell) cells)))
(defn has-cell? [loc cells]
(= loc (some #{loc} cells)))
(defn will-have-a-cell? [loc cells]
(let [num-neighbors (num-neighbors-being-a-cell loc cells)]
(or (= num-neighbors 3)
(and (= num-neighbors 2)
(has-cell? loc cells)))))
;...
Once I had the new function I used it inside both keep-being-cells and new-cells functions to highlight the duplication between them:

;...
(defn keep-being-cells [cells]
(set
(filter
#(will-have-a-cell? % cells)
cells)))
(defn new-cells [cells]
(set
(filter
#(will-have-a-cell? % cells)
(candidates-to-be-a-cell cells))))
(defn next-cells [cells]
(clojure.set/union
(keep-being-cells cells)
(new-cells cells)))
;...
Then I eliminated that duplication by using will-have-a-cell? directly in next-cells function, which made both keep-being-cells and new-cells obsolete:

;...
(defn all-neighbors-locations [cells]
(reduce clojure.set/union
(map neighbors cells)))
(defn next-cells [cells]
(set
(filter
#(will-have-a-cell? % cells)
(all-neighbors-locations cells))))
;...
Notice how will-have-a-cell? is used to filter all the possible locations (the current cells and their neighbors) which are given by the new all-neighbors-locations function.

Then I eliminated all the obsolete functions and their tests and did some renaming of the remaining functions, local bindings and parameters.

These are the resulting tests:

(ns game-of-life.core-test
(:use midje.sweet)
(:use [game-of-life.core]))
(facts
"about Game of Life"
(facts
"about neighbors"
(fact
"the neighbors of a given location can be known"
(neighbors [1 1]) => #{[0 0] [0 1] [0 2] [1 0] [1 2] [2 0] [2 1] [2 2]}
(neighbors [0 0]) => #{[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]})
(fact
"the number of neighbors of a given location which have a cell can be known"
(num-neighbors-with-a-cell [1 2] [[1 2] [4 5] [1 3]]) => 1
(num-neighbors-with-a-cell [1 2] [[1 2] [1 1] [1 3]]) => 2
(num-neighbors-with-a-cell [10 20] [[1 2] [1 1] [1 3]]) => 0))
(facts
"about game of life rules"
(fact
"a location with a cell will have a cell in next generation
if it has 2 or 3 neighbors"
(will-have-cell? [1 2] [[1 2] [1 1] [1 3]]) => true
(will-have-cell? [1 2] [[1 2] [1 1]]) => false
(will-have-cell? [1 2] [[1 2] [1 1] [1 3] [2 2]]) => true
(will-have-cell? [1 2] [[1 2] [0 2] [1 1] [1 3] [2 2]]) => false)
(fact
"a location without a cell will have a cell in next generation
if it has 3 neighbors"
(will-have-cell? [1 2] [[1 1] [1 3]]) => false
(will-have-cell? [1 2] [[1 1] [1 3] [2 2]]) => true
(will-have-cell? [1 2] [[1 1]]) => false))
(facts
"about Still lifes"
(fact
"a Block is a still life
(http://en.wikipedia.org/wiki/Still_life_%28cellular_automaton%29#Blocks)"
(let [a-block #{[0 0] [0 1] [1 1] [1 0]}
five-gens (game-of-life a-block 5)]
(nth five-gens 1) => a-block
(nth five-gens 2) => a-block
(nth five-gens 3) => a-block
(nth five-gens 4) => a-block))
(fact
"a Beehive is a still life
(http://www.conwaylife.com/wiki/Beehive)"
(let [a-beehive #{[0 1] [0 2] [1 0] [1 3] [2 1] [2 2]}
five-gens (game-of-life a-beehive 5)]
(nth five-gens 1) => a-beehive
(nth five-gens 2) => a-beehive
(nth five-gens 3) => a-beehive
(nth five-gens 4) => a-beehive))
(fact
"a Loaf is a still life
(http://en.wikipedia.org/wiki/Still_life_%28cellular_automaton%29#Loaves)"
(let [a-loaf #{[0 1] [0 2] [1 0] [1 3] [2 1] [2 3] [3 2]}
five-gens (game-of-life a-loaf 5)]
(nth five-gens 1) => a-loaf
(nth five-gens 2) => a-loaf
(nth five-gens 3) => a-loaf
(nth five-gens 4) => a-loaf))
(fact
"a Boat is a still life
(http://commons.wikimedia.org/wiki/File:Game_of_life_boat.svg)"
(let [a-boat #{[0 0] [0 1] [1 0] [1 2] [2 1]}
five-gens (game-of-life a-boat 5)]
(nth five-gens 1) => a-boat
(nth five-gens 2) => a-boat
(nth five-gens 3) => a-boat
(nth five-gens 4) => a-boat)))
(facts
"about Oscillators"
(fact
"a Blinker oscillates with period two
(http://en.wikipedia.org/wiki/File:Game_of_life_blinker.gif)"
(let [a-blinker #{[0 1] [0 2] [0 0]}
a-blinker-next #{[0 1] [1 1] [-1 1]}
five-gens (game-of-life a-blinker 5)]
(nth five-gens 1) => a-blinker-next
(nth five-gens 2) => a-blinker
(nth five-gens 3) => a-blinker-next
(nth five-gens 4) => a-blinker))
(fact
"a Toad oscillates with period two
(http://en.wikipedia.org/wiki/File:Game_of_life_toad.gif)"
(let [a-toad #{[0 3] [1 0] [1 2] [0 2] [1 1] [0 1]}
a-toad-next #{[0 3] [1 0] [0 0] [-1 2] [1 3] [2 1]}
five-gens (game-of-life a-toad 5)]
(nth five-gens 1) => a-toad-next
(nth five-gens 2) => a-toad
(nth five-gens 3) => a-toad-next
(nth five-gens 4) => a-toad)))
(facts
"about Gliders"
(fact
"a Glider moves diagonally with period 4
(http://en.wikipedia.org/wiki/File:Game_of_life_animated_glider.gif)"
(let [a-glider #{[0 0] [0 1] [0 2] [1, 0] [2, 1]}
five-gens (game-of-life a-glider 5)]
(nth five-gens 1) => #{[0 0] [0 1] [1 0] [-1 1] [1 2]}
(nth five-gens 2) => #{[0 0] [1 0] [-1 1] [-1 0] [0 2]}
(nth five-gens 3) => #{[0 0] [-1 1] [-1 0] [1 1] [0 -1]}
(nth five-gens 4) => #{[-1 1] [-1 0] [0 -1] [1 0] [-1 -1]}))))
and this is the resulting code:

(ns game-of-life.core)
(defn neighbors [[x-cell y-cell]]
(set (for [x (range (dec x-cell) (+ x-cell 2))
y (range (dec y-cell) (+ y-cell 2))
:when (not (and (= x x-cell) (= y y-cell)))]
[x y])))
(defn num-neighbors-with-a-cell [loc cells]
(count (filter (neighbors loc) cells)))
(defn has-cell? [loc cells]
(= loc (some #{loc} cells)))
(defn will-have-cell? [loc cells]
(let [num-neighbors (num-neighbors-with-a-cell loc cells)]
(or (= num-neighbors 3)
(and (= num-neighbors 2)
(has-cell? loc cells)))))
(defn locations [cells]
(reduce clojure.set/union (map neighbors cells)))
(defn next-cells [cells]
(set (filter #(will-have-cell? % cells) (locations cells))))
(defn game-of-life [cells num-iter]
(take num-iter (iterate next-cells cells)))
which is slightly shorter than the one in the previous version.

As usual I commited the code after every passing test and every refactor.

You will notice a problem I had with Midje :autotest not reacting properly after some of the renamings I did. I had to restart it so that it could take into account the changes.

If you want to follow the whole process, you can find the commits step by step here.

You can also find the resulting code in GitHub.

Wednesday, November 19, 2014

Kata: Conway's Game of Life in Clojure

Last Saturday I attended the Global Day of Code Retreat in Zaragoza where I had a great time practicing with other kindred spirits.

Today I did a version of Conway's Game of Life in Clojure having in mind some of the ideas I took home from the code retreat.

These are the resulting tests using Midje:

(ns game-of-life.core-test
(:use midje.sweet)
(:use [game-of-life.core]))
(facts
"about Game of Life"
(facts
"about cells neighbors"
(fact
"we can know the neighbors of a cell"
(neighbors [1 1]) => #{[0 0] [0 1] [0 2] [1 0] [1 2] [2 0] [2 1] [2 2]}
(neighbors [0 0]) => #{[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]})
(fact
"we can know how many neighbors are a cell"
(num-neighbors-being-a-cell [1 2] [[1 2] [4 5] [1 3]]) => 1
(num-neighbors-being-a-cell [1 2] [[1 2] [1 1] [1 3]]) => 2
(num-neighbors-being-a-cell [10 20] [[1 2] [1 1] [1 3]]) => 0))
(facts
"about game of life rules"
(fact
"a cell with enough neighbors with cells will go on being a cell in the next generation"
(will-go-on-being-a-cell? 3) => true
(will-go-on-being-a-cell? 2) => true)
(fact
"a cell with too few neighbors with cells will not go on being a cell in the next generation"
(will-go-on-being-a-cell? 1) => false)
(fact
"a cell with too many neighbors with cells will not go on being a cell in the next generation"
(will-go-on-being-a-cell? 4) => false)
(fact
"a candidate with the right amount of neighbors with cells will be a cell in the next generation"
(will-be-a-cell? 3) => true
(will-be-a-cell? 4) => false
(will-be-a-cell? 2) => false))
(facts
"about candidates to be a cell in next generation"
(fact
"the candidates are the cells neighbors"
(candidates-to-be-a-cell []) => #{}
(candidates-to-be-a-cell [[1 1]]) => #{[0 0] [0 1] [0 2] [1 0] [1 2] [2 0] [2 1] [2 2]})
(fact
"no cells are included in the candidates"
(candidates-to-be-a-cell [[1 1] [0 0]]) => #{[0 1] [0 2] [1 0] [1 2] [2 0] [2 1] [2 2]
[-1 -1] [-1 0] [-1 1] [0 -1] [1 -1] }))
(facts
"about cells keep being cells in next generation"
(fact
"no cells keep being cells when there are no cells"
(keep-being-cells []) => #{})
(fact
"no cells keep being cells because they do not have enough neighbors that are cells"
(keep-being-cells [[2 2] [1 1]]) => #{})
(fact
"the cells keep being cells are the cells with just enough neighbors that are cells"
(keep-being-cells [[2 2] [0 0] [1 1] [-1 -1]]) => #{[0 0] [1 1]}
(keep-being-cells [[0 0] [0 1] [1 0] [1 1]]) => #{[0 0] [0 1] [1 0] [1 1]}))
(facts
"about new cells in next generation"
(fact
"the new cells are neighbors of the cells with enough neighbors that are cells"
(new-cells []) => #{}
(new-cells [[2 2] [0 0] [1 1] [-1 -1] [1 0]]) => #{[0 1] [0 -1] [2 1]}
(new-cells [[0 1] [1 0] [1 1]]) => #{[0 0]}))
(facts
"about next generation cells"
(fact
"the next generation cells are the union of the cells that keep being cells and the new cells"
(next-cells []) => #{}
(next-cells [[2 2] [0 0] [1 1] [-1 -1] [1 0]]) => #{[0 1] [0 -1] [2 1] [1 0] [0 0] [1 1]}
(next-cells [[0 1] [1 0] [1 1]]) => #{[0 0] [0 1] [1 0] [1 1]}))
(facts
"about Still lifes"
(fact
"a Block is a still life
(http://en.wikipedia.org/wiki/Still_life_%28cellular_automaton%29#Blocks)"
(let [a-block #{[0 0] [0 1] [1 1] [1 0]}
five-gens (game-of-life a-block 5)]
(nth five-gens 1) => a-block
(nth five-gens 2) => a-block
(nth five-gens 3) => a-block
(nth five-gens 4) => a-block))
(fact
"a Beehive is a still life
(http://www.conwaylife.com/wiki/Beehive)"
(let [a-beehive #{[0 1] [0 2] [1 0] [1 3] [2 1] [2 2]}
five-gens (game-of-life a-beehive 5)]
(nth five-gens 1) => a-beehive
(nth five-gens 2) => a-beehive
(nth five-gens 3) => a-beehive
(nth five-gens 4) => a-beehive))
(fact
"a Loaf is a still life
(http://en.wikipedia.org/wiki/Still_life_%28cellular_automaton%29#Loaves)"
(let [a-loaf #{[0 1] [0 2] [1 0] [1 3] [2 1] [2 3] [3 2]}
five-gens (game-of-life a-loaf 5)]
(nth five-gens 1) => a-loaf
(nth five-gens 2) => a-loaf
(nth five-gens 3) => a-loaf
(nth five-gens 4) => a-loaf))
(fact
"a Boat is a still life
(http://commons.wikimedia.org/wiki/File:Game_of_life_boat.svg)"
(let [a-boat #{[0 0] [0 1] [1 0] [1 2] [2 1]}
five-gens (game-of-life a-boat 5)]
(nth five-gens 1) => a-boat
(nth five-gens 2) => a-boat
(nth five-gens 3) => a-boat
(nth five-gens 4) => a-boat)))
(facts
"about Oscillators"
(fact
"a Blinker oscillates with period two
(http://en.wikipedia.org/wiki/File:Game_of_life_blinker.gif)"
(let [a-blinker #{[0 1] [0 2] [0 0]}
a-blinker-next #{[0 1] [1 1] [-1 1]}
five-gens (game-of-life a-blinker 5)]
(nth five-gens 1) => a-blinker-next
(nth five-gens 2) => a-blinker
(nth five-gens 3) => a-blinker-next
(nth five-gens 4) => a-blinker))
(fact
"a Toad oscillates with period two
(http://en.wikipedia.org/wiki/File:Game_of_life_toad.gif)"
(let [a-toad #{[0 3] [1 0] [1 2] [0 2] [1 1] [0 1]}
a-toad-next #{[0 3] [1 0] [0 0] [-1 2] [1 3] [2 1]}
five-gens (game-of-life a-toad 5)]
(nth five-gens 1) => a-toad-next
(nth five-gens 2) => a-toad
(nth five-gens 3) => a-toad-next
(nth five-gens 4) => a-toad)))
(facts
"about Gliders"
(fact
"a Glider moves diagonally with period 4
(http://en.wikipedia.org/wiki/File:Game_of_life_animated_glider.gif)"
(let [a-glider #{[0 0] [0 1] [0 2] [1, 0] [2, 1]}
five-gens (game-of-life a-glider 5)]
(nth five-gens 1) => #{[0 0] [0 1] [1 0] [-1 1] [1 2]}
(nth five-gens 2) => #{[0 0] [1 0] [-1 1] [-1 0] [0 2]}
(nth five-gens 3) => #{[0 0] [-1 1] [-1 0] [1 1] [0 -1]}
(nth five-gens 4) => #{[-1 1] [-1 0] [0 -1] [1 0] [-1 -1]}))))
and this is the code:

(ns game-of-life.core
(:require [clojure.set :only [union difference]]))
(defn neighbors [[x-cell y-cell]]
(set
(for [x (range (dec x-cell) (+ x-cell 2))
y (range (dec y-cell) (+ y-cell 2))
:when (not (and (= x x-cell) (= y y-cell)))]
[x y])))
(defn num-neighbors-being-a-cell [cell cells]
(count (filter (neighbors cell) cells)))
(defn will-go-on-being-a-cell? [num-neighbors-being-a-cell]
(or (= num-neighbors-being-a-cell 3)
(= num-neighbors-being-a-cell 2)))
(defn will-be-a-cell? [num-neighbors-being-a-cell]
(= num-neighbors-being-a-cell 3))
(defn candidates-to-be-a-cell [cells]
(clojure.set/difference
(reduce clojure.set/union
(map neighbors cells))
(set cells)))
(defn keep-being-cells [cells]
(set
(filter
#(will-go-on-being-a-cell?
(num-neighbors-being-a-cell % cells))
cells)))
(defn new-cells [cells]
(set
(filter
#(will-be-a-cell?
(num-neighbors-being-a-cell % cells))
(candidates-to-be-a-cell cells))))
(defn next-cells [cells]
(clojure.set/union
(keep-being-cells cells)
(new-cells cells)))
(defn game-of-life [cells num-iter]
(take num-iter (iterate next-cells cells)))
When I have some more time and learn more Clojure, I'd like to make it configurable to change the geometry of the game and its rules using different versions of the neighbors, will-go-on-being-a-cell? and will-be-a-cell? functions.

I did another version of Conway's Game of Life in Java some time ago which could be configured in that manner.

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

I commited the code after every passing test and every refactor. I also commited the tiny tests and spikes I did on the REPL.

If you want to follow the process, you can find the commits step by step here.

You can also find the resulting code in GitHub.

Thanks to all the colleagues from Zaragoza!

Friday, November 14, 2014

MOOCs: Web Application Architectures in Coursera

I recently finished this Coursera course by Dr. Greg Heileman from the University of New Mexico: The theory in this course was a great introduction to know general concepts and patterns that are used in web development and see how they are applied in Ruby on Rails.

However, the homework assignments were not challenging at all.

In any case, I'd like to thank Coursera and Professor Heileman for offering this course.

Caesar cipher in Perl

#!/usr/bin/perl
use strict;
use warnings;
sub shiftChar {
(my $asciiVal, my $base, my $shift) = @_;
return chr(($asciiVal - $base + $shift) % 26 + $base );
}
sub isUpperCase {
my $asciiVal = shift;
return ($asciiVal >= 65 && $asciiVal <= 90);
}
sub isLowerCase {
my $asciiVal = shift;
return ($asciiVal >= 97 && $asciiVal <= 122);
}
sub charCipher {
(my $character, my $shift) = @_;
my $asciiVal = ord($character);
if (isLowerCase($asciiVal)) {
return shiftChar($asciiVal, 97, $shift);
}
if (isUpperCase($asciiVal)) {
return shiftChar($asciiVal, 65, $shift);
}
return $character;
}
sub charDecipher {
(my $character, my $shift) = @_;
return charCipher($character, - $shift);
}
sub transformText {
(my $text, my $shift, my $function) = @_;
return join('', map { $function->($_, $shift) } split('', $text));
}
sub caesarCipher {
return transformText(@_, \&charCipher);
}
sub caesarDecipher {
return transformText(@_, \&charDecipher);
}
my $text = "Todo lo que se preguntaba eran las mismas respuestas que buscamos el resto de nosotros. ¿De dónde vengo? ¿A dónde voy? ¿Cuánto tiempo tengo? Todo lo que pude hacer fue sentarme y ver como moría. z";
my $expectedSolution = "Wrgr or txh vh suhjxqwded hudq odv plvpdv uhvsxhvwdv txh exvfdprv ho uhvwr gh qrvrwurv. ¿Gh góqgh yhqjr? ¿D góqgh yrb? ¿Fxáqwr wlhpsr whqjr? Wrgr or txh sxgh kdfhu ixh vhqwduph b yhu frpr pruíd. c";
my $solution = caesarCipher($text, 3);
print "Caesar cipher is ok: ", $expectedSolution eq $solution, "\n";
print "Caesar decipher is ok: ", $text eq caesarDecipher($solution, 3), "\n";

Reading GOOS (VII)

These are the links mentioned in this week's conversation about the 8th and 9th chapters:
  1. Code samples
  2. Posts

Thursday, November 13, 2014

Practicing with sets in Advanced Student Language

This is the version I did some time ago using the Advanced Student Language of the sets exercise from the Coursera Scala course:

;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-advanced-reader.ss" "lang")((modname sets) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ())))
;; Number -> (Number => Boolean)
;; Contains set an elem
(define (contains set elem)
(set elem))
(check-expect
(contains (lambda (x) (= 2 x)) 2)
true)
(check-expect
(contains (lambda (x) (= 2 x)) 3)
false)
;; Number -> (Number => Boolean)
;; Singleton set
(define (singletonSet elem)
(lambda (x)
(= elem x)))
(check-expect
(contains (singletonSet 4) 4)
true)
(check-expect
(contains (singletonSet 3) 4)
false)
;; (Number => Boolean), (Number => Boolean) -> (Number => Boolean)
;; Union of sets
(define (union set1 set2)
(lambda (x)
(or (set1 x)
(set2 x))))
(define set-created-using-union
(union
(lambda (x)
(= (remainder x 2) 0))
(lambda (x) (> x 2))))
(check-expect
(contains set-created-using-union 6)
true)
(check-expect
(contains set-created-using-union 1)
false)
(check-expect
(contains set-created-using-union 7)
true)
;; (Number => Boolean), (Number => Boolean) -> (Number => Boolean)
;; Intersection of sets
(define (intersection set1 set2)
(lambda (x)
(and (set1 x)
(set2 x))))
(define set-created-using-intersection
(intersection
(lambda (x) (< x 4))
(lambda (x) (> x 2))))
(check-expect
(contains
set-created-using-intersection 3)
true)
(check-expect
(contains
set-created-using-intersection 2)
false)
;; (Number => Boolean), (Number => Boolean) -> (Number => Boolean)
;; Difference of sets
(define (diff set1 set2)
(lambda (x)
(and (set1 x)
(not (set2 x)))))
(define set-created-using-diff
(diff (lambda (x) (< x 4))
(lambda (x) (> x 2))))
(check-expect
(contains set-created-using-diff 2)
true)
(check-expect
(contains set-created-using-diff 3)
false)
;; (Number => Boolean), (Number => Boolean) -> Boolean
;; Check if a predicate is true for all members of an interval which is inside [-1000, 1000]
(define (forall? set pred)
(iter (- BOUND) set pred))
(define BOUND 1000)
(define (iter a set pred)
(cond ((> a BOUND)
true)
(((diff set pred) a)
false)
(else
(iter (+ a 1) set pred))))
(check-expect
(forall? (lambda (x) (< -2 x 2))
(lambda (x) (< x 3)))
true)
(check-expect
(forall? (lambda (x) (< -2 x 2))
(lambda (x) (= (remainder x 2) 0)))
false)
;; (Number => Boolean), (Number => Boolean) -> Boolean
;; Check if a predicate is true for any member of an interval which is inside [-1000, 1000]
(define (exists? set pred)
(not (forall? set (diff set pred))))
(check-expect
(exists? (lambda (x) (< -2 x 2))
(lambda (x) (= (remainder x 2) 0)))
true)
(check-expect
(exists? (lambda (x) (< -2 x 2))
(lambda (x) (> x 4)))
false)
;; (Number => Boolean), (Number => Number) -> (Number => Boolean)
;; Maps using a given function a set in an interval which is inside [-1000, 1000]
(define (mapset set func)
(lambda (y) (exists? set (lambda (x) (= (func x) y)))))
(define set-defined-using-mapset
(mapset (lambda (x) (< -3 x 3))
(lambda (x) (* x x))))
(check-expect
(contains set-defined-using-mapset 4)
true)
(check-expect
(contains set-defined-using-mapset 1)
true)
(check-expect
(contains set-defined-using-mapset -2)
false)
(check-expect
(contains set-defined-using-mapset -1)
false)
(define other-set-defined-using-mapset
(mapset (lambda (x) (< -3 x 3))
(lambda (x) (- x x))))
(check-expect
(contains other-set-defined-using-mapset -2)
false)
(check-expect
(contains other-set-defined-using-mapset -1)
false)
(check-expect
(contains other-set-defined-using-mapset 0)
true)
(check-expect
(contains other-set-defined-using-mapset 1)
false)
(check-expect
(contains other-set-defined-using-mapset 2)
false)
view raw sets.rkt hosted with ❤ by GitHub

It helped me to practice with lambdas and to blur the border between data and functions.

Caesar Cipher in Haskell

import Data.Char
let2int initchr c = ord c - ord initchr
int2let initchr n = chr (ord initchr + n)
lower2int = let2int 'a'
upper2int = let2int 'A'
int2lower = int2let 'a'
int2upper = int2let 'A'
shiftcase n c int2case case2int =
int2case ((case2int c + n) `mod` 26)
shift n c
| isLower c = shiftcase n c int2lower lower2int
| isUpper c = shiftcase n c int2upper upper2int
| otherwise = c
encode n xs = [shift n x | x <- xs]

Detecting balanced Parentheses in Advanced Student Language

Today I revisited this exercise from the Coursera Scala course that I did some time ago using the Advanced Student Language:

;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-advanced-reader.ss" "lang")((modname balance) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ())))
(check-expect
(balanced-parentheses? "") true)
(check-expect
(balanced-parentheses? "()") true)
(check-expect
(balanced-parentheses? "(moko)") true)
(check-expect
(balanced-parentheses?
"(if (zero? x) max (/ 1 x))")
true)
(check-expect
(balanced-parentheses?
"I told him (that it’s not (yet) done). (But he wasn’t listening)")
true)
(check-expect
(balanced-parentheses? ")") false)
(check-expect
(balanced-parentheses? "())( )") false)
(check-expect
(balanced-parentheses? "())(") false)
(check-expect
(balanced-parentheses? ":-)") false)
(define (balanced-parentheses? str)
(letrec
([f
(lambda (char-list elements-in-stack)
(cond ((empty? char-list)
(= elements-in-stack 0))
((char=? (car char-list) #\()
(f (cdr char-list) (+ elements-in-stack 1)))
((and (char=? (car char-list) #\))
(= elements-in-stack 0))
false)
((char=? (car char-list) #\))
(f (cdr char-list) (- elements-in-stack 1)))
(else
(f (cdr char-list) elements-in-stack))))])
(f (string->list str) 0)))
I refactored it to define the helper function f inside balanced-parentheses?.

Since it is not allowed to have nested function definitions in Advanced Student Language (it's in Racket), I defined the function using letrec and a lambda.

I had forgotten how many parentheses a cond needs in Advanced Student Language. In that sense Clojure is far more convenient.

Revisited Kata: Berlin Clock in Clojure

I've revisited the code of the Berlin Clock kata that I did sometime ago in Clojure to apply on it some of the things that I've learned lately.

This is my original solution:

(ns berlin_clock.core)
(use '[clojure.string :only (join split)])
(defn show [time]
(let
[[h m s] (map #(Integer. %) (split time #":"))
turn-on-red (fn [num-lamps] (repeat num-lamps "R"))
turn-on-yellow (fn [num-lamps] (repeat num-lamps "Y"))
turn-off (fn [num-lamps] (repeat num-lamps "O"))
turn-on-YYR (fn [num-lamps-on]
(take num-lamps-on (cycle ["Y" "Y" "R"])))
show (comp (partial apply str) concat)
show-lamps (fn [num-lamps-on num-lamps turn-on]
(let [num-lamps-off (- num-lamps
num-lamps-on)]
(show (turn-on num-lamps-on)
(turn-off num-lamps-off))))
seconds (if (zero? (rem s 2)) "Y" "O")
hours-first-row (show-lamps (quot h 5) 4 turn-on-red)
hours-second-row (show-lamps (rem h 5) 4 turn-on-red)
minutes-first-row (show-lamps (quot m 5) 11 turn-on-YYR)
minutes-second-row (show-lamps (rem m 5) 4 turn-on-yellow)]
(join "\n"
[seconds
hours-first-row
hours-second-row
minutes-first-row
minutes-second-row])))
and this is the new one:

(ns berlin_clock.core)
(use '[clojure.string :only (join split)])
(defn- turn-on-red [num-lamps]
(repeat num-lamps "R"))
(defn- turn-on-yellow [num-lamps]
(repeat num-lamps "Y"))
(defn- turn-off [num-lamps]
(repeat num-lamps "O"))
(defn- turn-on-YYR [num-lamps-on]
(take num-lamps-on (cycle ["Y" "Y" "R"])))
(defn- show-lamps [num-lamps-on num-lamps turn-on]
(let [show (comp join concat)
num-lamps-off (- num-lamps num-lamps-on)]
(show (turn-on num-lamps-on)
(turn-off num-lamps-off))))
(defn show [time]
(let
[[h m s] (map #(Integer. %) (split time #":"))
seconds-lamps-row (if (even? s) "Y" "O")
hours-lamps-first-row (show-lamps (quot h 5) 4 turn-on-red)
hours-lamps-second-row (show-lamps (rem h 5) 4 turn-on-red)
minutes-lamps-first-row (show-lamps (quot m 5) 11 turn-on-YYR)
minutes-lamps-second-row (show-lamps (rem m 5) 4 turn-on-yellow)]
(join "\n"
[seconds-lamps-row
hours-lamps-first-row
hours-lamps-second-row
minutes-lamps-first-row
minutes-lamps-second-row])))

Wednesday, November 12, 2014

Euler Project: Problem 2 in Haskell

This is my solution in Haskell to the second problem:

-- Slow
fib 0 = 1
fib 1 = 1
fib n = fib (n - 2) + fib (n - 1)
res1 =
sum [x | x <- takeWhile (< 4000000) (map fib [1..]),
mod x 2 == 0] -- 4613732
-- Fast
fast_fibs =
1:1:zipWith (+) fast_fibs (tail fast_fibs)
res2 =
sum [x | x <- takeWhile (< 4000000) fast_fibs,
mod x 2 == 0] -- 4613732
view raw euler02.hs hosted with ❤ by GitHub

I still get a bit dizzy when I think about the second solution...

You will find a great explanation of the second solution in this post:
Fibonacci numbers: the slow way or the fast and lazy way

You'll find the solutions in Haskell to Project Euler problems that I've done so far in this GitHub repository.

Kata: FizzBuzz in SML

This is the code of the FizzBuzz kata in SML that I did some time ago using pattern matching and refactored this morning to use List's map and tabulate functions:

fun fizz_buzz num =
let
val remainders = (num mod 3, num mod 5)
in
case remainders of
(0, 0) => "FizzBuzz"
| (0, _) => "Fizz"
| (_, 0) => "Buzz"
| _ => Int.toString(num)
end
fun fizz_buzz_up_to n =
map fizz_buzz (List.tabulate(n, fn x => x + 1))
val test_not_multiple_of_three_nor_five =
fizz_buzz(1) = "1"
val test_other_not_multiple_of_three_nor_five =
fizz_buzz(2) = "2"
val test_three = fizz_buzz(3) = "Fizz"
val test_other_multiple_of_three = fizz_buzz(9) = "Fizz"
val test_five = fizz_buzz(5) = "Buzz"
val test_other_multiple_of_five = fizz_buzz(10) = "Buzz"
val test_multiple_of_three_and_five = fizz_buzz(15) = "FizzBuzz"
val test_first_fifteen_numbers =
fizz_buzz_up_to 15 =
["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
view raw fizzbuzz.sml hosted with ❤ by GitHub

You can check the code in this Bitbucket repository.

Reading GOOS (VI)

These are the links mentioned in this week's conversation about the 7th chapter:
  1. Posts and papers
  2. Talks
  3. Books

Monday, November 10, 2014

Kata: Refactoring Tennis in Ruby

We practiced with the Refactoring Tennis kata in the last Barcelona Ruby meetup.

There were three different versions of the original code. I refactored the first one.

This is the original code:

class TennisGame
def initialize(player1_name, player2_name)
@player1_name = player1_name
@player2_name = player2_name
@p1points = 0
@p2points = 0
end
def won_point(player_name)
if player_name == @player1_name
@p1points += 1
else
@p2points += 1
end
end
def score
result = ""
tempScore=0
if (@p1points==@p2points)
result = {
0 => "Love-All",
1 => "Fifteen-All",
2 => "Thirty-All",
}.fetch(@p1points, "Deuce")
elsif (@p1points>=4 or @p2points>=4)
minusResult = @p1points-@p2points
if (minusResult==1)
result ="Advantage " + @player1_name
elsif (minusResult ==-1)
result ="Advantage " + @player2_name
elsif (minusResult>=2)
result = "Win for " + @player1_name
else
result ="Win for " + @player2_name
end
else
(1...3).each do |i|
if (i==1)
tempScore = @p1points
else
result+="-"
tempScore = @p2points
end
result += {
0 => "Love",
1 => "Fifteen",
2 => "Thirty",
3 => "Forty",
}[tempScore]
end
end
result
end
end

First, I tried to refactor the code to the State Pattern as I did once before in C++. Then I realized checking the tests that the code was not meant to model a real tennis game. It's just focused in displaying the current score.

So I decided to try to separate the code that was keeping the tennis game score from the code that was displaying its score. I also wanted to be able to display the score in different languages.

This is the resulting code after the refactoring:

class TennisGame
attr_reader :game_score, :score_displayer
def initialize(game_score, score_displayer)
@game_score = game_score
@score_displayer = score_displayer
end
def won_point(player_name)
game_score.won_point(player_name)
end
def score
score_displayer.display(game_score)
end
end
class GameScore
attr_reader :first_player, :second_player
def initialize(first_player, second_player)
@first_player = first_player
@second_player = second_player
end
def tied?
first_player.points == second_player.points
end
def advantage_for_any_player?
both_with_forty_or_more? and points_difference() == 1
end
def over?
any_over_forty? and points_difference() >= 2
end
def won_point(player_name)
if player_name == first_player.name
first_player.won_point
else
second_player.won_point
end
end
def current_winner
first_player.points > second_player.points ? first_player : second_player
end
private
def points_difference
(first_player.points - second_player.points).abs
end
def both_with_forty_or_more?
first_player.points >= 3 and second_player.points >= 3
end
def any_over_forty?
first_player.points >= 4 or second_player.points >= 4
end
end
class Player
attr_reader :points, :name
def initialize(name)
@name = name
@points = 0
end
def won_point
@points += 1
end
end
class ScoreDisplayer
attr_accessor :vocabulary
def initialize
@vocabulary = GameVocabulary.new({
:zero_all => "Love-All",
:fifteen_all => "Fifteen-All",
:thirty_all => "Thirty-All",
:deuce => "Deuce",
:zero => "Love",
:fifteen => "Fifteen",
:thirty => "Thirty",
:forty => "Forty",
:advantage => "Advantage",
:game_over => "Win for"
})
end
def display(game_score)
if game_score.tied?
display_tie(game_score.first_player)
elsif game_score.over?
display_game_over(game_score.current_winner())
elsif game_score.advantage_for_any_player?
display_advantage(game_score.current_winner())
else
display_default(game_score.first_player, game_score.second_player)
end
end
def display_game_over(winner)
@vocabulary.word_for(:game_over) + " " + winner.name
end
def display_advantage(player_with_advantage)
@vocabulary.word_for(:advantage) + " " + player_with_advantage.name
end
def display_tie(any_player)
key = {
0 => :zero_all,
1 => :fifteen_all,
2 => :thirty_all,
}.fetch(any_player.points, :deuce)
@vocabulary.word_for(key)
end
def display_default(first_player, second_player)
key_by_points = {
0 => :zero,
1 => :fifteen,
2 => :thirty,
3 => :forty,
}
@vocabulary.word_for(key_by_points[first_player.points]) +
"-" +
@vocabulary.word_for(key_by_points[second_player.points])
end
end
class GameVocabulary
def initialize(vocabulary)
@vocabulary = vocabulary
end
def word_for(key)
@vocabulary[key]
end
end

The TennisGame has two collaborators: the GameScore and the ScoreDisplayer.

The GameScore keeps track of the two Players in order to answer questions about the game score, whereas the ScoreDisplayer is in charge of displaying the score.

By default the ScoreDisplayer uses an English GameVocabulary, but the GameVocabulary can be injected through its accessor in order to display the score a different language (check the tests to see how the score is displayed in Spanish).

You can check the code and its tests in this GitHub repository.

I also committed after every tiny refactoring step so you can follow the process (especially the changes of mind I had and the dead-ends I found).

This kata was a great puzzle to practise and think.

I'd like to thank David Vrensk for his great work facilitating the kata and the interesting talk about Deliberate Practice that he gave before.

Sunday, November 9, 2014

Kata: Bowling Game in Clojure

I've just done the Bowling Game Kata in Clojure.

These are the tests using Midje:

(ns bowling-game.core-test
(:use midje.sweet)
(:use [bowling-game.core]))
(def a-gutter-game (repeat 20 0))
(def a-no-spares-no-strikes-game
(concat [1 6 4 5 3 1] (repeat 14 0)))
(def a-game-with-spares
(concat [4 6 4 5 3 1] (repeat 14 0)))
(def a-game-with-strikes
(concat [10 4 5 3 1] (repeat 14 0)))
(def a-game-with-spare-in-10th-frame
(concat (repeat 14 0) [3 1 4 2 4 6] [2]))
(def a-game-with-strike-in-10th-frame
(concat (repeat 14 0) [3 1 4 2 10] [2 3]))
(def a-perfect-game
(repeat 12 10))
(facts "about bowling-game"
(fact "it scores a game with no spins down"
(score a-gutter-game) => 0)
(fact "it scores a game with neither spares nor strikes"
(score a-no-spares-no-strikes-game) => 20)
(fact "it scores a game with a spare"
(score a-game-with-spares) => 27)
(fact "it scores a game with a strike"
(score a-game-with-strikes) => 32)
(fact "it scores a game with a spare in the 10th frame"
(score a-game-with-spare-in-10th-frame) => 22)
(fact "it scores a game with a strike in the 10th frame"
(score a-game-with-strike-in-10th-frame) => 25)
(fact "it scores a perfect game"
(score a-perfect-game) => 300))

and this is the code:

(ns bowling-game.core)
(defn- points [rolls]
(reduce + rolls))
(def ^:private ten-points?
(comp (partial = 10) points))
(def ^:private strike?
(comp ten-points? (partial take 1)))
(def ^:private spare?
(comp ten-points? (partial take 2)))
(defn- get-rolls-using [get-fn rolls]
(if (strike? rolls)
(get-fn 1 rolls)
(get-fn 2 rolls)))
(defn- first-frame [rolls]
(get-rolls-using take rolls))
(defn- rest-frames [rolls]
(get-rolls-using drop rolls))
(defn- take-next [n rolls]
(drop n (take 3 rolls)))
(defn- bonus-rolls [rolls]
(cond (strike? rolls) (take-next 1 rolls)
(spare? rolls) (take-next 2 rolls)
:else (empty rolls)))
(defn- score-current-frame [rolls n]
(if (> n 10)
0
(+ (points (first-frame rolls))
(points (bonus-rolls rolls)))))
(defn- score-frames [rolls n]
(if (empty? rolls)
0
(+ (score-current-frame rolls n)
(score-frames (rest-frames rolls) (inc n)))))
(defn score [rolls]
(score-frames rolls 1))

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

I commited the code after every passing test, every refactor and every major REPL spike.

If you want to follow the process, you can find the commits step by step here.

You can find the resulting code in GitHub.

Friday, November 7, 2014

Kata: Unconditional rock, paper, scissors in Ruby

Yesterday Álvaro García (@alvarobiz) and I paired working on a possible solution to the Unconditional rock, paper, scissors kata that I facilitated in the recent SCBCN14 event.

This is the last version of the tests so far:

require File.join(File.dirname(__FILE__), "rock_paper_scissors")
require 'test/unit'
class TestRockPaperScissors < Test::Unit::TestCase
def setup
@game = Game.new
@paper = Paper.new
@rock = Rock.new
@scissors = Scissors.new
end
def test_paper_against_paper
assert_that(
GameHand.with(@paper).against(@paper)
.results_in("Two Papers, no one wins")
)
end
def test_paper_against_rock
assert_that(
GameHand.with(@paper).against(@rock)
.results_in("Paper wins against Rock")
)
end
def test_paper_against_scissors
assert_that(
GameHand.with(@paper).against(@scissors)
.results_in("Scissors wins against Paper")
)
end
def test_scissors_against_paper
assert_that(
GameHand.with(@scissors).against(@paper)
.results_in("Scissors wins against Paper")
)
end
def test_scissors_against_rock
assert_that(
GameHand.with(@scissors).against(@rock)
.results_in("Rock wins against Scissors")
)
end
def test_scissors_against_scissors
assert_that(
GameHand.with(@scissors).against(@scissors)
.results_in("Two Scissors, no one wins")
)
end
def test_rock_against_paper
assert_that(
GameHand.with(@rock).against(@paper)
.results_in("Paper wins against Rock")
)
end
def test_rock_against_rock
assert_that(
GameHand.with(@rock).against(@rock)
.results_in("Two Rocks, no one wins")
)
end
def test_rock_against_scissors
assert_that(
GameHand.with(@rock).against(@scissors)
.results_in("Rock wins against Scissors")
)
end
def assert_that(predicate_result)
assert(predicate_result)
end
end
class GameHand
def initialize(gesture)
@gesture1 = gesture
end
class << self
def with(gesture)
new(gesture)
end
end
def against(gesture)
@gesture2 = gesture
self
end
def results_in(expected)
result = Game.new().hand(@gesture1, @gesture2)
result.to_s == expected
end
end

And this is the last version of the code:

class Game
def hand(gesture1, gesture2)
gesture1.play_against(gesture2)
end
end
class Gesture
def win_against(other)
Victory.new(self, other)
end
def tie_with(other)
Tie.new(other)
end
end
class Paper < Gesture
def play_against(other)
other.play_against_paper(self)
end
def play_against_paper(paper)
tie_with(paper)
end
def play_against_scissors(scissors)
scissors.play_against_paper(self)
end
def play_against_rock(rock)
win_against(rock)
end
def to_s
"Paper"
end
def to_plural_s
to_s + "s"
end
end
class Rock < Gesture
def play_against(other)
other.play_against_rock(self)
end
def play_against_paper(paper)
paper.play_against_rock(self)
end
def play_against_scissors(scissors)
win_against(scissors)
end
def play_against_rock(rock)
tie_with(rock)
end
def to_s
"Rock"
end
def to_plural_s
to_s + "s"
end
end
class Scissors < Gesture
def play_against(other)
other.play_against_scissors(self)
end
def play_against_paper(paper)
win_against(paper)
end
def play_against_scissors(scissors)
tie_with(scissors)
end
def play_against_rock(rock)
rock.play_against_scissors(self)
end
def to_s
"Scissors"
end
def to_plural_s
to_s
end
end
class Victory
def initialize(winner, loser)
@winner = winner
@loser = loser
end
def to_s
@winner.to_s + " wins against " + @loser.to_s
end
end
class Tie
def initialize(gesture)
@gesture = gesture
end
def to_s
"Two " + @gesture.to_plural_s + ", no one wins"
end
end

We managed to write the code without having to use conditionals in any moment.

You can follow the process if you like since we did commits after every passing test and every refactoring.

You can check the code in this GitHub repository.

As usual it was a pleasure to do pair programming with Álvaro.

Thursday, November 6, 2014

Euler Project: Problem 1 in Haskell

This is my solution in Haskell to the first problem:

sum [ x | x <- [1..1000], x `rem` 5 == 0 && x `rem` 3 == 0 ]
view raw euler1.hs hosted with ❤ by GitHub
I used a list comprehension.

Another way using also a lambda to create a helper:

multiple_of n = \ x -> (x `rem` n) == 0
sum [y | y <- [1..1000], multiple_of 3 y && multiple_of 5 y]
view raw euler1b.hs hosted with ❤ by GitHub


Bonus: Two ways to do the same in Clojure:

(def sum (partial reduce +))
(defn multiple-of [n]
(fn [x] (zero? (mod x n))))
(def multiple-of-3? (multiple-of 3))
(def multiple-of-5? (multiple-of 5))
(sum
(for [x (range 1001)
:when (and (multiple-of-3? x)
(multiple-of-5? x))]
x))
(sum
(filter #(and (multiple-of-3? %)
(multiple-of-5? %))
(range 1 1001)))
view raw euler1.clj hosted with ❤ by GitHub