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”.

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

No comments:

Post a Comment