Introduction to Groovy
In this article I am going to present a brief introduction to the Groovy programming language. Groovy can be very beneficial to the artificial intelligence programmer. When training a neural network for pattern recognition it is often necessary to pre-process the data considerably before training the neural network. This is particularly true for temporal pattern recognition. Additionally control and training sets must be established, often by statistical analysis. Groovy allows you to very quickly create such code in a scripted way, without all of the ceremony of regular Java. Then regular Java code can be used to perform the processor intensive training and recognition tasks of the neural network.
I will follow this article up with some actual examples of pre-processing data before presenting to the Encog Framework. This article assumes that you are already familiar with the Java programming language. I will discuss Groovy in general, and not go into the specifics of neural network programming. This will be a topic for later articles. This article would be a good starting point to adapt other neural network articles I've written to Groovy.
Start up the Groovy Console
Groovy comes with a handy Swing application called the Groovy console. This console can be used to construct and experiment with the Groovy system. In this tutorial we will make use of the Groovy console. You can see the Groovy console here.

The Groovy console is very easy to use. There are two panes, the top and bottom. Use the top pane to enter a Groovy script. Use the bottom pane to view the output from the top Groovy script. Simply enter your code into the top pane and click "run script". You will see the output produced in the bottom pane.
Groovy is Java
Lets start with "Hello World". Here is a simple "Hello World" application written in Groovy.
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello Groovy!");
}
}Look familiar? Its also Java code. Most Java code will compile under Groovy. It may not run the same way. All Java code will run the same way under Groovy if you simply link to Java JAR files compiled by javac. However, if you recompile your Java code under Groovy, in some cases you will get different results. In some cases the Java code will not even compile under Groovy. Consider the minor change to the above program.
public class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello Groovy!");
}
}This probably looks almost the same to you. But it is different. Notice the placement of the square brackets on the main function declaration. They are on the identifier, not on the type. This placement, though discouraged, is perfectly valid in Java. It is illegal in Groovy, and thus, the above code sample will not compile.
Java has much ceremony and overhead to get something done. Groovy seeks to eliminate. This class could be simplified considerably under Groovy. Consider the following Groovy version of the above class.
class HelloWorld {
static main( args ){
println "Hello World!"
}
}The above class follows exactly the same structure as the Java version. But this is not a Java version, this will not compile under Java. It shows how Groovy is more concise than Java.
Groovy is dynamically typed, so we were able to get rid of the type information on the main function declaration, even the return type. Semicolons are optional. Additionally, every Groovy object has direct access to the println method.
For a simple Groovy script you can do away with classes altogether, and simply use the following as your program.
println "Hello World!"
Groovy and GStrings
There are two types of string in the Groovy programming language. Regular Java Strings are supported, but there is also a new string type called a GString. A GString is declared by using double quotes. A regular Java string uses single quotes.
There are many new features in the new GString. One is the dollar sign usage in a GString. The dollar sign has special meaning in a GString. Consider the following script.
name = "Jeff" println "Hello $name!"
This works better than having to use +'s to tie everything together. You can use curly brackets with dollar signs to group expressions together.
println "1 + 1 = ${1+1}"If you want to actually print a dollar sign, simply use the following.
println "You made \$1.20"
Functions and Return Statements
Functions work a little different than they did in Java. Return types do not need to be specified. Types for parameters do not need to be specified either. Consider the following program.
class HelloWorld {
def greet( name ){
"Hello ${name}!"
}
}
hm = new HelloWorld()
println hm.greet("Jeff")Notice there is no return statement in the greet function? The last line of the function is assumed to be the return value for that function.
Groovy supports string buffer's in a unique way. Using the <<= operator allows text to be appended to a string. Of course if << is used on an actual string, then a StringBuffer is returned.
def str = "Hello World" str <<= '!' str <<= '!' println str println str.class.name
This will print "Hello World!!", and will note that the type of str is StringBuffer. Note, future versions of Groovy may switch this to StringBuilder, since as of JDK 1.5 the use of StringBuilder is preferable.
Closures
Closures are perhaps one of the most important features of Groovy. In the most simple form, a closure looks something like this.
def c = {
println "This is the closure"
}
c()The above code creates a closure that is held by the variable c. The closure is then executed. The power of closures comes in that these closures can be passed around the program.
Closures can have parameters. The syntax for parameters can look a bit odd if you've never seen it before. If you have only one parameter it would look something like this.
def c = { print it }
c( "Jeff" ) This will simply print "Jeff". Notice the code in the closure. It uses a special reserved word named "it". If you have a closure with only one parameter, simply use the keyword "it" to reference it.
For two or more parameters they need to be named.
def c = { person1, person2 -> print "Hello $person1 and $person2" }
c( "Jeff", "John" )Notice the -> ? It is what separates the parameters from the rest of the closure. List all parameters before it, comma separated.
Closures as Parameters
Closures can be passed around the program as parameters. Consider the following program.
def list = ['a','b','c','d']
def newList = []
def c = { it.toUpperCase() }
list.collect( newList, c )
assert newList == ["A", "B", "C", "D"]The above program takes a list of letters. It will then convert them to upper case. The first line of this program creates a Java list of strings, note the shorthand used to create it. An empty new list is also created. A closure is created that will accept a single parameter and return it as an upper case parameter. This closure is named "c". The collect method is called on the list, passing in the new list and the closure. The collect method accepts two parameters. The first is a new list that is to receive the values from the old. The second is a closure that is allowed to operate on each of the old values before it is collected into the list. This allows you to quickly perform an operation, specified by the closure, on every member of a list while copying it into a new list.
Because the closure is the last parameter a special shorthand is allowed. Because of this closures are almost always the last parameter. Consider the following code, which does the same thing.
def list = ['a','b','c','d']
def newList = []
list.collect( newList ) {
it.toUpperCase()
}
println newListThis syntax seemed very strange to me as a Java programmer, when I saw it for the first time. But it is really nothing more than passing a closure in for the last argument.
Ranges
Ranges are another very interesting feature of Groovy. They allow you to specify a range of numbers or letters. Consider the following code, which uses a range to print each value.
( 1 .. 10 ).each { println it }This is a single line program, but there really is quite a bit going on. A range and closure are used together. First a range is created that holds the values between 1 and 10. The method named "each" is being called on the range object. Most collection type objects contain a "each" method. This acts like a "for each" in other programming languages. The "each" method accepts a single parameter, a closure. Because the closure is the last(and only) parameter for "each" method, the shorthand we just saw can be used. The closure is specified inline, between the curly brackets. In this case we simply print out the single parameter being passed to the closure. The "each" method passes a single parameter, which is the element currently being iterated over. Therefore the "println it" prints out each member of the collection.
Ranges can also work with letters. Consider the following.
( 'a' .. 'c' ).each { println it }The above code prints out "a", "b", and "c" on different lines.
Ranges can also be useful for switch/case statements. Consider the following.
def age = 15
switch(age)
{
case 0..10:
println "You are under 10 years old."
break
case 11..20:
println "You are between 11 and 20."
break
case 21..30:
println "You are between 21 and 30."
break
}Lists
Lists are very easy to define and use in Groovy. The following code creates a list of numbers and then displays them.
def numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
numbers.each {
println it;
}
The above code first creates a list of numbers. A closure that prints out each element is then sent to the "each" method.
It is also very easy to add numbers to the list.
def numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
numbers << 11;
numbers << 12;
numbers.each {
println it;
}Maps
Maps are very easy to declare inline. The following code declares a simple map that maps the abbreviation for each of the days of the week to the full name for that day of the week.
def map = [
'MON': 'Monday',
'TUE' : 'Tuesday',
'WED' : 'Wednesday',
'THR' : 'Thursday',
'FRI' : 'Friday',
'SAT' : 'Saturday' ]
println map['MON']
println map.MONOf course you can use the "each" method to iterate over the keys of the above map.
def map = [
'MON': 'Monday',
'TUE' : 'Tuesday',
'WED' : 'Wednesday',
'THR' : 'Thursday',
'FRI' : 'Friday',
'SAT' : 'Saturday' ]
map.each {
println it
}Maps can also be used to create named parameters.
Maps as Named Parameters
Much of the map syntax is optional, this allows Groovy to support named parameters, such as this.
def calculate(params)
{
println "x is $params.x"
println "y is $params.y"
}
calculate( x: 20, y: 30 )This feature of Groovy is very commonly used in the builders.
Variable Parameter Lists
Arrays can be used to support variable parameter functions. Useful for when you do not know how many parameters are going to be passed.
def calculate(int[] list)
{
int i=0
list.each {
println "Param $i is ${list[i]}"
i++
}
}
calculate( 1,2,3 )
Getters and Setters in Groovy
Getters and setters are much easier in Groovy. No need to type pages and pages of get/set methods for properties that have simple access. Consider the following class.
class MyClass
{
int myInt;
static main(args)
{
MyClass c = new MyClass()
c.myInt = 2;
println c.myInt
}
}You might say, you can do this in Java as well? It looks like we simply broke the rules of OOP and simply implemented an accessible property. However, there are getters and setters generated behind the scene. If you used a hybrid approach and called this class from regular Java, you would have to use the generated getter.
This is fine for simple classes. But what if you need to abstract the way in which myInt is set? Maybe you want to impose a range between 1-10.
class MyClass
{
int myInt
void setMyInt(int i)
{
if( i>=1 && i<=10 )
{
this.myInt = i
}
else
throw RuntimeException("Setting out of range")
}
static main(args)
{
MyClass c = new MyClass()
c.myInt = 2
println c.myInt
c.myInt = 100
}
}The power here is that we have introduced a setter, but we did not need to modify any of the code that thought that it was accessing the property directly.



