This post will present my solutions for day 2 of the prolog chapter of the excelent book seven languages in seven weeks:
After the basic introduction of day 1, day 2 dives into unifications and recursions. It took me quite some time to get used to Prolog, especially the fact that you don’t return values from the rules, but pass in a param. Of course this makes sense if you look at prolog and logical-languages in general, because you want to create logical statements that are true or false. Then you can use the statement with a variable to see which value the variable have to be to make the statement true.
Anyways here are my solutions.
Reverse a list
nothing really special, I started with the empty list, then list with 1 member and continued, until it was clear how the regression part should be implemented.
Here are the run results on ideone: http://ideone.com/RZRvY/.
(BTW, if anyone knows how to combine gists and ideone run in wordpress it would be greatly appreciated).
tracing
in GnuProlog you can easily enable tracing with the command:
trace.
I really needed this for the next two exercises.
smallest
I came up with a solution for the smallest number in a list, but it it wasn’t satisfactory because Prolog is not sure there is one answer. It will give you the option to see al posibilities, but there is just one. Bit strange, so if someone who reads this can point out what causes this I will be very gratefull.
After some googling and I found this solution.
Restults at ideone.com
This one has almost the same problem if you pass in a list of 1,2 or 3 elements it works fine. But if you pass in 4 elements it will also ask you if you want more solutions, while there are none.
Update:
My colleague Mark van der Voort helped me find a real solution for the smallest:
The ! is used in prolog to indicate that it does not have to search for other solutions anymore.
Results at ideone
sort
I could not figure this one out on my own, and looked up some insert sort sample which I then adjusted to my taste.
here it is.
conclusion
I still like the power prolog gives you but had quite some problems implementing the exercises. I’m not sure if a solution is right when it asks you if you want to see more solutions for What. I doubt it anyway.
Next chapter seems interesting, letting the computer solve a sudoku.
