TDD and TPP applied to Prolog
Some months before, I have rediscovered Prolog with a more Craft point of view. When I learnt it at school, it was more introduced as a toy language for understanding logic programming rather than a industrial-ready tool.
However, you can have a Craft approach to Prolog as you would do for other languages.
From this point, I assume you have a basic knowledge of Prolog and logic programming.
Test framework
Build your own TF!
As I re-entered the Prolog world with a Craft view, I decided to create my test framework. Yeah!. In prolog, you can easily create an assertEquals:
The first predicate indicates that if we can unified the second argument with the third, everything is OK. The second predicate does the opposite. Simple and convenient.
I’m using swipl. If you don’t like my wonderful test framework ;), you can use the built-in one shipped with swipl
Test framework in swi-pl
Examples are based on the riddle of the wolf, the cabbage and the cabbage that have to cross a river.
You start by enclosing your tests between two tags :
Then, you can add your tests:
And a failing test:
You can then load and run your tests from the swipl program:
$ swipl
?- consult("cabbage.pl"), run_tests(cabbage).
% PL-Unit: cabbage ................. done
% All 17 tests passed
true.
For more information, check the unit test page.
TDD
Red - Green - Refactor
The basic first thing in TDD is the cycle “Red-Green-Refactor”.
First, we write a failing test:
Then, we need to make it pass as fast as we can. Here, he most simple solution is to introduce a constant:
Then, we need to refactor. Here, we can’t really have something better. So let’s add another failing test:
And, we introduce another predicate :
Now, we can refactor. We should look for duplication. Here, we have goat which is a member of both predicates:
Yes, we did it.
Transformation Priority Premise
Transformation Priority Premise is a programming approach defined by Robert C. Martin. The idea is to apply the simpler transformation to your code to make the new test pass.
We can transpose this approach to prolog:
- {} ==> simple predicate with constant
- simple predicate ==> failing predicate (rule with fail)
- predicate ==> anonymous variable
- predicate ==> simple unifiable variable (equals(X, X))
-
predicate ==> recursive unifiable variable (equals(X, [X T])) - variable ==> variable with domain (ins/in)
- predicate ==> rule (with a body)
- predicate ==> comparaison
- predicate ==> recursion
- predicate ==> cut
- predicate ==> operation (X is X+1)
This is just a proposition. I’m looking forward for your comments :).