Constraint programming is a style of programming where relations between variables are stated in the form of constraints. Constraints differ from the common primitives of other programming languages in that they do not specify a step or sequence of steps to execute but rather the properties of a solution to be found. If you want use a constraint-specific programming language, you should consider something like Prolog. If however you like Groovy but want to apply some constraint style magic, read on.
Gecode/J is a Java interface for the Gecode C++ constraint programming library. Let's have a look at making the Money example from the Gecode/J library a bit Groovier.
A little helper library
First we create a little helper library to make our Groovy code a little cleaner:
A Groovy Solution
Running this code (we used the latest HEAD version of Groovy on Java 6 with the following JVM argument,
Running the program with the
-gui command line argument yields the following GUI display:
It would be fun to take the example a little further with a proper DSL to define the constraints.