How to write similar code D?

FG via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 9 17:31:50 PST 2015


On 2015-02-10 at 01:41, bearophile wrote:
>
>      auto query = iota(2, 12)
>                   .map!(c => Tuple!(int,"length", int,"height", int,"hypotenuse")
>                                    (2 * c, c ^^ 2 - 1, c ^^ 2 + 1))
>                   .map!(x => "%3d%4d%4d".format(x.height, x.hypotenuse, x.length));
>

I took advantage of the fact that all elements were of the same type:

     auto query = iota(2, 2 + 10)
     .map!(c => ["Length": 2 * c, "Height": c * c - 1, "Hypotenuse": c * c + 1])
     .map!(x => format("%4d%4d%4d", x["Height"], x["Hypotenuse"], x["Length"]));
     ...

and was surprised that it worked straight away. :)
But definitely this looks better and less complicated:

     auto query = iota(2, 12)
         .map!(c => tuple(c ^^ 2 - 1, c ^^ 2 + 1, 2 * c));
     foreach (x; query)
         writefln("%4d%4d%4d", x[]);

It's the foreach version, since `each` isn't officially out yet.


More information about the Digitalmars-d-learn mailing list