{data dendrites} exploring data science with Python et al.

FizzBuzz in Julia — using ternary operator

The rules are well-known: Print numbers from 1 to N (usually 100). If a number is divisible by 3, print "Fizz"; if it's divisible by 5, print "Buzz"; if it's divisible by both, print "FizzBuzz"; if neither, print the number.

This is obviously a very easy problem, but this is an opportunity to show the use of Julia's ternary operator (?):

[1:50 [ (i % 3 == 0 && i % 5 == 0) ? "FizzBuzz " : (i % 3 == 0 ? "Fizz " : (i % 5 == 0 ? "Buzz " : i)) for i in 1:50 ] ]

This version is of course not very "pythonic", but after all, Julia is not Python. A clearer version would be:

for i in 1:50
    if i % 3 == 0 && i % 5 == 0
        println(i, " Fizz Buzz")
    elseif i % 3 == 0
        println(i, " Fizz")
    elseif i % 5 == 0
        println(i, " Buzz")
    else
        println(i)
    end
end

Alternatively, you can use the ternary notation in a block form:

for i in 1:50
    i % 3 == 0 && i % 5 == 0 ? println(i, "FizzBuzz ") : 
    i % 3 == 0 ? println(i, "Fizz ") : 
    i % 5 == 0 ? println(i, "Buzz ") : 
    println(i)
end

As you can probably guess, : is else. It is required with ?. Writing a = 10; a < 20 ? print("oh") will result in an error: syntax: colon expected in "?" expression. Of course, if you wanted to write just a quick if...then statement, you could write:

a = rand()
a < 0.5 && print("oh")

The second line is equivalent to:

if (a < 0.5) print("oh") end

You can also write the list comprehension on several lines:

[   
    i % 3 == 0 && i % 5 == 0 ? println(i, "FizzBuzz ") : 
    i % 3 == 0 ? println(i, "Fizz ") : 
    i % 5 == 0 ? println(i, "Buzz ") : 
    println(i)

    for i in 1:50
]
comments powered by Disqus