Groovy Fizz and Buzz 6

Posted by Frederic Jean Thu, 28 Feb 2008 06:57:02 GMT

The FizzBuzz programming interview question raised it's head again. I've managed to resist the temptation to implement it in any languages so far. Until this morning that is...

So I fired up the Groovy Console and played a little. A nice feature of the console is that it displays a history of the scripts it ran. This allows me to present an evolution of my FizzBuzz program.

I first started with a rather naive implementation:

              (1..100).each { 
                def out = "" 
                if ((it % 3) == 0) { out += "Fizz" } 
                if ((it % 5) == 0) { out += "Buzz" } 
                if (out == "" ) { out = it } 
                println out
              }
              

Not bad for something that I came up with in about 10 minutes. It doesn't really take advantage of Groovy's features though. So I refined it a bit by using the ternary operator:

              (1..100).each {
                def out = (it % 3) == 0 ? "Fizz" : ""
                out += (it % 5) == 0 ? "Buzz" : ""
                println (out == "" ? it : out)
              }
              

This is a slight improvement over the first version. I still didn't feel that this was Groovy enough for me. I decided to play with the List collect method. This applies a closure to all items in a collection. The first pass was the following code segment:

              println ((1..100).collect {
                def out = (it % 3) == 0 ? "Fizz" : ""
                out += (it % 5) == 0 ? "Buzz" : ""
                out == "" ? it : out
              })
              

This ended up printing the list returned by the collect method. Really close, but not quite what I was hoping for. After all, the challenge is to print the results, not quite a string representation of a list. It was easy then to go from the code above to the code below:

              (1..100).collect {
                def out = (it % 3) == 0 ? "Fizz" : ""
                out += (it % 5) == 0 ? "Buzz" : ""
                out ?: it
              }.each { println it }
              

This printed the list just like the first pass. It's definitively Groovier (in my opinion) than the original implementation. It still does fall short of the capabilities of Groovy.

So here's my final implementation:

              (1..100).collect {
                   ((it % 3) == 0 ? "Fizz" : "") << ((it % 5) == 0 ? "Buzz" : "") ?: it
              }.each { println it }
              

This takes full advantage of Groovy's power. It is a little harder to read, which is a downside. It does take full advantage of many of Groovy's powerful features:

  1. A range to generate the list of numbers to process. Ranges return an iterator that iterates from the start of the range to the end of the range.
  2. The collect method which applies a closure to each item in the collection (or iterator) and returns the results as a list.
  3. The each method, which iterates through a list and applies a closure to it. It returns the collection that it iterated through.
  4. Closures, which are implemented quite well in Groovy.
  5. Operator overloading. The << operator is overloaded on the String class to concatenate two Strings together.
  6. The brand new Elvis operator (?:) which returns the alternate value if the expression evaluates to false.
  7. Groovy returns the last expression of a block as the result of the block. This includes closures and methods.

I do think that I'll incorporate this question in future interviews. It has quite a few interesting subtleties and implementations that are only rivaled by the Singleton pattern. I guess that the last group of interviewees got it a little easier...


Groovy Fizz and Buzz 6

Posted by Frederic Jean Thu, 28 Feb 2008 06:57:02 GMT

The FizzBuzz programming interview question raised it's head again. I've managed to resist the temptation to implement it in any languages so far. Until this morning that is...

So I fired up the Groovy Console and played a little. A nice feature of the console is that it displays a history of the scripts it ran. This allows me to present an evolution of my FizzBuzz program.

I first started with a rather naive implementation:

              (1..100).each { 
                def out = "" 
                if ((it % 3) == 0) { out += "Fizz" } 
                if ((it % 5) == 0) { out += "Buzz" } 
                if (out == "" ) { out = it } 
                println out
              }
              

Not bad for something that I came up with in about 10 minutes. It doesn't really take advantage of Groovy's features though. So I refined it a bit by using the ternary operator:

              (1..100).each {
                def out = (it % 3) == 0 ? "Fizz" : ""
                out += (it % 5) == 0 ? "Buzz" : ""
                println (out == "" ? it : out)
              }
              

This is a slight improvement over the first version. I still didn't feel that this was Groovy enough for me. I decided to play with the List collect method. This applies a closure to all items in a collection. The first pass was the following code segment:

              println ((1..100).collect {
                def out = (it % 3) == 0 ? "Fizz" : ""
                out += (it % 5) == 0 ? "Buzz" : ""
                out == "" ? it : out
              })
              

This ended up printing the list returned by the collect method. Really close, but not quite what I was hoping for. After all, the challenge is to print the results, not quite a string representation of a list. It was easy then to go from the code above to the code below:

              (1..100).collect {
                def out = (it % 3) == 0 ? "Fizz" : ""
                out += (it % 5) == 0 ? "Buzz" : ""
                out ?: it
              }.each { println it }
              

