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”.
Showing posts with label Kotlin. Show all posts
Showing posts with label Kotlin. Show all posts

Tuesday, March 20, 2012

Buzz 20 - In Some Particular Order

One of the features that Kotlin has borrowed from other languages is the notion of tuples.  For lack of a more precise and rigorous definition tuples are (sometimes) ordered lists of stuff.  You may say that your language already has ordered lists of stuff.  But this is special stuff... it's got.. specialness.

fun Int.isBuzz() : Boolean {
    return this % 5 == 0;
}

fun main(args : Array<String>) {
    for (i in 1..100) {
        println( when (#(i % 3, i.isBuzz())) {
            #(0, true) -> "FizzBuzz";
            #(0 ,false) -> "Fizz";
            #(1 ,true), #(2 ,true) -> "Buzz";
            else -> i;
        });
    }
}

The type of specialness that tuples have in are threefold.  Syntax, language integration, and generics.

First, Kotlin gives Tuples a special language syntax of their own.  A Hash followed by a parenthesized list of stuff  constitutes a tuple.  This is a shorthand notation for a tuple.  Tuples are usually significant in their order, but if you prefix the value with a label then that value gets a name and it can be accesses by that name.  It becomes a very lightweight way to define data structures that are only needed locally.

Second, there is a good deal of language integration with tuples.  The void equivalent return type Unit is actually a Tuple0 as well, which is a tuple with zero members.  And Kotlin uses the tuple mechanism to allow a function to return multiple types.  Even though the JVM and JavaScript VMs only allow a single return type, Kotlin does an end run by making the return a tuple.  While you could do this yourself with Object arrays and one off classes Kotlin integrates this practice so you can take only your favorite parts of the return in your code rather than swallowing the whole horse pill.

Finally, there is a good amount of generics integration with the tuple.  Since each position can be a different type Kotlin integrates the type of the position into the type signature of the particular tuple you are using.  This is more important when you consider that Kotlin generics are fully reifiable.

Of course, I haven't come up with a good way to demonstrate reifiable generics in a FizzBuzz solution.  And until someone does we should not expect the typical developer to get it right.

Tuesday, March 13, 2012

Fizz 18 - Getting the Monkey Off of Your Patch

When talking about functions and methods there really isn't much difference between the two at first.  The real meaning and value doesn't start to show up until other esoteric features like  class inheritance, subtyping, polymorphism, late binding, multiple dispatch, meta-object protocols, category theory, and on and on and on.  That is the territory where PhDs are minted.  Without all that messy class theory the main difference between a method and a function are access to protected fields and an implicit this parameter.  Methods are also typically also declared inside the structure declaring the class.  And methods for a particular class are almost always declared by the original implementer of the class.  If you need a new method in a class, you nearly always had to sub-class the class.  Nearly.

fun Int.isFizz() : Boolean {
    return this % 3 == 0
}

fun Int.isBuzz() : Boolean {
    return this % 5 == 0
}

fun main(args : Array<String>) {
    for (i:Int in 1..100) {
        when {
            i.isFizz() && i.isBuzz() -> println("FizzBuzz")
            i.isFizz() -> println("Fizz")
            i.isBuzz() -> println("Buzz")
            else -> println (i)
        }
    }
}

Kotlin let you, after a fashion, declare methods that look like they belong in a class.

On line 10 we declare the looping variable i to be of type Int. This is a class provided by Kotlin and is one that is not open to extension. Remember, all classes are closed by default in Kotlin. But look at lines 12, 13, and 14. We are calling an isFizz and isBuzz method in the Int class. Surely they are not just juicing up the standard library to look good in a standard demo, are they?

It's not the Kotlin team that is juicing things up. It is the program itself. Lines 1-7 are declaring extension functions on the Int class. This is how we are adding what look like methods onto the already closed class Int. Really, these are not all that different from Python methods except for some syntactic sugar low-carb coding where the explicit self parameter becomes an implicit this parameter, whose type is explicitly determined by convention of the function name: <class name>.<method name>.

This addition, however, does not literally add a method to the class it is extending.  The method is not subject to any late binding or multiple dispatch.  The particular method is entirely determined at compile time.  It also must either be present in the package at compile time, or explicitly imported in the file in which it is used. So a developer can write an awesome set of String extension functions, like String.invertEveryThirdWord() and not have to involuntarily subject the world to their awesomeness by declaring them in the org.example.of.category.theory package, and only let the 1337 few who are worthy of it's power bask in it's glory.

Wednesday, March 7, 2012

#17 - Putting the Meth in Method

Functions and procedures are old hat. Those ideas were conceived of not only before I started earning a paycheck in Software, but before I myself was even conceived. Modern programmers use more current techniques like Object Oriented programming. A technique that was conceived of over a decade after functions and procedures were, and was still, sadly, before I was conceived. It's not modern, it's just the modern fashion.

class FizzBuzzer(max: Int) {
    var i:Int = 0
    val max:Int = max

