Most elegant way for split array of struct into components

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 5 01:46:46 PDT 2016


On 07/05/2016 01:10 AM, Miguel L wrote:

 > could it be possible to implement some class or
 > struct method that works on an array of objects of that class or method?
 >
 > class A
 > {
 > void Y(A[] a){...}
 > }
 >
 > A[] array;
 > array.Y();
 >

Yes, but that normally belongs outside the type. Luckily, D's UFCS 
feauter lets one call a non-member function as if it's a member function:

import std.stdio;
import std.algorithm;
import std.range;

class A {
     int i;
     this(int i) {
         this.i = i;
     }
}

// Not a member:
void Y(A[] a){
     foreach (e; a) {
         writefln("working with %s", e.i);
     }
}

void main() {
     A[] array = iota(5).map!(i => new A(i)).array;

     // Can be called like a member:
     array.Y();
}

Still, it's debatable whether an array-processing functions should be 
executed with the member function syntax. I would write Y(array). When 
you discover the ranges, you will realize that instead of defining 
functions like Y that contain explicit loops, combining functions that 
work with just a single A is more maintainable, scalable, and almost 
always faster (sometimes you won't need to hold actual arrays of anything).

void y(A a) {
     writefln("working with %s", a.i);
}

void main() {
     // Objects are created but not a single array is in sight:
     iota(5)
         .map!(i => new A(i))
         .each!y;
}

The output is the same:

working with 0
working with 1
working with 2
working with 3
working with 4

Ali



More information about the Digitalmars-d-learn mailing list