To write such an expressive code D
Dennis Ritchie via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 10 17:11:17 PST 2015
On Wednesday, 11 February 2015 at 00:56:03 UTC, bearophile wrote:
> Dennis Ritchie:
>
>> Output:
>>
>> 0 xor 0 xor 0 = 0
>> 0 xor 0 xor 1 = 1
>> 0 xor 1 xor 0 = 1
>> 0 xor 1 xor 1 = 0
>> 1 xor 0 xor 0 = 1
>> 1 xor 0 xor 1 = 0
>> 1 xor 1 xor 0 = 0
>> 1 xor 1 xor 1 = 1
>>
>> This man again took advantage of the fact that in D there is
>> no such operation -> (analog switch).
>
> A natural solution in D:
>
> void main() {
> import std.stdio;
>
> foreach (immutable a; 0 .. 2)
> foreach (immutable b; 0 .. 2)
> foreach (immutable c; 0 .. 2)
> writefln("%d xor %d xor %d = %d", a, b, c, (a +
> b + c) % 2);
> }
>
>
>
> Alternative solution closer to the F# code:
>
> import std.stdio, std.algorithm, std.typecons;
>
> int f(T)(T t) if (isTuple!T) {
> return t.predSwitch(
> tuple(0, 0, 0), 0,
> tuple(0, 1, 1), 0,
> tuple(1, 0, 1), 0,
> tuple(1, 1, 0), 0,
> /*else*/ 1);
> }
>
> void main() {
> foreach (immutable a; 0 .. 2)
> foreach (immutable b; 0 .. 2)
> foreach (immutable c; 0 .. 2)
> writefln("%d xor %d xor %d = %d", a, b, c,
> tuple(a, b, c).f);
> }
>
> Bye,
> bearophile
Thanks.
More information about the Digitalmars-d-learn
mailing list