    fun hasNext() : Boolean {
        return i < max
    }

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

fun main(args : Array<String>) {
    val fizzer : FizzBuzzer = FizzBuzzer(100)
    while (fizzer.hasNext()) {
        println(fizzer.nextValue())
    }
}

The implementation for this solution is one of an iterator. But we won't dwell on that since that isn't what we are looking at in this post. Similarly to talk about methods we have to embed them in a class, which is something we will just wave our hands over now and come back to later, because the true power of OO actually can be used to solve FizzBuzz. So I will wave my hands over that and move on to what you can't get enough of: methods.

The first thing you should notice about Kotlin classes is that the constructors are for the most part integrated into the class body. There is a notion of a primary constructor which is in place to discourage the proliferation of constructors. When combined with default parameters it handles nearly all the reasons for constructor proliferation, leaving for the most part only weird stuff like copy and pseudo-copy constructors. It is unclear in the current docs if there is any allowance for other constructors. I am not sure if this is a bad thing.

Next, we look at the member variables. In Kotlin all fields are properties by default. You can change this with a private modifier. Also, because fields are properties by default each property either must be initialized or have a get defined as part of the declaration. What is good practice in C (undefined fields can be practically random and a security risk), and implied in Java (zero, false, or null as appropriate) is compulsory in Kotlin.

When it come to actually instantiating an instance of the object on line 21 we see that the new operator is not required.  In fact, it is not even allowed! Calls to create objects look just like regular function calls. While you may argue that this limits the namespace of functions I counter by saying this is a good thing, since functions named like objects usually create bugs. Add in the practice that  class names generally get the German Noun treatment distinguishing a constructor call from a method call should be trivial.

Finally, an implementation note. It may look like the main function doesn't belong to a class. But because of the structure of the JVM it does belong in a class, as a static method of that class. The class is (currently) named namespace and it is declared in the package of the code it is written in.

Be careful when picking up Object Oriented programming. You may think you can stop anytime you want. But you won't ever want to. And when you try to stop, your language won't let you.  You will be coding methods for the rest of your life.  Even languages like Clojure are fooling you.  It's all methods all the time.

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?!

Friday, February 24, 2012

#14 - Express Yourself

When creating a new language the designers really need to look at the cool features from current languages and steal the best parts. But you need to be cautious about not just picking up fashions. Remember: fashion is what you look at 20 years later and say "That looks so ugly."

But the reality is that only time will tell what is simply fashion and what is not. One of the cooler features of Ruby is that everything is an expression. Control structures included. That may be why ruby lacks the three expression for loop. That and a mild aversion to semi-colons. I'de post this code in Ruby, except that the new kid on the block is Kotlin, and everyone loves to play with the new kid.

fun main(args : Array<String>) {
  for (i:Int in 1..100) {
    println (
      when (i%15) {
        0 -> "FizzBuzz" 
        5, 10 -> "Buzz"
        3, 6, 9, 12 -> "Fizz"
        else -> i
      })
  }
}

This is only a mild variation from the previous solution. Instead of printing out the results inside the when blocks the whole result of the when block is printed out. Structures like this figure into some of the design decisions like making the case statements only one expression. Evert expression on Kotlin returns a value. Even if it returns Nothing (and there is a language construct for Nothing).

Hopefully the "everything is an expression" thing isn't just fashion.  Ideally when you come back in 20 years (or 20 weeks) and see yourself using control structures as expressions you won't ask yourself  "What was I thinking?"

Tuesday, February 21, 2012

#13 - When in St. Petersberg

That was a short break. Basically I wasn't liking the structure I was forcing myself into. Once I get a large corpus of solutions I can look into formatting, but in the mean time I will focus on stuff that entertains me, free of schedule constraints or themes.

But last Tuesday JetBrains publicly released the beta of Kotlin, their entry into the alternative not-just-JVM languages. There are several very interesting features of this language. And best of all it runs in an IDE I use on a daily basis: IntelliJ Idea. Since this will be the first of several posts, I will first present the solution that most of them will build on.

fun main(args : Array<String>) {
    for (i in 1..100) {
        when (i%15) {
            0 -> println("FizzBuzz");
            5,10 -> println("Buzz");
            3,6,9,12 -> println("Fizz");
            else -> println(i);
        }
    }
}

Instead of a switch statement Kotlin has a when statement (lines 3-8). This is for the most part syntactic sugar, but real sugar not the high fructose code syrup sold to public school programming students. At first blush it looks like changing the word when for switch and some other changes in the case blocks. And in this example, it is all the same. But it is denser and hence reads better.

First, you will not that there is no implicit fall-through. Each case statement matches up to exactly one expression (and that expression can be a multi-expression block). To fall through the rest of the switch you must explicitly use the continue statement. And even then it will simply continue to evaluate itself against the conditions rather than jump to the next block. So the old-school switch drop throughs which were the source of some mysterious bugs are not longer explicitly allowed.

Second, because of the single use structure of the blocks, multiple cases are combined into one comma-separated expression. This is possible because there is no possibility of fall-through between each label.

Finally, the default case (denoted by the else case) is required except in instances when "the compiler can prove that all possible cases are covered with branch conditions".

For this solution, I took advantage of the 15 number pattern in FizzBuzz and simply switched on the mod of 15. There is one case for a FizzBuzz, two for a Buzz, and four for a Fizz. Everything else falls into the else block. This actually reads fairly close to the text description of the problem statement.

The IntelliJ team writing Kotlin is based mostly in Russia. The name Kotlin is from the name of an island near St. Petersberg, which is not really that close to Rome.