Possible to write a classic fizzbuzz example using a UFCS chain?

w0rp via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 28 04:04:11 PDT 2015


On Tuesday, 28 April 2015 at 10:46:54 UTC, Gary Willoughby wrote:
> After reading the following thread:
>
> http://forum.dlang.org/thread/nczgumcdfystcjqybtku@forum.dlang.org
>
> I wondered if it was possible to write a classic fizzbuzz[1] 
> example using a UFCS chain? I've tried and failed.
>
> [1]: http://en.wikipedia.org/wiki/Fizz_buzz

You can do this.

import std.range : iota;
import std.algorithm : map, each;
import std.typecons : Tuple, tuple;
import std.stdio : writeln;

Tuple!(size_t, string) fizzbuzz(size_t number) {
     if (number % 3 == 0) {
         if (number % 5 == 0) {
             return tuple(number, "fizzbuzz");
         } else {
             return tuple(number, "fizz");
         }
     } else if (number % 5 == 0) {
         return tuple(number, "buzz");
     }

     return tuple(number, "");
}

void main(string[] argv) {
     iota(1, 101)
     .map!fizzbuzz
     .each!(x => writeln(x[0], ": ", x[1]));
}

The desired output may vary, depending on variations of FizzBuzz. 
(Some want the number always in the output, some don't.) You 
could maybe do crazy ternary expressions instead of writing a 
function, or put it directly in there as a lambda, but both just 
look ugly, and you might as well just write a function for it.


More information about the Digitalmars-d-learn mailing list