Search code examples
d

How to write multi statements in a range block with Dlang?


I would like to write multi statements in a range block, like this:

long[] W = [0L];
long[] V = [0L];

array.each!(s => // "s" has following strings "3 4" 
  W ~= s.split(" ")[0].to!long;
  V ~= s.split(" ")[1].to!long;
);

But this causes compile error. Is there any way to write all statements in the range ?


Solution

  • Just use slightly longer form function syntax:

    long[] W = [0L];
    long[] V = [0L];
    
    array.each!( (s) {
        W ~= s.split(" ")[0].to!long;
        V ~= s.split(" ")[1].to!long;
      }
    );
    

    (s) { x; y; z; } works anywhere s => x works, except with s=>x if you need the return value, the long-form is (s) { return x; }.