2
\$\begingroup\$

I have been playing around with the Io language, and this is my second toy, after the yes program that is just loop ("yes" printl) and on which not much review is possible, I wrote a FizzBuzz program. I like the shortness of it, but any improvement is welcome as I am very beginner in this programming language.

toBuzzWord := method(n,
   if (n % 15 == 0, "FizzBuzz",
   if (n % 5 == 0, "Fizz",
   if (n % 3 == 0, "Buzz", n))))

for (i, 1, 100, toBuzzWord(i) println)
\$\endgroup\$
2
\$\begingroup\$

From discussion elsewhere I know you don't want to change the basic implementation, so I'll confine my comments to idiom, style and tweaks.

I would replace the for loop with a foreach

Range // addon reference required in newer versions
1 to(100) foreach(i, toBuzzWord(i) println)

The Range protocol used to be in the core library but is now an add-on, hence the reference needed before you can use it. That said, it's a more idiomatic, expressive and robust way to deal with simple ranges. for loops are even more fragile in Io than in C-like languages, given the optional parameter and Io's blithe tolerance of extra parameters.

I don't like chained if-then-elsif in any language, even when it's a function and not a keyword. One alternative would be to use return

method(n,
   if (n % 15 == 0, return "FizzBuzz")
   if (n % 5 == 0, return "Fizz")
   if (n % 3 == 0, return "Buzz")
   return n
)

Multiple exit points from a function are much debated and criticised, but

  1. Io has no switch or case function and the community doesn't want one.
  2. lists (using a numeric index lookup) or maps (using a string key) are sometimes used for very simple switch-style control flows but that doesn't work here.

In purist OO style, Io developers prefer to use (no surprise here) polymorphism. Send a message and let the inheritance chain pick the appropriate action.

Polymorphism is really overkill for the simple fizzBuzz implementation you have chosen. It might be useful for a more efficient solution.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.