FizzBuzz in Julia — using ternary operator
13 Jan 2015
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 (?
):
This version is of course not very “pythonic”, but after all, Julia is not Python. A clearer version would be:
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
]