This printed the list just like the first pass. It's definitively Groovier (in my opinion) than the original implementation. It still does fall short of the capabilities of Groovy.

So here's my final implementation:

              (1..100).collect {
                   ((it % 3) == 0 ? "Fizz" : "") << ((it % 5) == 0 ? "Buzz" : "") ?: it
              }.each { println it }
              

This takes full advantage of Groovy's power. It is a little harder to read, which is a downside. It does take full advantage of many of Groovy's powerful features:

  1. A range to generate the list of numbers to process. Ranges return an iterator that iterates from the start of the range to the end of the range.
  2. The collect method which applies a closure to each item in the collection (or iterator) and returns the results as a list.
  3. The each method, which iterates through a list and applies a closure to it. It returns the collection that it iterated through.
  4. Closures, which are implemented quite well in Groovy.
  5. Operator overloading. The << operator is overloaded on the String class to concatenate two Strings together.
  6. The brand new Elvis operator (?:) which returns the alternate value if the expression evaluates to false.
  7. Groovy returns the last expression of a block as the result of the block. This includes closures and methods.

I do think that I'll incorporate this question in future interviews. It has quite a few interesting subtleties and implementations that are only rivaled by the Singleton pattern. I guess that the last group of interviewees got it a little easier...


Talking about JSON at the Boulder JUG

Posted by Frederic Jean Tue, 11 Sep 2007 17:02:40 GMT

I'll give a presentation about JSON at the Boulder JUG tonight. I'll introduce JSON to the audience, talk about consuming and producing JSON, discuss some of the security implications around JSON before talking about some recent developments. This is an extension of the presentation I gave to the Denver JUG a few months ago.

Technorati Tags:

I Edited Wikipedia

Posted by Frederic Jean Thu, 28 Sep 2006 22:08:18 GMT

I was playing with Pathway, which is a new Wikipedia browser. I decided to look at the Groovy article and navigate a bit around. I ended on the Closure article, which mentioned a few languages that implement closures. Groovy was missing, so I added it.

The nice thing is that I didn't have to worry about processes or finding the right people to make the change. It simply did happen.

The Four Pillars of Groovy Adoption

Posted by Frederic Jean Thu, 07 Sep 2006 22:48:06 GMT

Groovy in and of itself is a very good language. We have been using it for many years now in our shipping products. Yet, there is still to be a ground swell of adoption of the language. Part of the problem may be the relative obscurity of the language, or a misconception around its "scripting" nature. I do believe that we need to do some evangelism on the language.

Even so, I see four different pillars that the community can leverage to drive adoption. Out of these four, two are Groovy specific:

  1. JSR-223 providing a standardized way to call dynamic languages within Java code.
  2. Spring 2.0 treating dynamic languages beans as first class citizen within the framework. You can define you beans in groovy without compiling it and inject it into another Spring bean.
  3. Grails. Brings many of the principles that are making Ruby on Rails successful to the Java platform without the, er, attitude displayed by the Rails core team.
  4. Groovy In Action. Having one or more books on a technology is usually a milestone toward wider adoption of a technology. I will simply point to Dave Thomas's books on Ruby (Pickaxe 1 and 2) and Rails (Agile Web Development with Ruby on Rails) as examples.

Groovy In Action will probably have the most immediate impact since having a book available in bookstores will increase the visibility of the language. It is currently going through Manning's early access program (MEAP), but the material so far is pretty good.

Looking At Grails (And Liking It)

Posted by Frederic Jean Wed, 02 Aug 2006 04:57:58 GMT

A few months ago, I was introduced to the Grails project while attending a Boulder JUG meeting. It was just after they released they 0.1 release. It was a little rough around the edges. At the times, I thought it was just another Java based Ruby on Rails wannabe. As a result, I just ran the basic install, went through the quick start tutorial and moved on to more interesting (to me) projects.

I have since changed my mind.

We use a lot of Groovy at OpenLogic. We use it in our infrastructure. We use it to build our content packages. I tend to use it whenever I would have to write more catch clauses than they are lines of code that could possibly throw these exceptions. It’s a great dynamic language in its own right, and it integrates seamlessly with Java code.

Now, Grails happens to be written in Groovy. It does borrow concepts from Ruby on Rails such as Convention over Configurations, (dynamic) code generation and scaffolding while leveraging the power of existing libraries and framework such as Spring, Hibernate and Sitemesh. I’m just starting with it, and I’m still learning the different “grailisms” used to code the applications, but I like it so far.

I’ll keep looking at it and evaluate it for future project. In the mean time, I’m starting with a pet project. It is similar to a different project I did while I was still at Sun. As a result, I already have a pretty good idea how to proceed with the project. That will help a lot.