Private default arguments?

bearophile bearophileHUGS at lycos.com
Fri Dec 28 02:58:58 PST 2012


Often recursive functions need some "bookkeeping" default 
arguments that aren't meant to be used by the user, they are 
meant to be used only by recursive calls:


void radixSort(uint[] items, in uint shiftBits=24) {
     ...
     if (shiftBits > 0) {
         ...
         radixSort(array[...], shiftBits - 8);
     }
}
void main() {
     auto array = new uint[n];
     ...
     array.radixSort();
}



So this call is a bug:

void main() {
     ...
     array.radixSort(26);
}


To avoid bugs and to not expose such private arguments I 
sometimes define an inner function (or a private function in a 
struct/class). Now the only argument of the outer function is 
'items', and no mistakes can happen using radixSort2():


void radixSort2(uint[] items) {
     void radix(in uint shiftBits=24) {
         ...
         if (shiftBits > 0) {
             ...
             radixSort(array[...], shiftBits - 8);
         }
     }
     radix();
}


This has some disadvantages.

An alternative idea (that I maybe I proposed years ago in a 
weaker form) is to introduce 'private' default arguments (they 
must have a default value):


void radixSort3(uint[] items, private in uint shiftBits=24) {
     ...
     if (shiftBits > 0) {
         ...
         radixSort(array[...], shiftBits - 8);
     }
}


The 'private' means that only radixSort3 is allowed to set a 
shiftBits argument value. So this is reported as compilation 
error:

void main() {
     ...
     array.radixSort(26);
}


A more detailed proposal, almost a DEP:
http://d.puremagic.com/issues/show_bug.cgi?id=9229

Is this little feature worth the amount of language complexity 
increase it causes?

Bye,
bearophile


More information about the Digitalmars-d mailing list