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

Idan Arye via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 28 06:58:52 PDT 2015


On Tuesday, 28 April 2015 at 11:03:09 UTC, bearophile wrote:
> Gary Willoughby:
>
>> I wondered if it was possible to write a classic fizzbuzz[1] 
>> example using a UFCS chain? I've tried and failed.
>
> Is this OK?
>
> void main() {
>     import std.stdio, std.algorithm, std.range, std.conv, 
> std.functional;
>
>     100
>     .iota
>     .map!(i => ((i + 1) % 15).predSwitch(
>         0,       "FizzBuzz",
>         3,       "Fizz",
>         5,       "Buzz",
>         6,       "Fizz",
>         9,       "Fizz",
>         10,      "Buzz",
>         12,      "Fizz",
>         /*else*/ i.text))
>     .reverseArgs!writefln("%-(%s\n%)");
> }
>
>
> Bye,
> bearophile

I've change your solution to use predSwitch's custom predicate:

     100
     .iota
     .map!(i => ((i + 1) % 15).predSwitch!((a, b) => 0x10 * (0 == 
a % 3) + (0 == a % 5) == b)(
         0x00, i.text,
         0x10, "Fizz",
         0x01, "Buzz",
         0x11, "FizzBuzz"))
     .reverseArgs!writefln("%-(%s\n%)");


More information about the Digitalmars-d-learn mailing list