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

Timon Gehr timon.gehr at gmx.ch
Mon Jan 15 21:51:12 UTC 2018


On 15.01.2018 20:05, xenon325 wrote:
> 
> 
> I think, most clear code would be with tripple `foreach`, so I'll go 
> with that. But probably someone will come up with something better and 
> range-ier.
> 
> Suggestion are welcome!

import std.stdio, std.algorithm, std.range, std.array, std.conv, 
std.json, std.typecons;

auto aa(R)(R r){
     typeof(r.front[1])[typeof(r.front[0])] a;
     foreach(x;r) a[x[0]] = x[1];
     return a;
}
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, "")))
               ).aa).array.JSONValue.toPrettyString.writeln;
}



More information about the Digitalmars-d-learn mailing list