Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Tuesday, January 10, 2012

Fizz 3 - Elvis Has Left the Building (Groovy)

Whenever I count "Fizz" in this series I will examine a language that has yet to be examined before. There is no shortage of candidates but the trick will be to keep the languages choices relevant and readily verifyable (this could be tricky).  Ideally I will be able to consider a feature that is relatively unique to that language or family of languages.

For this post I will examine the Groovy programming language.  Picking a relatively unique feature for Groovy is a fairly hard prospect since it tries to pull all the best parts from all other languages.  It is based on Java, so it's a C like curly brace language.  It compiles to JVM byte code.  It is object oriented, but strives to delay it's method dispatch as late as possible, enabling multiple dispatch method invocations as seen in Common Lisp.  It uses closure like blocks much like you would see in Ruby.

There are a lot of neat tricks in Groovy so I see myself coming back to this language later in this series.  But perhaps the most unique feature of Groovy, or the one feature that it has gone the furthest to popularize, then it would be the "Elvis Operator:" ?: a C style ternary operator with the middle operand removed.

for (int i = 1; i <= 100; i++) {
  String answer = ""

  if (i%3 == 0) {
    answer += "Fizz"
  }

  if (i%5 == 0) {
    answer += "Buzz"
  }
  
  println answer ?: i
}

This isn't the most idiomatic Groovy code for this solution. It is intended to demonstrate just the Elvis operator with all other awesomeness removed.  I have a three statement solution that shows other Groovy features such as blocks and ranges. But for the purpose of this post we should focus just on the unique feature. There, on line 12 of the verbosely expressed code, is the Elvis operator. Why is it called Elvis? If you rotate it clockwise the question mark kind of forms Elvis Presley's hair just above his eyes.

But what does it do?  It clearly has no hips to shake suggestively since he is being expressed from the nose up.  Elvis picks the first "true" item it sees and returns only that item.  Mode technically, the left hand side of the operator is evaluated for "groovy truth," and if it returns negative (null, false, zero, or empty string in most cases) then the right hand side of the operator is returned. If the left had side matches any other value, then the left hand side of the operator is returned.

This roughly equates to the C style statement x ? x : y. If the middle operator leaves the building, along with the white space, you are left with the Elvis operator: x ?: y. Even though Elvis has left the building, his legacy remains.

No comments:

Post a Comment