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, March 6, 2012

#16 - Putting the Fun in Function

Kotlin has functions. Whodathunk? You've been seeing them since the first code samples but perhaps we should put it to real use.

fun fizzBuzz(i : Int) : String {
    return when (i%15) {
      0 -> "FizzBuzz";
      5,10 -> "Buzz";
      3,6,9,12 -> "Fizz";
      else -> i.toString();
    }
}

fun main(args : Array<String>) {
  for (i in 1..100) {
    println (fizzBuzz(i));
  }
}

The function deceleration syntax is very reminiscent of Pascal, the third programming language I ever learned (various BASICs and Action! were the first two). These differ from C[#/++] and Java in several ways.

One difference is that there are only three letters for fun, rather than all 8 for function. Even with IDE code completion, f [ctrl+space] [Enter] is still three keystrokes. I guess they could put in an extra space to save one, but then I'de be compelled to count [ctrl+space] as two keystrokes (even though it is one cord).

The next difference is that the type follows the symbol name. This is more of a western approach to surnames than the typical braces and semicolons approach which places the type before the symbol, if you consider the type of the symbol to be the family name of the symbol. In a sense, placing the identity of the symbol above that of it's role.

One other quirk is that there are no primitive types in Kotlin, or there are no object types of primitives (via the Int type deceleration on the first line). Actually there are object primitive types, but they are the nullable primitive types. Except that you use a capitalized name, which implies they are Object types, which they are unless they happen to have a nullable modifier on the object type, which makes it a different type rather than a modification of the original type. So to express this in a particle physics metaphor this is an anti-quirk to a Java quirk, which means they annihilate each other. Except they are quirks not quarks, so a strange quark, or quirk, is left over. Which only matters when comparing it to a particular implementation platform. Charming.

Finally, unlike Pascal there are no procedures. Everything is a function, even if it returns Nothing. The closest analog to a procedure would be a function with no declared return type, which is then implied to mean Tuple0, a tuple with zero members, which appears as of the writing of this post to be disctinct from Nothing. Remember, {ε} ≠ ∅. Isn't math fun?!

No comments:

Post a Comment