Possible to write a classic fizzbuzz example using a UFCS chain?
wobbles via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 28 05:30:34 PDT 2015
On Tuesday, 28 April 2015 at 11:04:12 UTC, w0rp wrote:
> 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.
Crazy ternary experessions:
void main(){
"%s".writefln(
iota(1, 100, 1)
.map!(a => a%3==0 ? (a%5==0? "fizzbuzz" : "fizz")
: a%5==0 ? "buzz" : a.to!string));
}
More information about the Digitalmars-d-learn
mailing list