Possible to write a classic fizzbuzz example using a UFCS chain?
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 28 10:36:32 PDT 2015
On Tuesday, 28 April 2015 at 16:06:16 UTC, Andrea Fontana wrote:
> On Tuesday, 28 April 2015 at 13:59:48 UTC, Ivan Kazmenko 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
>>
>> Here is another, hopefully readable, version with lambda built
>> on ternary operators:
>> -----
>> import std.algorithm, std.conv, std.functional, std.range,
>> std.stdio;
>> void main () {
>> sequence !(q{n + 1})
>> .map !(x =>
>> (x % 3 == 0 ? "fizz" : "") ~
>> ( x % 5 == 0 ? "buzz" : "") ~
>> (x % 3 != 0 && x % 5 != 0 ? x.text : ""))
>> .take (100)
>> .join (" ")
>> .writeln;
>> }
>> -----
>>
>> Output:
>> -----
>> 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 26 fizz 28 29 fizzbuzz 31
>> 32 fizz 34 buzz fizz 37 38 fizz buzz 41 fizz 43 44 fizzbuzz 46
>> 47 fizz 49 buzz fizz 52 53 fizz buzz 56 fizz 58 59 fizzbuzz 61
>> 62 fizz 64 buzz fizz 67 68 fizz buzz 71 fizz 73 74 fizzbuzz 76
>> 77 fizz 79 buzz fizz 82 83 fizz buzz 86 fizz 88 89 fizzbuzz 91
>> 92 fizz 94 buzz fizz 97 98 fizz buzz
>> -----
>>
>> Ivan Kazmenko.
>
> [2, -1, -1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, -1, -1]
> .cycle
> .enumerate
> .drop(1)
> .take(100)
> .map!(a =>
> a[1]>=0?["Fizz","Buzz","FizzBuzz"][a[1]]:a[0].to!string)
> .each!writeln;
An inefficient but neat version of that:
void main()
{
[3, 3, 0, 3, 1, 0, 3, 3, 0, 1, 3, 0, 3, 3, 2]
.cycle
.enumerate(1)
.take(100)
.map!(a =>
["Fizz","Buzz","FizzBuzz",a[0].to!string][a[1]])
.each!writeln;
}
note `enumerate(1)` to avoid having to drop one.
But if we always print the number then we can have:
import std.range, std.stdio, std.conv, std.algorithm;
void main()
{
["","","Fizz","","Buzz","Fizz","","","Fizz","Buzz","","Fizz","","","FizzBuzz"]
.cycle
.enumerate(1)
.take(100)
.each!(a => writeln(a[0],'\t',a[1]));
}
More information about the Digitalmars-d-learn
mailing list