I came across Gerald Benischke's post on FizzBuzz without if clauses, which inspired me to play around with FizzBuzz in Julia. My attempts aren't nearly as interesting, since they all do feature at least one if clause, but they were still fun to work on.
The first attempt is a naïve implementation of FizzBuzz. It's easy to read and it works well enough, but I don't like the fact that there's an explicit case for printing "fizzbuzz"—both the condition and the executed statement are redundant.
fizzbuzzes = (
naïve =
function (n)
if n%15 == 0 print("fizzbuzz")
elseif n%3 == 0 print("fizz")
elseif n%5 == 0 print("buzz")
else print(n)
end
print(" ")
end,
The second attempt removes the redundancy in the executed statement, but merely rewords the redundancy in the condition.
simpler =
function (n)
if n%5 != 0 && n%3 != 0 print(n) end
if n%3 == 0 print("fizz") end
if n%5 == 0 print("buzz") end
print(" ")
end,
The third attempt removes both redundancies, at the cost of a state variable.
flag =
function (n)
m = false
if n%3 == 0 print("fizz"); m = true; end
if n%5 == 0 print("buzz"); m = true; end
if !m print(n); end
print(" ")
end,
The following two attempts are simply variants of the second attempt, designed to illustrate an interesting technique—placing functions inside a flat or nested tuple and iterating over it/them. (In fact, all the attempts are an illustration of this technique—they're all stored in the fizzbuzzes
tuple).
anons =
function (n)
fs = (n -> if n%3 == 0 print("fizz") end,
n -> if n%5 == 0 print("buzz") end,
n -> if n%5 != 0 && n%3 != 0 print(n) end)
for f in fs
f(n)
end
print(" ")
end,
doubleanons =
function (n)
fs = ((n -> n%3 == 0, n -> print("fizz")),
(n -> n%5 == 0, n -> print("buzz")),
(n -> n%5 != 0 && n%3 != 0, n -> print(n)))
for f in fs
if f[1](n) f[2](n) end
end
print(" ")
end
)
This tuple-of-functions technique is very convenient for applying many independent functions to the same data. This made it very simple to add more attempts and test them all simultaneously.
julia> for (i, f) in collect(pairs(fizzbuzzes))
rpad("$i:", 15) |> print
for n in 1:25
f(n)
end
println()
end
naïve: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz
simpler: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz
flag: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz
anons: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz
doubleanons: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz