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:

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:

and these are the tests using Midje:

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:

and these are the tests using Midje:


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

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

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:

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

and this is the new function's code:

Once I had the new function I used it inside both keep-being-cells and new-cells functions to highlight the duplication between them:

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:

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:

and this is the resulting code:

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:

and this is the code:

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

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:


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

Caesar Cipher in Haskell

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:

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:

and this is the new one:

Wednesday, November 12, 2014

Euler Project: Problem 2 in Haskell

This is my solution in Haskell to the second problem:


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:


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:


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:


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:


and this is the code:


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:


And this is the last version of the code:


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:

I used a list comprehension.

Another way using also a lambda to create a helper:



Bonus: Two ways to do the same in Clojure:

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:


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


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:


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


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:


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

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:


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:


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:

Euler Project: Problem 4 in Clojure

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


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:


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:


and this is the code:


It's possible to convert numbers over 3999:


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.


I added some extra tests to complete the provided ones:


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

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:


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.

  2. A map function for a list which can contain arbitrarily deeply nested lists.

  3. A filter function for a list which can contain arbitrarily deeply nested lists.

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:


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


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:


and the code:


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:


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:


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:


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:


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


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.


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:

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:


In this case life is much easier in Ruby :)

Exercism: "Gigasecond in Clojure"

This is my solution to the Gigasecond problem in Clojure.


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:


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


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:


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:


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

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

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

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

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

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



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

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

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

Wednesday, July 23, 2014

A bit about JavaScript functions

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

These are the talk slides.

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

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

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

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

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

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

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

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

Thursday, July 17, 2014

Kata: Rotate an array in place in JavaScript

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

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

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

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

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

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


and this is the corresponding code:


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

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

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


in order to spy on it:


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

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


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

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


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


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

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


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

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

Thursday, July 10, 2014

Exercism: "Grains in Clojure"

This is my solution to the Grains problem in Clojure.


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

This was the Racket version:


As you see they are quite different.

letfn is somehow equivalent to Racket's letrec.

My biggest problem was with cons because they behave different.

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

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

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

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

Grains problem in Racket using a home-made stream

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


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

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

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

Now I want to do something similar in Clojure.

Tuesday, July 8, 2014

Exercism: "Space Age in Clojure"

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

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


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


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


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

Saturday, July 5, 2014

Exercism: "Extract-Transform-Load in Clojure"

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

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


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

It works but it's not very readable.

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


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


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

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


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

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

Exercism: "Leap year in Clojure"

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


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

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

Friday, July 4, 2014

Exercism: "Robot name in Clojure"

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


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

It also helped me to discover the repeatedly function.

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

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

Update:

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


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

You can nitpick this new version here.

Kata: Reverse Polish Notation Calculator in Clojure with Midje

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

These are the tests:


I really love how readable tests are when using Midje.

And this is the final version of the code:


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

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

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

Thursday, July 3, 2014

Exercism: "Grade School in Clojure"

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

The first working version:


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

This is the resulting version:


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


I think the -> macro is great.

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

Exercism: "Phone Number in Clojure"

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

The first version:


And then a second one:


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

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

Interesting Talk: "Failure for Fun and Profit!"

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

Wednesday, July 2, 2014

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

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


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


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

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