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.