How to imporve D-translation of these Python list comprehensions ?

Timon Gehr timon.gehr at gmx.ch
Mon Jan 15 21:53:30 UTC 2018


On 15.01.2018 22:51, Timon Gehr wrote:
> auto aa(R)(R r){
>      typeof(r.front[1])[typeof(r.front[0])] a;
>      foreach(x;r) a[x[0]] = x[1];
>      return a;
> }

Actually, better to use std.array.assocArray.

import std.stdio, std.algorithm, std.range, std.array, std.conv, 
std.json, std.typecons;
alias emap(alias a) = map!(x => a(x.expand));

void main(){
     auto srv1 = [
         "acs": ["ver": "1.2.3", "rev": "6f2260d"],
         "cms": ["ver": "4.5", "rev": "b17a67e"],
         "ots": ["ver": "6.7.80", "rev": "4f487d2"]];
     auto srv2 = [
         "acs": ["ver": "1.2.3", "rev": "6f2260d"],
         "cms": ["ver": "5.1", "rev": "2a56c53"],
         "vaa": ["ver": "0.7", "rev": "00852cb"]];

     chain(srv1.keys, srv2.keys).sort.uniq
         .map!(k => chain(only(tuple("_name", k)),
                          cartesianProduct(only("ver", "rev"), 
only(srv1, srv2).enumerate)
                          .emap!((prop, srv) => tuple(text(prop, 
srv.index), srv.value.get(k, null).get(prop, "")))
               ).assocArray).array.JSONValue.toPrettyString.writeln;
}


More information about the Digitalmars-d-learn mailing list