Tuesday, December 30, 2014

Books I read (2014)

January
- Pan, educación, libertad (Ψωμί, παιδεία, ελευθερία), Petros Márkaris
- NW London, Zadie Smith
- 101 cuentos clásicos de la China, Chang Shiru, Ramiro A. Calle
- Mr. Neighborly's Humble Little Ruby Book, Jeremy McAnally

February
- Blankets, Craig Thompson

March
- Practical Object-Oriented Design in Ruby, Sandi Metz
- Modern C++ Programming with Test-Driven Development, Jeff Langr

April
- Learning PHP, MySQL & JavaScript, Robin Nixon
- Measuring the world, Daniel Kehlmann

May
- El hombre que plantaba árboles, (L'homme qui plantait des arbres), Jean Giono
- Extreme Programming Explained, Embrace Change, Kent Beck
- Adiós, Chunky Rice, (Good-bye, Chunky Rice), Craig Thompson

June
- Eloquent Ruby, Russ Olsen
- Implementing Domain-Driven Design, Vaughn Vernon

July
- JavaScript Allongé, Reginald Braithwaite
- JavaScript: The Good Parts, Douglas Crockford

August
- Programming Clojure, (2nd edition), Stuart Halloway and Aaron Bedra
- Introduction to Computing, Explorations in Language, Logic and Machines, David Evans
- JavaScript Allongé, Reginald Braithwaite (2nd time)

September
- Functional JavaScript, Introducing Functional Programming with Underscore.js, M. Fogus
- Functional Thinking, Paradigm Over Syntax, Neal Ford
- Understanding the Four Rules of Simple Design, Corey Haines
- A People's History of London, Lindsey German and John Rees

November
- Software Craftsmanship: Professionalism, Pragmatism, Pride, Sandro Mancuso

December
- Me llamo Rojo (Benim Adım Kırmızı), Orhan Pamuk (2nd time)
- Clojure Programming, Chas Emerick, Brian Carper and Christophe Grand
- The Little Schemer, Daniel P. Friedman and Matthias Felleisen

Tuesday, December 16, 2014

Clojure Developers Barcelona: Talk about Clojure destructuring

Today I gave a talk about destructuring in Clojure for some of the Clojure study group members.

This is the "clean version" of the code I wrote on the fly on Lightable to explain destructuring:

;;
;; Destructuring
;;
;; Destructuring is a concise syntax for declaratively pulling apart collections and
;; binding values contained therein as named locals within a let form.
;; (Clojure Programming, Chas Emerick, Brian Carper, Christophe Grand)
;; Since it's a facility provided by let, it can be used
;; in any expression that implicitly uses let (like fn, defn, loop, etc).
;; It comes in two flavours:
;;
;; 1. Sequential Destructuring
;;
(def v [51 25 3 [4 5] 6 7 [88 [99 11] 33]])
;; 1.1 Simple examples
;; [51 25 3 [4 5] 6 7 [88 [99 11] 33]]
;; [x y ]
(let [[x y] v]
(vector x y))
;; [51 25 3 [4 5] 6 7 [88 [99 11] 33]]
;; [x _ y ]
(let [[x _ y] v]
(vector x y))
;; [51 25 3 [4 5] 6 7 [88 [99 11] 33]]
;; [x _ _ v1 ]
(let [[x _ _ v1] v]
(vector x v1))
;; _ does not have a special semantics.
;; It is just a valid name for a var
;; that is used as a convention meaning
;; that you are not interested in its value.
(let [[x _ _ v1] v]
_)
;; 1.2 Nested examples
;; [51 25 3 [4 5] 6 7 [88 [99 11] 33]]
;; [x _ _ [_ y] ]
(let [[x _ _ [_ y]] v]
(+ x y))
;; [51 25 3 [4 5] 6 7 [88 [99 11] 33]]
;; [_ _ _ [_ _] _ _ [_ [_ x] y]]
(let [[_ _ _ _ _ _ [_ [_ x] y]] v]
(+ x y))
;; [51 25 3 [4 5 8 9 3] 6 7 [88 [99 11] 33]]
;; [_ _ _ [_ z] _ _ [_ [_ x] y]]
(let [[_ _ _ [_ z] _ _ [_ [_ x] y]] v]
(vector z x y))
;; 1.3 Rest of values: &
(def values1 ["hi" "there" "koko" "moko"])
;; ["hi" "there" "koko" "moko"]
;; [_ & the-rest ]
(let [[_ & the-rest] values1]
the-rest)
;; Notice that how the-rest is a sequence, regardless the original collection being a vector
;; ["hi" "there" "koko" "moko"]
;; [_ _ & the-rest ]
(let [[_ _ & the-rest] values1]
the-rest)
;; ["hi" "there" "koko" "moko"]
;; [& the-rest ]
(let [[& the-rest] values1]
the-rest)
(rest [])
(next [])
;; & has the same semantics as next (like rest except that (= nil (next '())))
(let [[_ _ _ _ & the-rest] values1]
the-rest)
; This is how you can have varargs in functions
(defn +-mine [& args]
(apply + args))
(+-mine)
(defn show-separated-by-commas [& args]
(clojure.string/join ", " args))
(show-separated-by-commas 1 5 "hola")
;; 1.4 Retaining the original collection: :as
(def coll [3 5 8 9])
(let [[x y & the-rest :as orig-coll] coll]
(show-separated-by-commas x y the-rest orig-coll))
;; 1.5 Sequencial destructuring works with:
;; 1.5.a. Clojure lists, vectors and seqs
;; Lists
(let [[a _ c] '(1 2 3)]
(show-separated-by-commas a c))
;; Seqs
(let [[a _ c] (filter odd? '(1 2 3 4 5 6 7))]
(show-separated-by-commas a c))
;; 1.5.b. Any collection that implements java.util.List
(def an-array-list
(doto (java.util.ArrayList.) (.add 1) (.add 2) (.add 3)))
(let [[a _ c] an-array-list]
(show-separated-by-commas a c))
;; 1.5.c. Java arrays
(def an-array (int-array [1 2 3]))
(let [[a _ c d] an-array]
(vector a c d))
;; 1.5.d. Strings, which are destructured into characters
(let [[& characters] "koko"]
characters)
(seq "koko")
;;
;; 2. Map Destructuring
;;
(def a-map {:a 1
:b 3
:c [7 8 9]
:d {:e "koko" :f "moko"}
"foo" 88
'g 99
9 "nine"
[1 3] "hola"})
;; 2.1 Simple examples
(let [{x :a y :b} a-map]
(- x y))
;; Order is not important
(let [{y :b x :a} a-map]
(- x y))
(:a a-map)
(:b a-map)
(get a-map :a)
(get a-map :b)
(let [{y "foo"} a-map]
y)
;("foo" a-map)
(get a-map "foo")
(let [{y 'g} a-map]
y)
(get a-map 'g)
(let [{y 9} a-map]
y)
(get a-map 9)
(let [{x [1 3]} a-map]
x)
;; 2.2 Nested examples
;; From a previous example:
;; (def a-map {:a 1
;; :b 3
;; :c [7 8 9]
;; :d {:e "koko" :f "moko"}
;; "foo" 88
;; 'g 99
;; 9 "nine"
;; [1 3] "hola"})
;; 2.2.a Maps nested inside maps
(let [{inner-map :d} a-map]
inner-map)
(let [{{word :f} :d} a-map]
word)
;; Equivalent to using let with successive bindings:
(let [{inner-map :d} a-map
{word :f} inner-map]
word)
;; Or to using get-in:
(get-in a-map [:d :f])
(let [{x :a {word :f} :d other-num :b} a-map]
(show-separated-by-commas x word other-num))
;; 2.2.b Vectors nested inside maps
(def map-with-vector {:a "koko" :b ["hello" "two"]})
(let [{[_ number] :b} map-with-vector]
number)
(let [[_ {x :b}] [1 {:a "x" :b 7}]]
x)
;; 2.3 Map destructuring works with anything that get function works with:
;; 2.3.a Clojure hash-maps, array-maps and records
; array-maps
(def an-array-map (array-map :a 10 :b 20))
(let [{a :a b :b} an-array-map]
(show-separated-by-commas a b))
; Records
(defrecord Point [x y])
(def a-point (Point. 1 2))
a-point
(let [{x :x y :y} a-point]
(show-separated-by-commas x y))
;; 2.3.b Any collection that implements java.util.Map
(def a-java-hash-map
(doto (java.util.HashMap.)
(.put "a" "Hola")
(.put "b" "koko")
(.put "c" "moko")))
(let [{x "a" y "c" } a-java-hash-map]
(show-separated-by-commas x y))
;; 2.3.a Any value that is supported by the get function using indices as keys:
;; Clojure vectors, Strings and arrays
;; Vectors
;; From a previous example -> (def v [51 25 3 [4 5] 6 7 [88 [99 11] 33]])
;; [51 25 3 [4 5] 6 7 [88 [99 11] 33]]
;; [_ _ _ [_ _] _ _ [_ [_ x] y]]
(let [[_ _ _ _ _ _ [_ [_ x] y]] v]
(show-separated-by-commas x y))
; It can be also done with map-destructuring and the indexes:
(let [{{{x 1} 1 y 2} 6} v]
(show-separated-by-commas x y))
(let [{[_ [_ x] y] 6} v]
(show-separated-by-commas x y))
; Or using get-in
(get-in v [6 1 1])
(get-in v [6 2])
; Another example:
; From a previous example -> (def map-with-vector {:a "koko" :b ["hello" "two"]})
(let [{[_ num] :b} map-with-vector]
num)
(get-in map-with-vector [:b 1])
(let [{{num 1} :b} map-with-vector]
num)
;; Arrays
;; From a previous example -> (def an-array (int-array [1 2 3]))
(let [[a _ c] an-array]
(show-separated-by-commas a c))
(let [{a 0 c 2} an-array]
(show-separated-by-commas a c))
;; Strings
(let [[a _ c] "koko"]
(show-separated-by-commas a c))
(let [{a 0 c 2} "koko"]
(show-separated-by-commas a c))
;; 2.4 Retaining the original collection: :as
; From a previous example -> (def map-with-vector {:a "koko" :b ["hello" "two"]})
(let [{a :a :as orig-map} map-with-vector]
(show-separated-by-commas a orig-map))
;; 2.5 Default values: :or
; From a previous example -> (def map-with-vector {:a "koko" :b ["hello" "two"]})
(let [{k :unknown a :a} map-with-vector]
(vector a k))
(let [{k :unknown a :a
:or {k "default-value" a "not-going-to-appear!"}} map-with-vector]
(show-separated-by-commas a k))
;; You can get a similar behaviour using:
(let [{k :unknown} map-with-vector
k (or k "default-value")]
k)
;; But this last code fails to distinguish false from nil
;; So that in this wicked example k gets incorrectly bound -> k should be false!!
(let [{k :unknown} {:unknown false}
k (or k "wrong-value!!!")]
k)
;; It works if you use :or (k is bound to false)
(let [{k :unknown
:or {k "wrong-value!!!"}} {:unknown false}]
k)
;; 2.6 Binding values to their keys names: :keys, :syms, :strs
;; This is very repetitive:
(let [{x :x y :y} {:x 1 :y 2}]
(show-separated-by-commas x y))
;; You can write it in a more convenient way:
(let [{:keys [x y]} {:x 1 :y 2}]
(show-separated-by-commas x y))
(get '(:x 1 :y 2) :x)
(let [{:keys [x y]} '(:x 1 :y 2)]
(show-separated-by-commas x y))
(let [{x 0 y 1} [1 2]]
(show-separated-by-commas x y))
(let [{:strs [x y]} {"x" 1 "y" 2}]
(show-separated-by-commas x y))
(let [{:syms [x y]} {'x 1 'y 2}]
(show-separated-by-commas x y))
;; Notice how the binding names have to be equal to the keys
;; It also works for records
;; From a previous example -> (defrecord Point [x y])
(let [{x :x y :y} (Point. 1 2)]
(show-separated-by-commas x y))
(let [{:keys [x y]} (Point. 1 2)]
(show-separated-by-commas x y))
;; And for maps using strings as keys
(let [{:keys [x y]} {:x 1 "y" 2}]
(vector x y))
(let [{:keys [x] :strs [y]} {:x 1 "y" 2}]
(vector x y))
(let [{:keys [x] pepito "y"} {:x 1 "y" 2}]
(vector x pepito))
;; And for maps using strings as keys
(let [{x "x" y "y"} {"x" 1 "y" 2}]
(show-separated-by-commas x y))
(let [{:strs [x y]} {"x" 1 "y" 2}]
(show-separated-by-commas x y))
;; And for maps using symbols as keys
(let [{x 'x y 'y} {'x 1 'y 2}]
(show-separated-by-commas x y))
(let [{:syms [x y]} {'x 1 'y 2}]
(show-separated-by-commas x y))
;; 2.7 Rest of key-value pairs: &
(def user-info ["Koko" 47 :address "Sesamo Street 26" :color "blue"])
(let [[name age & {:keys [address color]}] user-info]
(show-separated-by-commas name age address color))
(defn f [ [name age & {:keys [address color]}] ]
(show-separated-by-commas name age address color))
(f user-info)
(defn make-tamagotchi [& {:keys [fulness tiredness]
:or {fulness 0 tiredness 0}}]
{:fulness fulness
:tiredness tiredness})
(make-tamagotchi)
(make-tamagotchi :tiredness 4)
(make-tamagotchi :fulness 4)
(make-tamagotchi :fulness 4 :tiredness 8)
(let [{:keys [fulness tiredness]
:or {fulness 0 tiredness 0}} '(:fulness 4)]
(vector fulness tiredness))
;; This can be used to have function with keyword arguments.
;; To learn more:
;; Clojure Programming, Practical Lisp for the Java World. Chas Emerick, Brian Carper, Christophe Grand
;;
;; The complete guide to Clojure destructuring -> http://blog.brunobonacci.com/2014/11/16/clojure-complete-guide-to-destructuring/
;;
;; Pattern Matching vs. Destructuring… to the death! -> http://blog.fogus.me/2011/01/12/pattern-matching-vs-destructuring-to-the-death/
;;
;; Clojure: Destructuring -> http://blog.jayfields.com/2010/07/clojure-destructuring.html
;;
;; Clojure’s Mini-languages -> http://blog.fogus.me/2010/03/23/clojures-mini-languages/
;;
;; Destructuring on ClojureBridge -> https://clojurebridge.github.io/community-docs/docs/clojure/destructuring/
;;
;; Clojure Binding Forms (Destructuring) -> http://clojure.org/special_forms#binding-forms
;;
;; Clojure Destructuring Tutorial and Cheat Sheet -> https://gist.github.com/john2x/e1dca953548bfdfb9844
;;
;; Beautiful Clojure – Destructuring data -> https://www.laliluna.de/articles/2013/010/29/clojure-destructuring.html
;
;; Grover -> http://en.wikipedia.org/wiki/Grover
I had a great time and learned a lot preparing the talk.

I hope this small study group will be help to get the Clojure Developers Barcelona Group up and running again soon.

Thanks all for coming.

Update

I repeated this talk yesterday.

I updated the code in the gist shown above.

Monday, December 15, 2014

Kata: Roman Numerals in Clojure (2nd time)

I've just redone the Roman Numerals kata in Clojure following the advices about test-driving algorithms that Sandro Mancuso gave during his Crafted Code course:
  • Grow an algorithm bit by bit
  • Delay treating exceptions (in this case, because they are more complex)
  • Intentionally cause duplication
  • Focus on simple structures first
The resulting code to convert decimals up to 3999 to roman numerals is much simpler than the code I got the first time I did the kata.

I think the reason is that the first time I started refactoring too soon and that hid the duplication pattern that would have lead me to this simpler solution.

As in the previous version, I extended the kata to also convert decimal numbers over 3999.

This is the resulting code:

(ns roman-numerals-converter.core)
(declare
to-roman-from-up-to-3999
to-roman-from-over-3999)
(defn to-roman [decimal]
(if (<= decimal 3999)
(to-roman-from-up-to-3999 decimal)
(to-roman-from-over-3999 decimal)))
;;
;; Decimal numbers up to 3999
;;
(def ^:private
decs-to-roms
[{:dec 1000 :rom "M"}
{:dec 900 :rom "CM"}
{:dec 500 :rom "D"}
{:dec 400 :rom "CD"}
{:dec 100 :rom "C"}
{:dec 90 :rom "XC"}
{:dec 50 :rom "L"}
{:dec 40 :rom "XL"}
{:dec 10 :rom "X"}
{:dec 9 :rom "IX"}
{:dec 5 :rom "V"}
{:dec 4 :rom "IV"}
{:dec 1 :rom "I"}])
(defn- to-roman-from-up-to-3999 [decimal]
(loop [acc ""
decimal decimal
decs-to-roms decs-to-roms]
(if (zero? decimal)
acc
(let [dec-to-rom (first decs-to-roms)]
(if (>= decimal (:dec dec-to-rom))
(recur (str acc (:rom dec-to-rom))
(- decimal (:dec dec-to-rom))
decs-to-roms)
(recur acc
decimal
(rest decs-to-roms)))))))
;;
;; Decimal numbers over 3999
;;
(def ^:private join-str
(partial apply str))
(defn- times-thousand-bar [multiple]
(concat (repeat (count multiple) "-") "\n"))
(defn- times-thousand-bars [multiple times]
(join-str
(flatten
(repeat times
(times-thousand-bar multiple)))))
(defn- multiple [decimal]
(loop [times 0 num decimal]
(if (<= num 3999)
[(to-roman-from-up-to-3999 num) times]
(recur (inc times) (quot num 1000)))))
(defn- to-roman-from-over-3999 [decimal]
(let [[multiple times] (multiple decimal)]
(str (times-thousand-bars multiple times)
multiple
(to-roman-from-up-to-3999
(rem decimal (* times 1000))))))
view raw to-romans.clj hosted with ❤ by GitHub
and these are the tests using Midje:

(ns roman-numerals-converter.core-test
(:use midje.sweet)
(:use [roman-numerals-converter.core]))
(facts
"about Roman numerals converter"
(fact
"converts decimal numbers up to 3999 into roman numbers"
(to-roman 1) => "I"
(to-roman 2) => "II"
(to-roman 3) => "III"
(to-roman 4) => "IV"
(to-roman 5) => "V"
(to-roman 6) => "VI"
(to-roman 8) => "VIII"
(to-roman 9) => "IX"
(to-roman 10) => "X"
(to-roman 11) => "XI"
(to-roman 18) => "XVIII"
(to-roman 25) => "XXV"
(to-roman 33) => "XXXIII"
(to-roman 34) => "XXXIV"
(to-roman 39) => "XXXIX"
(to-roman 40) => "XL"
(to-roman 50) => "L"
(to-roman 90) => "XC"
(to-roman 100) => "C"
(to-roman 400) => "CD"
(to-roman 500) => "D"
(to-roman 900) => "CM"
(to-roman 1000) => "M"
(to-roman 2499) => "MMCDXCIX"
(to-roman 3949) => "MMMCMXLIX"
(to-roman 3999) => "MMMCMXCIX")
(fact
"converts decimal numbers over 3999 into roman numbers"
(to-roman 4000) => "--\nIV"
(to-roman 4001) => "--\nIVI"
(to-roman 30000) => "---\nXXX"
(to-roman 3999005) => "---------\nMMMCMXCIXV"
(to-roman 4000000) => "--\n--\nIV"
(to-roman 4000025) => "--\n--\nIVXXV"))
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.

This time it was a bit easier to derive the algorithm only using strict TDD.

You can find all the code in this repository in GitHub.

Friday, December 12, 2014

Kata: Studious Student in Clojure

Last week Leo Antoli facilitated a kata for Software Craftsmanship Barcelona.

We had to solve the Studious Student exercise.

Leo wanted us to experiment how useful testing is in an exercise like this one, so we divided the group in some pairs using TDD, some pairs testing after writing the code and some pairs not testing at all.

The exercise is a bit tricky as pairs that were not testing discovered at the end, whereas the ones doing TDD or testing after coding discovered early during the process.

After an iteration of one hour, we had a very interesting debate about automatic testing.

This is my solution of the exercise in Clojure:

(ns studious-student.core)
(def ^:private join (partial apply str))
(defn lexic-shortest-concat [words-list]
(join (sort #(compare (str %1 %2)
(str %2 %1))
words-list)))
(defn- file-lines [file]
(rest (clojure.string/split-lines (slurp file))))
(defn- line-words [line]
(rest (clojure.string/split line #" ")))
(defn- extract-words-lists [file]
(map line-words (file-lines file)))
(defn lexic-shortest-concat-lines [file]
(->>
file
extract-words-lists
(map lexic-shortest-concat)))
(defn studious-student [file-in file-out]
(spit file-out
(clojure.string/join
"\n"
(lexic-shortest-concat-lines file-in))))
and these are the tests using Midje:

(ns studious-student.core-test
(:use midje.sweet)
(:use [studious-student.core]))
(facts
"about Studious Student exercise"
(facts
"about concatenating the words in a list of words
to generate the lexicographically lowest possible string"
(fact
"it works for an empty words list"
(lexic-shortest-concat []) => "")
(fact
"it works for trivial non-empty words lists"
(lexic-shortest-concat
["facebook" "hacker" "cup" "for" "studious" "students"])
=> "cupfacebookforhackerstudentsstudious"
(lexic-shortest-concat
["k" "duz" "q" "rc" "lvraw"]) => "duzklvrawqrc"
(lexic-shortest-concat
["mybea" "zdr" "yubx" "xe" "dyroiy"]) => "dyroiymybeaxeyubxzdr"
(lexic-shortest-concat
["uiuy" "hopji" "li" "j" "dcyi"])=> "dcyihopjijliuiuy")
(fact
"it also works for non-trivial word lists"
(lexic-shortest-concat
["jibw" "ji" "jp" "bw" "jibw"]) => "bwjibwjibwjijp"))
(facts
"about concatenating the words in each line of a file
to generate the lexicographically lowest possible strings"
(fact
"it reads a file and concatenates the words in each line
to generate the lexicographically lowest possible strings"
(lexic-shortest-concat-lines
"./test/studious_student/studious_student.in")
=> '("cupfacebookforhackerstudentsstudious"
"duzklvrawqrc"
"dyroiymybeaxeyubxzdr"
"bwjibwjibwjijp"
"dcyihopjijliuiuy"))
(let [out "./test/studious_student/s.out"]
(fact
"it writes an output files with the lexicographically lowest possible strings
of the words in each line of a given file"
(do (studious-student "./test/studious_student/studious_student.in" out)
(clojure.string/split-lines (slurp out)))
=> '("cupfacebookforhackerstudentsstudious"
"duzklvrawqrc"
"dyroiymybeaxeyubxzdr"
"bwjibwjibwjijp"
"dcyihopjijliuiuy")
(against-background (after :facts (clojure.java.io/delete-file out))))
(fact
"it also works for the long given input file"
(do (studious-student "./test/studious_student/studious_student_long.in" out)
(slurp out) => (slurp "./test/studious_student/studious_student_long.out"))
(against-background (after :facts (clojure.java.io/delete-file out)))))))

You can see all the code in this GitHub repository.

I'd like to thank Leo for being so kind and sharing his knowledge with us.

Reading GOOS (IX)

These are the links mentioned in last two weeks conversations about the 12th and 13th chapters:
  1. Posts and Papers
  2. Talks

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

Saturday, October 18, 2014

Introduction to TDD with Barcelona JUG and SCBCN

Yesterday Álvaro (@alvarobiz) and I facilitated the Fractions Arithmetic kata. It was an activity organized by the Barcelona Java Users Group and the Barcelona Software Craftsmanship Community. Thanks to Ignacio Cougil and Jonathan Vila for having the idea and making this event possible.

Since the kata was meant to be an introducction to TDD, we had first a short talk explaining a bit what TDD is about.

The talk took longer than I expected because we discussed about topics, such as, TDD, object-oriented design or refactoring. Thanks for the questions and comments, I think they lead to interesting discussions.

Then we started the kata working in pairs.

In the Fractions Arithmetic kata you have to develop the arithmetic of rational numbers but, in this occasion, we limited ourselves to just developing the addition of rational numbers. We modeled the rational numbers as value objects and the fractions had to be reduced.

Álvaro and I went from pair to pair commenting with them their approaches, helping when some pair was stuck, talking about some possible refactorings, etc.

I enjoyed the experience a lot and I hope all participants took something useful home.

We talked about some books and talks that might be interesting to learn more about TDD.

These are the links:
Thanks to all for coming. We'll see each other in the next one.

Sunday, October 5, 2014

Exercism: "Atbash Cipher in Clojure"

I solved the Atbash Cipher problem in Clojure.

This is my solution:

(ns atbash-cipher
(:require [clojure.string :as string]))
(def ^:private latin-alphabet "abcdefghijklmnopqrstuvwxyz")
(def ^:private cypher-by-letter
(zipmap latin-alphabet
(reverse latin-alphabet)))
(defn- encode-char [c]
(if (Character/isDigit c)
c
(get cypher-by-letter c)))
(defn- encode-chunk [chunk]
(apply
str
(map encode-char
(string/lower-case chunk))))
(defn- extract-chunks [text]
(map (partial apply str)
(partition 5 5 nil text)))
(defn- remove-punctuation [text]
(filter
#(or (Character/isDigit %)
(Character/isLetter %))
text))
(def ^:private encode-chunks
(partial map encode-chunk))
(defn encode [text]
(string/join
" "
(encode-chunks
(extract-chunks
(remove-punctuation text)))))

And this is the same but using the ->> macro inside the encode function:

(ns atbash-cipher
(:require [clojure.string :as string]))
(def ^:private latin-alphabet "abcdefghijklmnopqrstuvwxyz")
(def ^:private cypher-by-letter
(zipmap latin-alphabet
(reverse latin-alphabet)))
(defn- encode-char [c]
(if (Character/isDigit c)
c
(get cypher-by-letter c)))
(defn- encode-chunk [chunk]
(apply
str
(map encode-char
(string/lower-case chunk))))
(defn- extract-chunks [text]
(map (partial apply str)
(partition 5 5 nil text)))
(defn- remove-punctuation [text]
(filter
#(or (Character/isDigit %)
(Character/isLetter %))
text))
(def ^:private encode-chunks
(partial map encode-chunk))
(defn encode [text]
(->>
text
(remove-punctuation)
(extract-chunks)
(encode-chunks)
(string/join " ")))

For this exercise I had to learn how the padding parameter of the partition function works.

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

Exercism: "Allergies in Clojure"

I solved the Allergies problem in Clojure.

This is my first iteration of the solution:

(ns allergies)
(declare allergies-by-score several-allergies, search-subset, searc-helper)
(defn list [score]
(if-let [one-match (get allergies-by-score score)]
[one-match]
(several-allergies score)))
(defn allergic_to? [score stuff]
(some #{stuff} (list score)))
(def ^:private allergies-by-score
{ 1 "eggs"
2 "peanuts"
4 "shellfish"
8 "strawberries"
16 "tomatoes"
32 "chocolate"
64 "pollen"
128 "cats"})
(defn- several-allergies [score]
(let [possible-allergies-ids (filter #(< % score) (keys allergies-by-score))]
(if (empty? possible-allergies-ids)
[]
(map #(get allergies-by-score %)
(search-subset
score
possible-allergies-ids)))))
(defn- searc-helper [score num-set nums]
(if (> score (reduce + (keys allergies-by-score)))
(let [max-num (apply max nums)]
(searc-helper (- score max-num)
(conj num-set max-num)
nums))
(if (empty? nums)
false
(let [current-num (first nums)
sum (+ current-num (reduce + num-set))
num-set-with-current-num (conj num-set current-num)]
(cond (= score sum) num-set-with-current-num
(> score sum) (if-let [res (searc-helper score num-set-with-current-num (rest nums))]
res
(searc-helper score num-set (rest nums)))
(< score sum) (searc-helper score num-set (rest nums)))))))
(defn- search-subset [score nums]
(searc-helper score #{} nums))
view raw allergies1.clj hosted with ❤ by GitHub

And this is the second one which is tail-recursive:

(ns allergies)
(def ^:private allergies-by-score
(sorted-map 1 "eggs"
2 "peanuts"
4 "shellfish"
8 "strawberries"
16 "tomatoes"
32 "chocolate"
64 "pollen"
128 "cats"))
(defn- sum-subset [sum nums]
(loop [s sum
i (dec (count nums))
acc-set #{}]
(if (or (zero? s) (neg? i))
acc-set
(let [num (nth nums i)]
(if (>= s num)
(recur (- s num) i (conj acc-set num))
(recur s (dec i) acc-set))))))
(defn list [score]
(let [possible-allergies-ids (filter #(<= % score)
(keys allergies-by-score))]
(vec (map #(get allergies-by-score %)
(sum-subset score possible-allergies-ids)))))
(defn allergic_to? [score stuff]
(some #{stuff} (list score)))
view raw allergies2.clj hosted with ❤ by GitHub

This problem was very interesting. To solve it you need to find a solution for a problem called subset sum. Both iterations use backtracking to find the subset of numbers that sum to the allergies score.

I had used this backtracking algorithm once before to solve the N-Queens problem in Racket for the Introduction to Systematic Program Design 1 Coursera course.

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

Saturday, October 4, 2014

Saturday, September 13, 2014

Refactoring my generalized fizzbuzz to use only applicative higher-order functions

I refactored my my previous version of generalized FizzBuzz, so that, it doesn't use neither for loops nor recursion. Now it only uses: reduce and map.

This is the new code:

var makeSubstitute = function(substitutionDescriptions) {
var substituteNumber = (function() {
var substitutionFns = substitutionDescriptions.map(
function(desc) {
return function(number) {
return desc.pred(number) ? desc.replacement : "";
};
}
);
return function(number) {
var res = substitutionFns.reduce(
function(acc, substite) {
return acc + substite(number)
},
""
);
return res !== "" ? res : String(number);
};
}());
return function(numbers) {
return numbers.map(substituteNumber).join(" ");
};
};

The tests are exactly the same as in the previous version:

describe("FizzBuzz", function () {
var fizzBuzzSubstitute;
beforeEach(function () {
fizzBuzzSubstitute = makeSubstitute([
{ pred: function(number) {return number % 3 == 0;},
replacement: "Fizz"},
{ pred: function(number) {return number % 5 == 0;},
replacement: "Buzz"}
]);
});
it("works for an empty array", function () {
expect(fizzBuzzSubstitute([])).toBe("");
});
it("returns same number for array with number not multiple of 3 or 5", function () {
expect(fizzBuzzSubstitute([1])).toBe("1");
});
it("returns Fizz for an array with a multiple of 3", function () {
expect(fizzBuzzSubstitute([3])).toBe("Fizz");
expect(fizzBuzzSubstitute([9])).toBe("Fizz");
});
it("returns Buzz for an array with a multiple of 5", function () {
expect(fizzBuzzSubstitute([5])).toBe("Buzz");
expect(fizzBuzzSubstitute([25])).toBe("Buzz");
});
it("returns FizzBuzz for an array with a multiple of both 3 and 5", function () {
expect(fizzBuzzSubstitute([15])).toBe("FizzBuzz");
});
it("also works with arrays with more than one element", function () {
expect(fizzBuzzSubstitute([1, 2, 15])).toBe("1 2 FizzBuzz");
});
});
describe("FizzKozz", function () {
var fizzKozzSubstitute = makeSubstitute([
{ pred: function(number) {return number % 3 == 0;},
replacement: "Fizz"},
{ pred: function(number) {return number % 2 == 0;},
replacement: "Kozz"}
]);
it("also works with different substitution rules", function () {
expect(
fizzKozzSubstitute([1, 2, 4, 6, 15])).toBe("1 Kozz Kozz FizzKozz Fizz");
});
});
describe("FizzOddSeven", function () {
var fizzOddSevenSubstitute = makeSubstitute([
{ pred: function(number) {return number % 3 == 0;},
replacement: "Fizz"},
{ pred: function(number) {return number % 2 == 1;},
replacement: "Odd"},
{ pred: function(number) {return number == 7;},
replacement: "Seven"}
]);
it("works with rules using any predicate on a number", function () {
expect(
fizzOddSevenSubstitute(
[1, 2, 4, 6, 15, 7])).toBe("Odd 2 4 Fizz FizzOdd OddSeven");
});
});

Thursday, September 4, 2014

Euler Project: Problem 10 in Clojure

This is my solution in Clojure to the 10th problem from Euler project:

(defn sieve [[nums primes]]
(let [[prime & more] nums]
(vector (remove #(zero? (rem % prime)) nums)
(cons prime primes))))
(defn primes-below [n]
(let [sqrt-n (Math/sqrt n)]
(apply
concat
(first
(drop-while
#(< (ffirst %) sqrt-n)
(iterate sieve [(range 2 (inc n)) nil]))))))
(defn sum-primes-below [n]
(reduce + (primes-below n)))
(sum-primes-below 10) ; 17
(sum-primes-below 100) ; 1060
(sum-primes-below 1000) ; 76127
(sum-primes-below 10000) ; 5736396
(sum-primes-below 100000) ; 454396537
(sum-primes-below 2000000) ; 142913828922
view raw euler-10.clj hosted with ❤ by GitHub

Euler Project: Problem 9 in Clojure

This is my solution in Clojure to the ninth problem from Euler project:

(defn square [x]
(* x x))
(defn pythagorean-triplet? [a b c]
(and (< a b c)
(= (square c) (+ (square a) (square b)))))
(def triplet
(let [nums (range 500)]
(for [a nums
b nums
c nums
:when (and (= 1000 (+ a b c))
(pythagorean-triplet? a b c))]
[a b c])))
triplet ; [200 375 425]
(reduce * triplet) ; 31875000
view raw euler-9.clj hosted with ❤ by GitHub

Wednesday, September 3, 2014

Euler Project: Problem 8 in Clojure

This is my solution in Clojure to the eighth problem from Euler project:

(def huge-num 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450)
(defn parse-int [s]
(Integer. (re-find #"\d+" s )))
(defn- digits-to-numbers [digits]
(map (comp parse-int str) digits))
(defn greatest-product-and-n-digits [huge-num n]
(let
[prod-n-digits-pairs (map #(let [numbers (digits-to-numbers %)]
[(reduce * numbers) numbers])
(partition n 1 (str huge-num)))
max-prod (apply max (map first prod-n-digits-pairs))]
(filter #(= max-prod (first %)) prod-n-digits-pairs)))
(greatest-product-and-n-digits huge-num 4) ; ([5832 (9 9 8 9)])
(greatest-product-and-n-digits huge-num 13) ; ([23514624000 (5 5 7 6 6 8 9 6 6 4 8 9 5)])
(def greatest-product
(comp ffirst greatest-product-and-n-digits))
(greatest-product huge-num 13) ; 23514624000
view raw euler-8.clj hosted with ❤ by GitHub

Tuesday, September 2, 2014

Euler Project: Problem 7 in Clojure

This is my solution in Clojure to the seventh problem from Euler project:

(defn prime? [n]
(loop [n n prime 2 factors []]
(if (> (count factors) 1)
false
(cond
(= n 1) true
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors)))))
(def nums (iterate inc 2))
(last (take 10001 (filter prime? nums))) ; 104743
view raw euler-7.clj hosted with ❤ by GitHub

It works but it's quite slow.

Monday, September 1, 2014

Euler Project: Problem 6 in Clojure

This is my solution in Clojure to the sixth problem from Euler project:

(defn pow [x n]
(reduce * (repeat n x)))
(pow 55 2) ; 3025
(defn square [x]
(pow x 2))
(square 55) ; 3025
(def sum (comp (partial reduce +) map))
(sum identity (range 0 11)) ; 55
(sum square (range 0 11)) ; 385
(defn sum-square-difference [n]
(let [nums (range 0 (+ 1 n))]
(- (square (sum identity nums))
(sum square nums))))
(sum-square-difference 10) ; 2640
(sum-square-difference 100) ; 25164150
view raw euler-6.clj hosted with ❤ by GitHub

Sunday, August 31, 2014

Euler Project: Problem 5 in Clojure

I solved the fifth problem from Euler project in Clojure.

My first approach was not successful:

(def positive-integers (iterate inc 1))
(def evenly-divisible?
(comp zero? rem))
(defn evenly-divisible-by-numbers? [from to number]
(let [numbers (range from (+ to 1))]
(every? (partial evenly-divisible? number) numbers)))
(defn positive-numbers-evenly-divisible-by-numbers [from to]
(filter (partial evenly-divisible-by-numbers? from to)
positive-integers))
(first
(positive-numbers-evenly-divisible-by-numbers 1 10)) ; 2520
;(first
; (positive-numbers-evenly-divisible-by-numbers 1 20))
; java.lang.OutOfMemoryError: GC overhead limit exceeded
view raw euler-5-1.clj hosted with ❤ by GitHub

Even though it could compute the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder, it didn't work for 1 to 20.
It consumed to much memory.

So I used pen and paper to devise a better approach to solve the problem.

I saw that the numbers from 1 to 10 which multiplied produce 2520 are 9, 8, 7 and 5.
What these numbers have in common is that they all have one prime factor with the highest possible multiplicity in the 1 to 10 range.

This is the code that I derived from those two facts:

(def factor?
(comp zero? rem))
(defn prime-factors [n]
(loop [n n prime 2 factors []]
(cond
(= n 1) factors
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors))))
(defn unique-factor? [factors]
(and (not (empty? factors))
(apply = factors)))
(defn extract-divisors [numbers-with-unique-factor]
(loop [numbers-with-unique-factor numbers-with-unique-factor
divisors [] factors []]
(if (empty? numbers-with-unique-factor)
divisors
(let [factor (first (second (first numbers-with-unique-factor)))]
(if (some #{factor} factors)
(recur (rest numbers-with-unique-factor)
divisors
factors)
(recur (rest numbers-with-unique-factor)
(conj divisors (first (first numbers-with-unique-factor)))
(conj factors factor)))))))
(extract-divisors
(filter #(unique-factor? (second %))
(map #(vector % (prime-factors %))
(reverse (range 1 10))))) ; [9 8 7 5]
(extract-divisors
(filter #(unique-factor? (second %))
(map #(vector % (prime-factors %))
(reverse (range 1 20))))) ; [19 17 16 13 11 9 7 5]
(defn smallest-evenly-divisible-by-all [from to]
(reduce
*
(extract-divisors
(filter #(unique-factor? (second %))
(map #(vector % (prime-factors %))
(reverse (range from (+ to 1))))))))
(smallest-evenly-divisible-by-all 1 10) ; 2520
(smallest-evenly-divisible-by-all 1 20) ; 232792560
view raw euler-5-2.clj hosted with ❤ by GitHub

which yields the right result.

Update:

As Leo pointed out in his comment, the answer is the least common multiple of the numbers from 1 to 20.

This is the final (more elegant and much simpler than the previous one) solution to the problem:

(defn greatest-common-divisor [a b]
(if (zero? b)
a
(greatest-common-divisor b (rem a b))))
(defn least-common-multiple [a b]
(/ (* a b) (greatest-common-divisor a b)))
(defn smallest-positive-number-evenly-divisible-by-all [from to]
(reduce
least-common-multiple
(range from (+ to 1))))
(smallest-evenly-divisible-by-all 1 10) ; 2520
(smallest-evenly-divisible-by-all 1 20) ; 232792560
view raw euler-5-3.clj hosted with ❤ by GitHub

Euler Project: Problem 4 in Clojure

This is my solution in Clojure to the fourth problem from Euler project:

(reverse (range 100 1000)) ; (999 998 997 996 995 994 ...)
(defn palindrome? [number]
(let [num-str (str number)]
(= num-str (apply str (reverse num-str)))))
(palindrome? 9009) ; true
(palindrome? 9008) ; false
(apply
max
(filter
palindrome?
(let [numbers (reverse (range 10 100))]
(for [x1 numbers x2 numbers]
(* x1 x2))))) ; 9009
(defn products [lower higher]
(let [numbers (reverse (range lower (+ higher 1)))]
(for [x1 numbers x2 numbers]
(* x1 x2))))
(defn largest-palindrome-product [lower higher]
(apply max (filter palindrome? (products lower higher))))
(largest-palindrome-product 10 99) ; 9009
(largest-palindrome-product 100 999) ; 906609
view raw euler-4.clj hosted with ❤ by GitHub

It was nice to practise with for.

Books I read (January - August 2014)

January
- Pan, educación, libertad (Ψωμί, παιδεία, ελευθερία), Petros Márkaris
- NW London, Zadie Smith
- 101 cuentos clásicos de la China, Chang Shiru, Ramiro A. Calle
- Mr. Neighborly's Humble Little Ruby Book, Jeremy McAnally

February
- Blankets, Craig Thompson

March
- Practical Object-Oriented Design in Ruby, Sandi Metz
- Modern C++ Programming with Test-Driven Development, Jeff Langr

April
- Learning PHP, MySQL & JavaScript, Robin Nixon
- Measuring the world, Daniel Kehlmann

May
- El hombre que plantaba árboles, (L'homme qui plantait des arbres), Jean Giono
- Extreme Programming Explained, Embrace Change, Kent Beck
- Adiós, Chunky Rice, (Good-bye, Chunky Rice), Craig Thompson

June
- Eloquent Ruby, Russ Olsen
- Implementing Domain-Driven Design, Vaughn Vernon

July
- JavaScript Allongé, Reginald Braithwaite
- JavaScript: The Good Parts, Douglas Crockford

August
- Programming Clojure, (2nd edition), Stuart Halloway and Aaron Bedra
- Introduction to Computing, Explorations in Language, Logic and Machines, David Evans
- JavaScript Allongé, Reginald Braithwaite (2nd time)

Thursday, August 28, 2014

Exercism: "Raindrops in Clojure"

I solved the Raindrops problem in Clojure.

This is my solution:

(ns raindrops)
(declare prime-factors convert-factor)
(defn convert [n]
(let
[factors (apply sorted-set (prime-factors n))]
(if (some #(or (= % 3) (= % 5) (= % 7)) factors)
(apply str (map convert-factor factors))
(str n))))
(defn- convert-factor [factor]
(cond
(= factor 3) "Pling"
(= factor 5) "Plang"
(= factor 7) "Plong"
:else ""))
(def ^:private factor?
(comp zero? rem))
(defn- prime-factors [n]
(loop [n n prime 2 factors []]
(cond
(= n 1) factors
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors))))
view raw raindrops.clj hosted with ❤ by GitHub

Where I used the code I wrote for the Prime factors kata in Clojure

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

Exercism: "Prime Factors in Clojure"

I solved the Prime factors problem in Clojure.

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

Wednesday, August 27, 2014

Exercism: "Roman Numerals in Clojure"

I solved the Roman Numerals problem in Clojure.

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

Tuesday, August 26, 2014

Kata: Roman Numerals in Clojure

I've just done the Roman Numerals kata in Clojure.

I used this description of roman numerals, On Roman Numerals, and continued the kata to also convert numbers over 3000.

These are the tests using Midje that I wrote to test-drive the solution:

(ns roman-numerals.core-test
(:use midje.sweet)
(:use [roman-numerals.core]))
(facts
"about arabic to roman numerals conversion"
(fact "it converts numbers until 10"
(arabic-to-roman 1) => "I"
(arabic-to-roman 2) => "II"
(arabic-to-roman 3) => "III"
(arabic-to-roman 4) => "IV"
(arabic-to-roman 5) => "V"
(arabic-to-roman 8) => "VIII"
(arabic-to-roman 9) => "IX"
(arabic-to-roman 10) => "X")
(fact "it converts numbers from 10 to 39"
(arabic-to-roman 13) => "XIII"
(arabic-to-roman 14) => "XIV"
(arabic-to-roman 25) => "XXV"
(arabic-to-roman 28) => "XXVIII"
(arabic-to-roman 39) => "XXXIX")
(fact "it converts numbers from 40 to 89"
(arabic-to-roman 40) => "XL"
(arabic-to-roman 49) => "XLIX"
(arabic-to-roman 50) => "L"
(arabic-to-roman 89) => "LXXXIX")
(fact "it converts numbers from 90 to 199"
(arabic-to-roman 90) => "XC"
(arabic-to-roman 99) => "XCIX"
(arabic-to-roman 100) => "C"
(arabic-to-roman 199) => "CXCIX")
(fact "it converts numbers from 200 to 1000"
(arabic-to-roman 200) => "CC"
(arabic-to-roman 250) => "CCL"
(arabic-to-roman 400) => "CD"
(arabic-to-roman 499) => "CDXCIX"
(arabic-to-roman 500) => "D"
(arabic-to-roman 899) => "DCCCXCIX"
(arabic-to-roman 900) => "CM"
(arabic-to-roman 999) => "CMXCIX"
(arabic-to-roman 1000) => "M")
(fact "it converts numbers from 1001 to 3999"
(arabic-to-roman 1100) => "MC"
(arabic-to-roman 1200) => "MCC"
(arabic-to-roman 2250) => "MMCCL"
(arabic-to-roman 3400) => "MMMCD"
(arabic-to-roman 3499) => "MMMCDXCIX"
(arabic-to-roman 3500) => "MMMD"
(arabic-to-roman 3899) => "MMMDCCCXCIX"
(arabic-to-roman 3900) => "MMMCM"
(arabic-to-roman 3999) => "MMMCMXCIX"
(arabic-to-roman 3000) => "MMM")
(fact "it converts numbers over 3999"
(arabic-to-roman 4000) => "--\nIV"
(arabic-to-roman 4001) => "--\nIVI"
(arabic-to-roman 3999005) => "---------\nMMMCMXCIXV"
(arabic-to-roman 4000000) => "--\n--\nIV"
(arabic-to-roman 4000025) => "--\n--\nIVXXV"))

and this is the code:

(ns roman-numerals.core)
(declare huge-roman-numeral convert roman-symbols)
(defn arabic-to-roman [arabic]
(cond
(<= arabic 10) (convert arabic :until-10)
(<= arabic 100) (str (convert (quot arabic 10) :until-100)
(arabic-to-roman (mod arabic 10)))
(<= arabic 1000) (str (convert (quot arabic 100) :until-1000)
(arabic-to-roman (mod arabic 100)))
(<= arabic 3999) (str (convert (quot arabic 1000) :until-3999)
(arabic-to-roman (mod arabic 1000)))
:else (huge-roman-numeral arabic)))
(def ^:private roman-symbols
{:until-10 "IVX"
:until-100 "XLC"
:until-1000 "CDM"
:until-3999 "M "})
(defn- convert [arabic in-range]
(let [[from medium to] (roman-symbols in-range)]
(cond
(= arabic 0) ""
(= arabic 10) (str to (convert (- arabic 10) in-range))
(= arabic 4) (str from medium)
(>= arabic 9) (str from to (convert (- arabic 9) in-range))
(>= arabic 5) (str medium (convert (- arabic 5) in-range))
:else (str from (convert (- arabic 1) in-range)))))
(defn- thousand-bar [size]
(str (apply str (repeat (count size) "-")) "\n"))
(defn- times-thousand [arabic]
(loop [n arabic times 0]
(if (<= n 3999)
times
(recur (quot n 1000) (+ times 1)))))
(defn- pow [m n]
(reduce * (repeat n m)))
(defn- huge-roman-numeral [arabic]
(let [times (times-thousand arabic)
div (pow 1000 times)
thousand-multiple (arabic-to-roman (quot arabic div))
horizontal-bar (thousand-bar thousand-multiple)]
(str
(apply str (repeat times horizontal-bar))
thousand-multiple
(arabic-to-roman (mod arabic div)))))

It's possible to convert numbers over 3999:

user=> (println (arabic-to-roman 3999005))
---------
MMMCMXCIXV
nil
user=> (println (arabic-to-roman 3999050))
---------
MMMCMXCIXL
nil
user=> (println (arabic-to-roman 3999150))
---------
MMMCMXCIXCL
nil
user=> (println (arabic-to-roman 4000150))
--
--
IVCL
nil
user=> (println (arabic-to-roman 3999000150))
---------
---------
MMMCMXCIXCL
nil

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.

It's been difficult to derive this recursive algorithm only using strict TDD, but it was also a lot of fun.

You can find the resulting code in GitHub.


Update: Recently I revisited the Roman Numerals kata and got to a simpler solution.

Exercism: "Scrabble Score in Clojure"

This is my solution to the Scrabble Score problem in Clojure.

(ns scrabble_score
(:require [clojure.string :as str]))
(def ^:private score-by-letter
{"A" 1 "E" 1 "I" 1 "O" 1 "U" 1 "L" 1 "N" 1 "R" 1 "S" 1 "T" 1
"D" 2 "G" 2
"B" 3 "C" 3 "M" 3 "P" 3
"F" 4 "H" 4 "V" 4 "W" 4 "Y" 4
"K" 5
"J" 8 "X" 8
"Q" 10 "Z" 10})
(defn score-letter [letter]
(get score-by-letter (str/upper-case letter)))
(defn score-word [word]
(reduce + (map #(score-letter %) word)))

I added some extra tests to complete the provided ones:

(ns scrabble-score.test (:require [clojure.test :refer :all]))
(load-file "scrabble_score.clj")
(deftest lower-case-letter
(is (= 1 (scrabble_score/score-letter "a"))))
(deftest upper-case-letter
(is (= 1 (scrabble_score/score-letter "A"))))
(deftest letters-scoring-1
(is (= 10 (scrabble_score/score-word "AEIOULNRST") (scrabble_score/score-word "aeioulnrst"))))
(deftest letters-scoring-2
(is (= 4 (scrabble_score/score-word "DG") (scrabble_score/score-word "dg"))))
(deftest letters-scoring-3
(is (= 12 (scrabble_score/score-word "BCMP") (scrabble_score/score-word "bcmp"))))
(deftest letters-scoring-4
(is (= 20 (scrabble_score/score-word "FHVWY") (scrabble_score/score-word "fhvwy"))))
(deftest letters-scoring-5
(is (= 5 (scrabble_score/score-word "K") (scrabble_score/score-word "k"))))
(deftest letters-scoring-8
(is (= 16 (scrabble_score/score-word "JX") (scrabble_score/score-word "jx"))))
(deftest letters-scoring-10
(is (= 20 (scrabble_score/score-word "QZ") (scrabble_score/score-word "qz"))))
(deftest two-letter-word
(is (= 2 (scrabble_score/score-word "at"))))
(deftest bigger-word-1
(is (= 6 (scrabble_score/score-word "street"))))
(deftest bigger-word-2
(is (= 22 (scrabble_score/score-word "quirky"))))
(deftest all-upper-case-word
(is (= 20 (scrabble_score/score-word "MULTIBILLIONAIRE"))))
(run-tests)

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

Monday, August 25, 2014

Euler Project: Problem 3 in Clojure

This is my solution in Clojure to the third problem from Euler project:

(def factor?
(comp zero? rem))
(defn prime-factors [n]
(loop [n n prime 2 factors #{}]
(cond
(= n 1) factors
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors))))
(prime-factors 35) ; #{5 7}
(prime-factors 24) ; #{2 3}
(prime-factors 600851475143) ; #{71 839 6857 1471}
(apply max (prime-factors 600851475143)) ; 6857
(defn largests-prime-factor [n]
(apply max (prime-factors n)))
(largests-prime-factor 600851475143) ; 6857
view raw euler-3.clj hosted with ❤ by GitHub

The largests-prime-factor function can be also written in this alternative way using Clojure's ->> macro:

(defn largests-prime-factor [n]
(->>
n
(prime-factors)
(apply max)))
view raw euler-3-b.clj hosted with ❤ by GitHub

Kata: Prime factors in Clojure

I've just done the Prime factors kata in Clojure.

These are the tests using Midje:

(ns prime-factors.core-test
(:use midje.sweet)
(:use [prime-factors.core]))
(facts
"about prime factors computation"
(fact "1 has no factors"
(factorize 1) => [])
(fact "a prime has only one factor: itself"
(factorize 2) => [2]
(factorize 3) => [3])
(fact "any power of primes has only one factor repeated as many times as the exponent"
(factorize 8) => [2 2 2]
(factorize 81) => [3 3 3 3])
(fact "any other positive integer has more than one factor"
(factorize 10) => [2 5]
(factorize 60) => [2 2 3 5]))

and this is the code:

(ns prime-factors.core)
(def ^:private factor?
(comp zero? rem))
(defn factorize [n]
(loop [n n prime 2 factors []]
(cond
(= n 1) factors
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors))))

You can find the commits step by step here.

Interesting Talk: "What does it mean to be Reactive?"

I've just watched this interesting talk by Erik Meijer:

Interesting Talk: "Being Human"

Yesterday I watched this very interesting talk by Brian J Brennan:

Friday, August 15, 2014

Interesting Talk: "SICP Lecture 3A: Henderson Escher Example"

I've just watched this wonderful class by Harold Abelson:

Pascal's triangle

Here is another exercise from David Evans book Introduction to Computing, Explorations in Language, Logic, and Machines.

This is a possible solution for the Pascal's triangle exploration at the end of chapter 5:

#lang racket
(require rackunit)
(define (pascal-triangle-number row col)
(if (or (= col 0)
(= col row))
1
(+ (pascal-triangle-number (- row 1) col)
(pascal-triangle-number (- row 1) (- col 1)))))
(check-equal?
(pascal-triangle-number 0 0) 1)
(check-equal?
(pascal-triangle-number 1 0) 1)
(check-equal?
(pascal-triangle-number 1 1) 1)
(check-equal?
(pascal-triangle-number 2 0) 1)
(check-equal?
(pascal-triangle-number 2 1) 2)
(check-equal?
(pascal-triangle-number 2 2) 1)
(check-equal?
(pascal-triangle-number 3 1) 3)
(check-equal?
(pascal-triangle-number 3 2) 3)
(check-equal?
(pascal-triangle-number 4 1) 4)
(check-equal?
(pascal-triangle-number 4 2) 6)
(check-equal?
(pascal-triangle-number 4 3) 4)
(define (pascal-triangle-row n)
(define (helper n i)
(if (< i 0)
null
(cons (pascal-triangle-number n i)
(helper n (- i 1)))))
(helper n n))
(check-equal? (pascal-triangle-row 0) (list 1))
(check-equal? (pascal-triangle-row 1) (list 1 1))
(check-equal? (pascal-triangle-row 2) (list 1 2 1))
(define (range from to)
(if (> from to)
null
(cons from
(range (+ from 1) to))))
(define (pascal-triangle n)
(map
pascal-triangle-row
(range 0 n)))
(check-equal?
(pascal-triangle 0)
(list (list 1)))
(check-equal?
(pascal-triangle 1)
(list (list 1) (list 1 1)))
(check-equal?
(pascal-triangle 2)
(list (list 1) (list 1 1) (list 1 2 1)))
(check-equal?
(pascal-triangle 4)
(list (list 1) (list 1 1) (list 1 2 1) (list 1 3 3 1) (list 1 4 6 4 1)))

It's a nice exercise to practise recursion.

Practising recursion with accumulate, filter and map for deeply nested lists

I'm practising recursion going through some of the exercises in David Evans book Introduction to Computing, Explorations in Language, Logic, and Machines.

These are the solutions to three of those exercises:

  1. An accumulate (reduce) function for a list which can contain arbitrarily deeply nested lists.

    #lang racket
    (require rackunit)
    (define (deep-list-accumulate comb base dls)
    (if (null? dls)
    base
    (let [(first-dls (first dls))]
    (comb (deep-list-accumulate comb base (rest dls))
    (if (list? first-dls)
    (deep-list-accumulate comb base first-dls)
    first-dls)))))
    (define (deep-list-sum dls)
    (deep-list-accumulate + 0 dls))
    (define (deep-list-prod dls)
    (deep-list-accumulate * 1 dls))
    (check-equal?
    (deep-list-sum '()) 0)
    (check-equal?
    (deep-list-sum (list (list 1))) 1)
    (check-equal?
    (deep-list-sum (list (list 1) (list 1))) 2)
    (check-equal?
    (deep-list-sum (list 1 (list 1))) 2)
    (check-equal?
    (deep-list-prod (list 1 (list 2 (list 3 (list 4))))) 24)
  2. A map function for a list which can contain arbitrarily deeply nested lists.

    #lang racket
    (require rackunit)
    (define (deep-list-map f dls)
    (if (null? dls)
    null
    (let [(first-dls (first dls))]
    (cons
    (if (list? first-dls)
    (deep-list-map f first-dls)
    (f first-dls))
    (deep-list-map f (rest dls))))))
    (define (deep-list-square dls)
    (deep-list-map (lambda (x) (* x x)) dls))
    (define (deep-list-double dls)
    (deep-list-map (lambda (x) (* 2 x)) dls))
    (check-equal?
    (deep-list-square (list 2))
    (list 4))
    (check-equal?
    (deep-list-square (list 1 (list 2 (list 3))))
    (list 1 (list 4 (list 9))))
    (check-equal?
    (deep-list-double (list 1 (list 2 (list (list 2 3 4) 3 (list 4)))))
    (list 2 (list 4 (list (list 4 6 8) 6 (list 8)))))
  3. A filter function for a list which can contain arbitrarily deeply nested lists.

    #lang racket
    (require rackunit)
    (define (deep-list-filter pred dls)
    (if (null? dls)
    null
    (let [(first-dls (first dls))
    (rest-dls (rest dls))]
    (if (list? first-dls)
    (cons (deep-list-filter pred first-dls)
    (deep-list-filter pred rest-dls))
    (if (pred first-dls)
    (cons first-dls
    (deep-list-filter pred rest-dls))
    (deep-list-filter pred rest-dls))))))
    (define (even? x)
    (zero? (modulo x 2)))
    (define (evens-in dls)
    (deep-list-filter even? dls))
    (define (odds-in dls)
    (deep-list-filter
    (lambda (x) (not (even? x)))
    dls))
    (check-equal?
    (evens-in (list 2 3 4))
    (list 2 4))
    (check-equal?
    (odds-in (list 2 3 4))
    (list 3))
    (check-equal?
    (odds-in (list 1 (list 2 (list 3))))
    (list 1 (list (list 3))))
    (check-equal?
    (evens-in (list 1 (list 2 (list 3))))
    (list (list 2 (list))))
    (check-equal?
    (evens-in (list 1 (list 2 (list (list 2 3 4) 3 (list 4)))))
    (list (list 2 (list (list 2 4) (list 4)))))
    (check-equal?
    (odds-in (list 1 (list 2 (list (list 2 3 4) 3 (list 4)))))
    (list 1 (list (list (list 3) 3 (list)))))
You can find these and other exercises and examples from the book in this GitHub repository.

I'm loving the book.

Monday, August 11, 2014

Interesting Talk: "SICP Lecture 2A: Higher-order Procedures"

I've just watched this wonderful class by Gerald Jay Sussman:

Kata: Find indexes of all upper-case letters in a word

Last Friday I went to a kata of Barcelona Software Craftsmanship facilitated by Carlos Blé at Runroom.

We had to write a function using TDD that when given a word will produce an array containing the positions of all the capital letters in the word.

The most interesting part of the exercise came during the second interaction in which we had the constraint of not mutating any value.

Although we didn't managed to finish the exercise, we had a very interesting debate about recursion, baby steps and TDD.

Once back at home I started to grow the code again in tiny steps, trying to make explicit the problem patterns before taking the leap of faith of recursion.

This is the code passing all the tests right before being refactored to be recursive:

'use strict';
function findCapitalLetterPositions(word) {
var res = [];
if(word.length === 0) {
return res;
}
if(isUpperCase(word[0])) {
res = res.concat([0]);
}
if (word.length == 1) {
return res;
}
if(isUpperCase(word[1])) {
res = res.concat([1]);
}
return res;
}
function isUpperCase(letter) {
return letter.toUpperCase() == letter[0];
}
describe("Upper case letters finder", function() {
it("an empty word contains no capital letters", function() {
expect(findCapitalLetterPositions("")).toEqual([]);
});
it("finds the index of a word with one letter that is upper case", function() {
expect(findCapitalLetterPositions("A")).toEqual([0]);
});
it("produces no index for a one letter word containing no capital letters", function() {
expect(findCapitalLetterPositions("a")).toEqual([]);
});
it("produces the index of a capital letter not at the beginning of the word", function() {
expect(findCapitalLetterPositions("aA")).toEqual([1]);
});
it("produces the indexes of a two capital letters word", function() {
expect(findCapitalLetterPositions("BA")).toEqual([0,1]);
});
});

In the repetition that existed in this code, it was possible to see two emerging patterns:
  1. The base case of the recursion which happens when the word length is equal to the current index.
  2. The use of concat to make the result grow when the character at the current index is a capital letter
Using that information I refactored the code to get to this recursive solution, (after a pair of failed attempts...):

'use strict';
function findCapitalLetterPositions(word) {
return f(word, 0);
function f(word, index) {
if(word.length == index) {
return [];
}
if(isUpperCase(word[index])) {
return [index].concat(f(word, index + 1));
}
return f(word, index + 1);
}
}
function isUpperCase(letter) {
return letter.toUpperCase() == letter[0];
}
describe("Upper case letters finder", function() {
it("an empty word contains no capital letters", function() {
expect(findCapitalLetterPositions("")).toEqual([]);
});
it("finds the index of a word with one letter that is upper case", function() {
expect(findCapitalLetterPositions("A")).toEqual([0]);
});
it("produces no index for a one letter word containing no capital letters", function() {
expect(findCapitalLetterPositions("a")).toEqual([]);
});
it("produces the index of a capital letter not at the beginning of the word", function() {
expect(findCapitalLetterPositions("aA")).toEqual([1]);
});
it("produces the indexes of a two capital letters word", function() {
expect(findCapitalLetterPositions("BA")).toEqual([0,1]);
});
});

In it you can still distinguish the similarities with the previous non-recursive version.

The base case now returns an empty array and concat is used again when a capital letter is found at the current index, only that the concatenation is now with a one-element list containing the current index.

In any other case, no element is concatenated to the result and the function is called again with the next index.

Later, I refactored the code and the tests a bit more to get to these final versions of the tests:

'use strict';
var findCapitalLetterPositions = require('./UpperCaseFinder.js').findCapitalLetterPositions;
describe("Upper case letters finder", function() {
it("produces no index for an empty word", function() {
expect(findCapitalLetterPositions("")).toEqual([]);
});
it("produces the indexes of capital letters in a word", function() {
expect(findCapitalLetterPositions("BAsrwQMPaZ")).toEqual([0, 1, 5, 6, 7, 9]);
});
it("ignores characters that are not letters", function() {
expect(findCapitalLetterPositions("3As5wQ6PaZ")).toEqual([1, 5, 7, 9]);
});
});

and the code:

'use strict';
function findCapitalLetterPositions(word, index) {
if (index === undefined) {
return findCapitalLetterPositions(word, 0);
}
if (word.length == index) {
return [];
}
if (isNotLetter(word[index]) || isNotUpperCase(word[index])) {
return findCapitalLetterPositions(word, index + 1);
}
return [index].concat(
findCapitalLetterPositions(word, index + 1)
);
function isNotUpperCase(letter) {
return letter.toUpperCase() != letter[0];
}
function isNotLetter(char) {
return !char.match(/[a-z]/i);;
}
}
module.exports.findCapitalLetterPositions = findCapitalLetterPositions

You can check the code in this GitHub repository.

All in all, I'm under the impression that I wrote the before-recursion code that way because I already had an insight of how the recursive solution was going to be.

Had I written it in a different way, might it have made more difficult to find a recursive solution?
What would have happened with a more difficult problem?

I'm not sure if TDD alone will help me to find recursive solutions.

I will keep working on it.

Sunday, August 10, 2014

Some home-made implementations of map

This post originated in a conversation we had during the last Barcelona Software Craftsmanship event.

We talked about a technique to recursively processing list elements once at a time in which you have to focus on two things:
  1. How to process an empty list (the base case of the recursion)
  2. How to process a non empty list in terms of the result of processing the tail of the list (the list except the first element)
To illustrate it, let's see a possible implementation of map in SML:

fun mapUsingListFunctions(f, ls) =
if null ls
then []
else f(hd ls)::mapUsingListFunctions(f, tl ls)
val test = mapUsingListFunctions(
(fn x => x * x),
[1, 2, 3])
(* val test = [1,4,9] : int list *)

It uses the following list functions:
  • hd to extract the head of the list (its first element)
  • tl to extract the tail of the list (the list except the first element)
  • null that returns true if the list is empty and false otherwise
The :: operator adds an element at the beginning of a list.

We can use a similar approach to write map in Racket:

#lang racket
(define (map-using-list-functions f ls)
(if (empty? ls)
'()
(cons (f (first ls))
(map-using-list-functions f (rest ls)))))
(map-using-list-functions
(lambda (x) (* x x))
'(1 2 3))
; '(1 4 9)

Here the name of the functions are a bit more expressive: first, rest and empty?.
The cons function adds an element at the beginning of a list.

A more idiomatic way to write map in SML would be using pattern matching:

fun mapUsingPatternMatching(f, ls) =
case ls of
[] => []
| head::tail => f(head)::mapUsingPatternMatching(f, tail)
val test = mapUsingPatternMatching(
(fn x => x * x),
[1, 2, 3])
(* val test = [1,4,9] : int list *)

This version is using the same approach but pattern matching makes the code more concise and expressive.

As a bonus here is a beautiful way to append two lists in SML using the same technique and pattern matching:

fun append(xs, ys) =
case xs of
[] => ys
| head::tail => head::append(tail, ys)
val testAppend1 = append([1, 2, 3, 4], [5, 6, 7])
(* val testAppend1 = [1,2,3,4,5,6,7] : int list *)
val testAppend2 = append([], [5, 6, 7])
(* val testAppend2 = [5,6,7] : int list *)
val testAppend3 = append([1, 2, 3, 4], [])
(* val testAppend3 = [1,2,3,4] : int list *)

This is very well explained in the first unit of of the Programming Languages course from Washington University at Coursera that I completed last year.

There is going to be a new edition starting up Oct 2. I cannot recommend it highly enough.

Tuesday, August 5, 2014

Interesting Talk: "Code that fits your brain"

I've just watched this very interesting talk by Adam Tornhill:

Exercism: Revisiting "Space Age in Clojure"

I used metaprogramming as I did in the Meetup problem to simplify the code of the Space Age problem (you can find my previous versions here):

(ns space-age)
(def planets
['mercury
'venus
'mars
'jupiter
'saturn
'uranus
'neptune])
(def orbital-periods-in-earth-years
(zipmap
planets
[0.2408467
0.61519726
1.8808158
11.862615
29.447498
84.016846
164.79132]))
(defn on-earth [seconds]
(let
[seconds-per-earth-year 31557600.0]
(/ seconds seconds-per-earth-year)))
(defn make-on-planet-function [orbital-period-in-earth-years]
(fn [seconds]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(doall
(map
#(intern
'space-age
(symbol (str "on-" (name %)))
(make-on-planet-function
(% orbital-periods-in-earth-years)))
planets))
view raw space-age4.clj hosted with ❤ by GitHub

This version has less repetition than the previous ones.

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

Exercism: "Triangle in Clojure"

This is my solution to the Triangle problem in Clojure.

(ns triangle)
(defn- equilateral? [a b c]
(= a b c))
(defn- isosceles? [a b c]
(or (= a b) (= b c) (= a c)))
(defn- triangle? [a b c]
(and
(< a (+ b c))
(< b (+ a c))
(< c (+ b a))))
(defn type [a b c]
(cond
(not (triangle? a b c)) :illogical
(equilateral? a b c) :equilateral
(isosceles? a b c) :isosceles
:else :scalene))
view raw triangle.clj hosted with ❤ by GitHub

This was an easy one.

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

Euler Project: Problem 2 in Clojure

This is my solution in Clojure to the second problem from Euler project:

(def fibonaccis
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
(def evens-in (partial filter even?))
(defn fibonaccis-below [num]
(take-while (partial > num) fibonaccis))
(reduce + 0 (evens-in (fibonaccis-below 4000000)))
view raw euler2.clj hosted with ❤ by GitHub
I created some helpers just to make the solution a bit more readable.

Sunday, August 3, 2014

Exercism: "Gigasecond in Ruby"

I solved the Gigasecond exercise in Ruby a month ago but I forgot to post it.

Since my previous post was about the solution to this exercise using Clojure, I'll post here its solution in Ruby:

class Gigasecond
GS_IN_DAYS = (10**9)/(60*60*24)
def initialize (birth_date)
@birth_date = birth_date
end
def date
@birth_date + GS_IN_DAYS
end
end
view raw gigasecond.rb hosted with ❤ by GitHub

In this case life is much easier in Ruby :)

Exercism: "Gigasecond in Clojure"

This is my solution to the Gigasecond problem in Clojure.

(ns gigasecond
(:require [clojure.string :as str])
(:import [java.util Calendar]
[java.text SimpleDateFormat]))
(defn- date [year month day]
(let
[calendar (Calendar/getInstance)]
(.setTime
calendar
(.parse
(SimpleDateFormat. "yyyy-MM-dd")
(str year "-" month "-" day)))
calendar))
(defn- add-days [date days]
(.add date (Calendar/DATE) days)
date)
(defn- date-to-vec [date]
[(.get date (Calendar/YEAR))
(+ (.get date (Calendar/MONTH)) 1)
(.get date (Calendar/DATE))])
(def GS_IN_DAYS
(/ (reduce * (repeat 9 10))
(* 60 60 24)))
(defn from [year month day]
(->
(date year month day)
(add-days GS_IN_DAYS)
date-to-vec))
view raw gigasecond.clj hosted with ❤ by GitHub

To solve it I had to learn first how to add days to a date in Java by having a look to the SimpleDateFormat and Calendar classes.

Then I learned a bit about how to use Java from Clojure in the Clojure Java Interop documentation and this other useful post: Calling java from Clojure.

Finally, once I had it working on the REPL, I added some private helper functions and used the -> macro in the implementation of the from function 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.

Interesting Talk: "Becoming an Outlier: Career Reboot for the Developer Mind"

I've just watched this interesting talk by Cory House:

Using jQuery Validation plugin with a custom rule and HTML5 data attributes

This is a small example from something I did recently at work.

We needed to apply some custom validation rules to some form fields using the jQuery Validation Plugin.

The decision of which fields were contained in a given form was taken dynamically, so instead of dynamically creating a rules object to pass it to the validate method, we decided to use HTML5 data attributes.

In the following example, I'll show you a way to do it.

Imagine that we'd like to validate that the first name introduced in a form is a palindrome.

To do it you could add a custom rule palindrome to the jQuery Validation plugin using its addMethod method and then validate the form, as shown in this JavaScript code:

var customValidations = (function() {
function reverse(word) {
var i, reversedLetters = [];
for (i = word.length - 1; i >= 0; i--) {
reversedLetters.push(word[i]);
}
return reversedLetters.join('');
}
return {
isPalindrome: function(word) {
return reverse(word) === word;
}
}
})();
$.validator.addMethod("palindrome", function(value) {
return customValidations.isPalindrome(value);
});
$("#exampleForm").validate();
view raw validation.js hosted with ❤ by GitHub

In the form we can refer to this custom rule using HTML5 data attributes:

<!DOCTYPE html>
<html>
<body>
<form id="exampleForm" action="" autocomplete="on">
First name:
<input type="text" name="fname" required
data-rule-palindrome="true"
data-msg-palindrome="Please introduce a palindrome"><br>
Last name:
<input type="text" name="lname" required><br>
<input type="submit">
</form>
<script
src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
<script
src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js">
</script>
<script
src="validation.js">
</script>
</body>
</html>

We used data-rule-palindrome="true" to state that the fname field must contain a palindrome and data-msg-palindrome="Please your name must be a palindrome" to set the message that is shown in case it's not a palindrome.

In a nutshell, using jQuery Validation plugin with a custom rule and HTML5 data attributes is as easy as adding a custom rule with addMethod and then adding in the field you want to validate with the custom rule:
  • data-rule + custom_rule_name="true" to apply the rule to a given field
  • data-msg- + custom_rule_name = "message" to set the error message

I hope you might find this useful

Saturday, August 2, 2014

Exercism: Revisiting "Grains in Clojure"

Recently I solved the Grains problem using a home-made stream both using Clojure and Racket (check the the Clojure's solution and the Racket's solution).

As I said then, the solution in Clojure was not idiomatic at all. I just wanted to write a stream in Clojure similar to the ones I had studied in the Coursera Programming Languages course.

This new version is a much more simple and Clojurist way of solving the same problem using the iterate function:

(ns grains)
(def grains (iterate #(* 2 %) 1N))
(defn square [sqr-num]
(nth grains (- sqr-num 1)))
(defn total []
(reduce + 0 (take 64 grains)))
view raw grains2.clj hosted with ❤ by GitHub

The iterate function generates a lazy sequence containing the number of grains in each square. The square and total functions realize that lazy sequence to get the content of a given square and the sum of the 64 squares of the chess board, respectively.

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

Thursday, July 24, 2014

Exercism: "Meetup in Clojure"

This is my solution to the Meetup problem in Clojure.

This is the first version:

(ns meetup)
(defn leap? [year]
(let
[divisible-by? (comp zero? (partial rem year))]
(or
(divisible-by? 400)
(and
(divisible-by? 4)
(not (divisible-by? 100))))))
(defn get-months-accum-days-moduli [year month]
(let
[months-accum-days-moduli-year
[0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5]
months-accum-days-moduli-leap-year
[0, 3, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6]]
(if (leap? year)
(nth months-accum-days-moduli-leap-year (- month 1))
(nth months-accum-days-moduli-year (- month 1)))))
(defrecord Date [year month day])
(defn compute-week-day [{year :year month :month day :day}]
(let
[div1 (quot (- year 1) 4)
div2 (quot (- year 1) 100)
div3 (quot (+ div2 1) 4)
div4 (int (- div1 (* 3 div3)))
week-day (rem
(+ (rem (- year 1) 7)
(rem div4 7)
(get-months-accum-days-moduli year month)
(rem day 7))
7)]
(if (zero? week-day) 7 week-day)))
(defn last-day-in-month [month year]
(let
[last-days-in-months
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
last-day (nth last-days-in-months (- month 1))]
(if (and (leap? year) (= month 2))
(+ 1 last-day)
last-day)))
(defn dates-in-month [month year]
(map (fn [day] (Date. year month day))
(range 1 (+ (last-day-in-month month year) 1))))
(defn is-week-day? [week-day date]
(let
[week-days {:MON 1 :TUE 2 :WED 3 :THU 4 :FRI 5 :SAT 6 :SUN 7}]
(= (week-days week-day) (compute-week-day date))))
(defn is-teenth? [{day :day}]
(let
[teenth-days (set (range 13 20))]
(teenth-days day)))
(defn days-of-month-that-is [week-day]
(comp
(partial
filter
(partial is-week-day? week-day))
dates-in-month))
(defn day-teenth [week-day]
(comp vec
vals
first
(partial filter #(is-teenth? %))
(days-of-month-that-is week-day)))
(def monteenth (day-teenth :MON))
(def tuesteenth (day-teenth :TUE))
(def wednesteenth (day-teenth :WED))
(def thursteenth (day-teenth :THU))
(def friteenth (day-teenth :FRI))
(def saturteenth (day-teenth :SAT))
(def sunteenth (day-teenth :SUN))
(defn get-week-day [pos week-day]
(comp vec
vals
pos
(days-of-month-that-is week-day)))
(def first-monday (get-week-day first :MON))
(def first-tuesday (get-week-day first :TUE))
(def first-wednesday (get-week-day first :WED))
(def first-thursday (get-week-day first :THU))
(def first-friday (get-week-day first :FRI))
(def first-saturday (get-week-day first :SAT))
(def first-sunday (get-week-day first :SUN))
(def second-monday (get-week-day second :MON))
(def second-tuesday (get-week-day second :TUE))
(def second-wednesday (get-week-day second :WED))
(def second-thursday (get-week-day second :THU))
(def second-friday (get-week-day second :FRI))
(def second-saturday (get-week-day second :SAT))
(def second-sunday (get-week-day second :SUN))
(defn third [ls] (nth ls 2))
(def third-monday (get-week-day third :MON))
(def third-tuesday (get-week-day third :TUE))
(def third-wednesday (get-week-day third :WED))
(def third-thursday (get-week-day third :THU))
(def third-friday (get-week-day third :FRI))
(def third-saturday (get-week-day third :SAT))
(def third-sunday (get-week-day third :SUN))
(defn fourth [ls] (nth ls 3))
(def fourth-monday (get-week-day fourth :MON))
(def fourth-tuesday (get-week-day fourth :TUE))
(def fourth-wednesday (get-week-day fourth :WED))
(def fourth-thursday (get-week-day fourth :THU))
(def fourth-friday (get-week-day fourth :FRI))
(def fourth-saturday (get-week-day fourth :SAT))
(def fourth-sunday (get-week-day fourth :SUN))
(def last-monday (get-week-day last :MON))
(def last-tuesday (get-week-day last :TUE))
(def last-wednesday (get-week-day last :WED))
(def last-thursday (get-week-day last :THU))
(def last-friday (get-week-day last :FRI))
(def last-saturday (get-week-day last :SAT))
(def last-sunday (get-week-day last :SUN))
view raw meetup1.clj hosted with ❤ by GitHub

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:

(ns meetup)
(defn leap? [year]
(let
[divisible-by? (comp zero? (partial rem year))]
(or
(divisible-by? 400)
(and
(divisible-by? 4)
(not (divisible-by? 100))))))
(defn get-months-accum-days-moduli [year month]
(let
[months-accum-days-moduli-year
[0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5]
months-accum-days-moduli-leap-year
[0, 3, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6]]
(if (leap? year)
(nth months-accum-days-moduli-leap-year (- month 1))
(nth months-accum-days-moduli-year (- month 1)))))
(defrecord Date [year month day])
(defn compute-week-day [{year :year month :month day :day}]
(let
[div1 (quot (- year 1) 4)
div2 (quot (- year 1) 100)
div3 (quot (+ div2 1) 4)
div4 (int (- div1 (* 3 div3)))
week-day (rem
(+ (rem (- year 1) 7)
(rem div4 7)
(get-months-accum-days-moduli year month)
(rem day 7))
7)]
(if (zero? week-day) 7 week-day)))
(defn last-day-in-month [month year]
(let
[last-days-in-months
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
last-day (nth last-days-in-months (- month 1))]
(if (and (leap? year) (= month 2))
(+ 1 last-day)
last-day)))
(defn dates-in-month [month year]
(map (fn [day] (Date. year month day))
(range 1 (+ (last-day-in-month month year) 1))))
(def week-days {'mon 1 'tues 2 'wednes 3 'thurs 4 'fri 5 'satur 6 'sun 7})
(defn is-week-day? [week-day date]
(= (week-days week-day) (compute-week-day date)))
(defn is-teenth? [{day :day}]
(let
[teenth-days (set (range 13 20))]
(teenth-days day)))
(defn days-of-month-that-is [week-day]
(comp
(partial
filter
(partial is-week-day? week-day))
dates-in-month))
(defn day-teenth [week-day]
(comp vec
vals
first
(partial filter #(is-teenth? %))
(days-of-month-that-is week-day)))
(defn third [ls] (nth ls 2))
(defn fourth [ls] (nth ls 3))
(defn get-week-day [pos week-day]
(comp vec
vals
pos
(days-of-month-that-is week-day)))
(doall
(map
#(intern 'meetup (symbol (str (name %) "teenth")) (day-teenth %))
(keys week-days)))
(def func-names ["first" "second" "third" "fourth" "last"])
(doall
(map
#(intern
'meetup
(symbol (str (first %) "-" (name (second %)) "day"))
(get-week-day (resolve (symbol(first %))) (second %)))
(for [func-name func-names
week-day (keys week-days)]
[func-name week-day])))
view raw meetup2.clj hosted with ❤ by GitHub


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:

'use strict';
var ArrayRotation = require("../src/ArrayRotation.js").ArrayRotation;
describe("Array rotation in place", function() {
it("An empty array does not change", function() {
var originalArray = [];
ArrayRotation.rotateInPlace(
originalArray, 3
);
expect(originalArray).toEqual([]);
});
it("A rotation by 0 steps does not change the array", function() {
var originalArray = [1, 2];
ArrayRotation.rotateInPlace(
originalArray, 0
);
expect(originalArray).toEqual([1, 2]);
});
it("A rotation by a number of steps that is less than the array size", function() {
var originalArray = [1, 2, 3, 4];
ArrayRotation.rotateInPlace(
originalArray, 2
);
expect(originalArray).toEqual([3, 4, 1, 2]);
});
});

and this is the corresponding code:

'use strict';
var ArrayRotation = {
rotateInPlace: function(array, steps) {
var i, step,
size = array.length;
if (size === 0) {
return;
}
for (step = 0; step < steps; step++) {
for (i = 1; i < size; i++) {
swap(0, i);
}
}
function swap(position1, position2) {
var temp = array[position1];
array[position1] = array[position2];
array[position2] = temp;
}
}
};
module.exports.ArrayRotation = ArrayRotation

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:

'use strict';
var ArrayRotation = {
rotateInPlace: function(array, steps) {
var i, step,
size = array.length;
if (size === 0) {
return;
}
for (step = 0; step < steps; step++) {
for (i = 1; i < size; i++) {
this.swap(array, 0, i);
}
}
},
swap: function(array, position1, position2) {
var temp = array[position1];
array[position1] = array[position2];
array[position2] = temp;
}
};
module.exports.ArrayRotation = ArrayRotation

in order to spy on it:

'use strict';
var ArrayRotation = require("../src/ArrayRotation.js").ArrayRotation;
describe("Array rotation in place", function() {
it("An empty array does not change", function() {
var originalArray = [];
ArrayRotation.rotateInPlace(
originalArray, 3
);
expect(originalArray).toEqual([]);
});
it("A rotation by 0 steps does not change the array", function() {
var originalArray = [1, 2];
ArrayRotation.rotateInPlace(
originalArray, 0
);
expect(originalArray).toEqual([1, 2]);
});
it("A rotation by a number of steps that is less than the array size", function() {
var originalArray = [1, 2, 3, 4];
ArrayRotation.rotateInPlace(
originalArray, 2
);
expect(originalArray).toEqual([3, 4, 1, 2]);
});
it("A rotation by a number of steps that is greater or equal than the array size", function() {
var originalArray = [1, 2, 3, 4];
spyOn(ArrayRotation, 'swap').andCallThrough();
ArrayRotation.rotateInPlace(
originalArray, 6
);
expect(originalArray).toEqual([3, 4, 1, 2]);
expect(ArrayRotation.swap.callCount).toBe(6);
});
});

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:

'use strict';
var ArrayRotation = {
rotateInPlace: function(array, steps) {
var i, step,
size = array.length;
if (size === 0) {
return;
}
for (step = 0; step < steps % size; step++) {
for (i = 1; i < size; i++) {
this.swap(array, 0, i);
}
}
},
swap: function(array, position1, position2) {
var temp = array[position1];
array[position1] = array[position2];
array[position2] = temp;
}
};
module.exports.ArrayRotation = ArrayRotation

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:

'use strict';
var ArrayRotation = {
rotateInPlace: function(array, steps) {
var i, step,
size = array.length;
if (size === 0) {
return;
}
for (step = 0; step < steps % size; step++) {
for (i = 1; i < size; i++) {
swap(0, i);
}
}
function swap(position1, position2) {
var temp = array[position1];
array[position1] = array[position2];
array[position2] = temp;
}
}
};
module.exports.ArrayRotation = ArrayRotation

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

'use strict';
var ArrayRotation = require("../src/ArrayRotation.js").ArrayRotation;
describe("Array rotation in place", function() {
it("An empty array does not change", function() {
var originalArray = [];
ArrayRotation.rotateInPlace(
originalArray, 3
);
expect(originalArray).toEqual([]);
});
it("A rotation by 0 steps does not change the array", function() {
var originalArray = [1, 2];
ArrayRotation.rotateInPlace(
originalArray, 0
);
expect(originalArray).toEqual([1, 2]);
});
it("A rotation by a number of steps that is less than the array size", function() {
var originalArray = [1, 2, 3, 4];
ArrayRotation.rotateInPlace(
originalArray, 2
);
expect(originalArray).toEqual([3, 4, 1, 2]);
});
it("A rotation by a number of steps that is greater or equal than the array size", function() {
var originalArray = [1, 2, 3, 4];
//spyOn(ArrayRotation, 'swap').andCallThrough();
ArrayRotation.rotateInPlace(
originalArray, 6
);
expect(originalArray).toEqual([3, 4, 1, 2]);
// expect(ArrayRotation.swap.callCount).toBe(6);
});
});

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:

'use strict';
var ArrayRotation = require('../src/ArrayRotation.js').ArrayRotation;
Array.prototype.rotate = function(steps) {
ArrayRotation.rotateInPlace(this, steps);
};
describe("Array rotation in place", function() {
it("A rotation by any number of steps on an empty array has no effect", function() {
var originalArray = [];
originalArray.rotate(3);
expect(originalArray).toEqual([]);
});
it("A rotation by 0 steps on a non-empty array has no effect", function() {
var originalArray = [1, 2];
originalArray.rotate(0);
expect(originalArray).toEqual([1, 2]);
});
it("A rotation by non-zero steps on a non-empty array works as expected", function() {
var originalArray = [1, 2, 3, 4];
originalArray.rotate(6);
expect(originalArray).toEqual([3, 4, 1, 2]);
});
});

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.

(ns grains)
(defn- grains []
(letfn
[(f [n]
(seq [n (fn [] (f (* 2 n)))]))]
(f 1N)))
(defn- stream-for-n-steps [stream n]
(letfn
[(f [i stream-rest]
(let
[pair (stream-rest)]
(when (not= i 0)
(cons (first pair)
(f (- i 1) (second pair))))))]
(f n stream)))
(defn square [sqr-num]
(last (stream-for-n-steps grains sqr-num)))
(defn total []
(reduce + 0 (stream-for-n-steps grains 64)))
view raw grains.clj hosted with ❤ by GitHub

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:

#lang racket
(define (grains)
(letrec
([f
(lambda (n)
(cons n
(lambda () (f (* 2 n)) )))])
(f 1)))
(define (stream-for-n-steps stream n)
(letrec ([f
(lambda(i stream-rest)
(if (= i 0)
empty
(cons (car (stream-rest))
(f (- i 1) (cdr (stream-rest))))))])
(f n stream)))
(define (square sqr-num)
(last (stream-for-n-steps grains sqr-num)))
(define total-grains
(lambda ()
(foldr + 0 (stream-for-n-steps grains 64))))
view raw grains.rkt hosted with ❤ by GitHub

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:

#lang racket
(define (grains)
(letrec
([f
(lambda (n)
(cons n
(lambda () (f (* 2 n)) )))])
(f 1)))
(define (stream-for-n-steps stream n)
(letrec ([f
(lambda(i stream-rest)
(if (= i 0)
empty
(cons (car (stream-rest))
(f (- i 1) (cdr (stream-rest))))))])
(f n stream)))
(define (square sqr-num)
(last (stream-for-n-steps grains sqr-num)))
(define total-grains
(lambda ()
(foldr + 0 (stream-for-n-steps grains 64))))
view raw grains.rkt hosted with ❤ by GitHub

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:

(ns space-age)
(defn on-earth [seconds]
(let
[seconds-per-earth-year 31557600.0]
(/ seconds seconds-per-earth-year)))
(defn on-mercury [seconds]
(let
[orbital-period-in-earth-years 0.2408467]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(defn on-venus [seconds]
(let
[orbital-period-in-earth-years 0.61519726]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(defn on-mars [seconds]
(let
[orbital-period-in-earth-years 1.8808158]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(defn on-jupiter [seconds]
(let
[orbital-period-in-earth-years 11.862615]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(defn on-saturn [seconds]
(let
[orbital-period-in-earth-years 29.447498]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(defn on-uranus [seconds]
(let
[orbital-period-in-earth-years 84.016846]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(defn on-neptune [seconds]
(let
[orbital-period-in-earth-years 164.79132]
(/ (on-earth seconds) orbital-period-in-earth-years)))
view raw space-age1.clj hosted with ❤ by GitHub

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:

(ns space-age)
(defn on-earth [seconds]
(let
[seconds-per-earth-year 31557600.0]
(/ seconds seconds-per-earth-year)))
(defn make-on-planet-function [orbital-period-in-earth-years]
(let
[inv-period (/ 1.0 orbital-period-in-earth-years)]
(comp (partial * inv-period) on-earth)))
(def on-mercury (make-on-planet-function 0.2408467))
(def on-venus (make-on-planet-function 0.61519726))
(def on-mars (make-on-planet-function 1.8808158))
(def on-jupiter (make-on-planet-function 11.862615))
(def on-saturn (make-on-planet-function 29.447498))
(def on-uranus (make-on-planet-function 84.016846))
(def on-neptune (make-on-planet-function 164.79132))
view raw space-age2.clj hosted with ❤ by GitHub

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

(ns space-age)
(defn on-earth [seconds]
(let
[seconds-per-earth-year 31557600.0]
(/ seconds seconds-per-earth-year)))
(defn make-on-planet-function [orbital-period-in-earth-years]
(fn [seconds]
(/ (on-earth seconds) orbital-period-in-earth-years)))
(def on-mercury (make-on-planet-function 0.2408467))
(def on-venus (make-on-planet-function 0.61519726))
(def on-mars (make-on-planet-function 1.8808158))
(def on-jupiter (make-on-planet-function 11.862615))
(def on-saturn (make-on-planet-function 29.447498))
(def on-uranus (make-on-planet-function 84.016846))
(def on-neptune (make-on-planet-function 164.79132))
view raw space-age3.clj hosted with ❤ by GitHub

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:

(ns etl)
(defn transform [data-set]
(reduce
(fn [data [letters num]]
(reduce
(fn [data letter]
(assoc
data
(clojure.string/lower-case letter)
num))
data
letters))
{}
(zipmap (vals data-set) (keys data-set))))
view raw etl0.clj hosted with ❤ by GitHub

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:

(ns etl (:require [clojure.string :as str]))
(defn transform [data-set]
(let
[assoc-pairs
(fn [data [letters num]]
(reduce
#(assoc %1 (str/lower-case %2) num)
data
letters))]
(reduce
assoc-pairs
{}
(zipmap (vals data-set) (keys data-set)))))
view raw etl1.clj hosted with ❤ by GitHub

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

(ns etl (:require [clojure.string :as str]))
(defn transform [letters-per-score]
(let
[associate-score-to-letters
(fn [scores-per-letter [letters score]]
(let
[associate-score-to-letter
(fn [scores-per-letter letter]
(assoc
scores-per-letter
(str/lower-case letter)
score))]
(reduce
associate-score-to-letter
scores-per-letter
letters)))]
(reduce
associate-score-to-letters
{}
(zipmap
(vals letters-per-score)
(keys letters-per-score)))))
view raw etl2.clj hosted with ❤ by GitHub

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):

(define (average x y)
(/ (+ x y) 2))
(define (custom_sqrt x)
(define (sqrt_iter previous_guess guess)
(if (good_enough? previous_guess guess)
guess
(sqrt_iter guess
(improve guess))))
(define (good_enough? previous_guess guess)
(< (abs (- previous_guess guess))
0.001))
(define (improve guess)
(average guess (/ x guess)))
(sqrt_iter 0.0 1.0))

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:

(ns leap)
(defn leap-year? [year]
(let
[divisible-by? (comp zero? (partial rem year))
(or
(divisible-by? 400)
(and
(divisible-by? 4)
(not (divisible-by? 100))))))
view raw leap.clj hosted with ❤ by GitHub

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:

(ns robot)
(defn robot []
(atom {:name ""}))
(defn robot-name [robot]
(let
[current-name (:name @robot)
random-name
(fn []
(let
[capital-letters
(map char (range (int \A) (+ (int \Z) 1)))
num-letters
(count capital-letters)]
(apply
str
(concat
(repeatedly
2
#(nth capital-letters (rand-int num-letters)))
(repeatedly
3
#(rand-int 10))))))]
(if (empty? current-name)
(:name (swap! robot assoc :name (random-name)))
current-name)))
(defn reset-name [robot]
(swap! robot assoc :name ""))
view raw robot-name.clj hosted with ❤ by GitHub

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:

(ns robot)
(def ^:private capital-letters
(map char (range (int \A) (+ (int \Z) 1))))
(defn- random-name []
(str
(rand-nth capital-letters)
(rand-nth capital-letters)
(rand-int 1000)))
(defn robot []
(atom {:name ""}))
(defn robot-name [robot]
(let
[current-name (:name @robot)]
(if (empty? current-name)
(:name (swap! robot assoc :name (random-name)))
current-name)))
(defn reset-name [robot]
(swap! robot assoc :name ""))
view raw robot1.clj hosted with ❤ by GitHub

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:

(ns rpn.t-core
(:use midje.sweet)
(:use [rpn.core]))
(facts
"about RPN calculator"
(fact
"a number evaluates to itself"
(evaluate "0") => 0
(evaluate "1") => 1)
(fact
"it adds several numbers"
(evaluate "0 1 +") => 1
(evaluate "1 2 5 + +") => 8)
(fact
"it subtracts several numbers"
(evaluate "0 1 -") => -1
(evaluate "1 2 5 - -") => 4)
(fact
"it multiplies several numbers"
(evaluate "0 1 *") => 0
(evaluate "1 2 5 * *") => 10)
(fact
"it divides several numbers (integer division)"
(evaluate "4 2 /") => 2
(evaluate "10 5 5 / /") => 10)
(fact
"it computes an expression with several operators"
(evaluate "4 2 / 5 + 10 * 5 6 - +") => 69
(evaluate "3 2 1 + *") => 9
(evaluate "1 2 + 4 * 5 + 3 -") => 14
(evaluate "5 1 2 + 4 * + 3 -") => 14
(evaluate "0 1 - 4 5 * *") => -20))
view raw rpn-tests.clj hosted with ❤ by GitHub

I really love how readable tests are when using Midje.

And this is the final version of the code:

(ns rpn.core
[:use [clojure [string :only [split]]]])
(defn parse-int [s]
(Integer/parseInt (re-find #"\A-?\d+" s)))
(defn parse [expression]
(let
[operators {"+" + "-" - "*" * "/" quot}
parse-token
(fn [token]
(if (contains? operators token)
(get operators token)
(parse-int token)))]
(map parse-token
(split expression #"\s"))))
(defn process-symbol [stack symbol]
(if (number? symbol)
(conj stack symbol)
(conj (pop (pop stack))
(apply symbol (take-last 2 stack)))))
(defn evaluate [expression]
(peek
(reduce
process-symbol
[]
(parse expression))))
view raw rpn.clj hosted with ❤ by GitHub

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:

(ns school)
(defn grade [school grade-num]
(get school grade-num []))
(defn add [school name grade-num]
(assoc
school
grade-num
(conj (grade school grade-num) name)))
(defn sorted [school]
(into {}
(map
(fn [[grade students]]
[grade (sort students)])
(sort-by key school))))
view raw school1.clj hosted with ❤ by GitHub

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:

(ns school)
(defn grade [school grade-num]
(get school grade-num []))
(defn add [school name grade-num]
(assoc
school
grade-num
(conj (grade school grade-num) name)))
(defn sorted [school]
(let
[sort-by-grades
(partial sort-by key)
sort-students-by-name
(partial map
(fn [[grade students]]
[grade (sort students)]))]
(into
{}
(sort-students-by-name
(sort-by-grades school)))))
view raw school2.clj hosted with ❤ by GitHub

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

(ns school)
(defn grade [school grade-num]
(get school grade-num []))
(defn add [school name grade-num]
(assoc
school
grade-num
(conj (grade school grade-num) name)))
(defn sorted [school]
(let
[sort-by-grades
(partial sort-by key)
sort-students-by-name
(partial map
(fn [[grade students]]
[grade (sort students)]))]
(into
{}
(->
school
sort-by-grades
sort-students-by-name))))
view raw school3.clj hosted with ❤ by GitHub

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:

(ns phone)
(defn extract-digits [phone-number]
(let
[digits (filter #(Character/isDigit %) phone-number)
digits-length (count digits)]
(cond
(= digits-length 10) digits
(and (= digits-length 11)
(= (first digits) \1)) (rest digits)
:else (repeat 10 0))))
(defn number [phone-number]
(apply str (extract-digits phone-number)))
(defn area-code-digits [phone-number]
(take 3 (extract-digits phone-number)))
(defn area-code [phone-number]
(apply str (area-code-digits phone-number)))
(defn pretty-print [number-to-print]
(let
[digits (extract-digits number-to-print)]
(apply str
(concat "(" (area-code-digits digits) ") "
(drop 3 (take 6 digits))
"-"
(drop 6 (take 10 digits))))))
view raw phone1.clj hosted with ❤ by GitHub

And then a second one:

(ns phone)
(defn extract-digits [phone-number]
(let
[digits (filter #(Character/isDigit %) phone-number)
digits-length (count digits)]
(cond
(= digits-length 10) digits
(and (= digits-length 11)
(= (first digits) \1)) (rest digits)
:else (repeat 10 0))))
(def to-str
(partial apply str))
(def number
(comp to-str extract-digits))
(def area-code-digits
(comp (partial take 3) extract-digits))
(def area-code
(comp to-str area-code-digits))
(def extension-digits
(comp (partial drop 3) (partial take 10)))
(defn pretty-extension [extension-digits]
(to-str
(concat
(take 3 extension-digits)
"-"
(drop 3 extension-digits))))
(defn pretty-area-code [area-code]
(to-str "(" area-code ")"))
(defn pretty-print [number-to-print]
(let
[digits (extract-digits number-to-print)]
(to-str
(pretty-area-code (area-code digits))
" "
(pretty-extension (extension-digits digits)))))
view raw phone2.clj hosted with ❤ by GitHub

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:

(ns dna)
(defn hamming-distance [strand1 strand2]
(reduce
+
(map
(fn [base1 base2]
(if (= base1 base2) 0 1))
strand1
strand2)))
view raw hamming.clj hosted with ❤ by GitHub

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

class Hamming
def self.compute(strand1, strand2)
def self.base_distance(base1, base2)
def self.both_exists?(base1, base2)
not [base1, base2].any? {|base| base.nil?}
end
(both_exists?(base1, base2) and base1 != base2) ? 1 : 0
end
strand1.chars.zip(strand2.chars).map do |base1, base2|
base_distance(base1, base2)
end.reduce(:+)
end
end
view raw hamming.rb hosted with ❤ by GitHub

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.