Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive arrays of arrays of ... in D function?

Tags:

arrays

d

Don't know if is possible, I want receive maybe data[n] or data[n][n][n]. In C could be (correct me if wrong):


void save_data(void* arr, int n, int dimensions)
{
    // do ugly things
}

But must exist a more elegant way in D.

like image 271
Pedro Lacerda Avatar asked Oct 06 '10 02:10

Pedro Lacerda


1 Answers

One alternative besides using C style pointer arithmetics is to template safe_data, i.e. do something like this:

import std.stdio;
import std.traits;

void safe_data(T)(in T arr) {
    static if(isArray!T) {
        writeln("Length ", arr.length); // do some ugly stuff for whole array
        foreach(e; arr) safe_data(e);   // recursively go deeper
    } else {
        writeln("Element ", arr);       // do more ugly stuff on individual elements
    }
}

void main() {
    writeln("A");
    int[3] A = [1,2,3];
    safe_data(A);
    writeln("B");
    int[3][2] B = [[1,2,3],[4,5,6]];
    safe_data(B);
}

Depending on what you want to do with the data, you might want to use ref instead on in. BTW, if you prefer, you can move the static if outside of the function which makes for cleaner code sometimes:

// handle arrays
void safe_data(T)(in T arr) if(isArray!T) {
        writeln("Length ", arr.length); // do some ugly stuff for whole array
        foreach(e; arr) safe_data(e);   // recursively go deeper
}

// handle array elements
void safe_data(T)(in T e) if(!isArray!T) {
        writeln("Element ", e);         // do more ugly stuff on individual elements
}
like image 75
stephan Avatar answered Oct 20 '22 02:10

stephan