Groovy Bar & Grill

December 9, 2008

Fibonacci.groovy

Filed under: Groovy Grill — jawild59 @ 6:49 pm

One of the ugliest constructs in Java is the for loop. The enhanced for in Java 5 improved readability but Groovy has alternatives that are even better. Let’s take a look. Here is Java code (from Java Examples in a Nutshell, 2nd Ed.) that prints the first 20 Fibonacci numbers:


public class Fibonacci {
  public static void main(String[] args) {
    int n0 = 1, n1 = 1, n2;
    System.out.print(n0 + " " + n1 + " ");

    for (int i = 0; i < 18; i++) {
      n2 = n1 + n0;
      System.out.print(n2 + " ");
      n0 = n1;
      n1 = n2;
    }
  }
}
  

Typical stuff; for is utilized to execute a loop a certain number of times, in this case eighteen. Groovy handles this much better.


def list = [01]

20.times {
  print "${list.last()} "
  list << list.sum()
  list = list.tail()
}

Because everything’s an object in Groovy, 20 is an Integer with all the extra methods supplied by the GDK. The times() method effectively executes the closure 20.intValue() number of times.

There’s some cool stuff going on with the Groovy list too; Instead of using 3 variables to track 2 values, we use a variable size list. Each iteration of the closure prints the last element in the list. Next, we sum up all the list elements and push the value onto the end of the list. list.trail() then lops off the first element in the list so we’re left with the next two numbers in the Fibonacci series.

1 Comment »

  1. This is neat! I like the .sum() and .tail() methods on the list. Ya learn somethin’ new every day!

    Comment by Steve — December 19, 2008 @ 11:49 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.