challenge: implement the max function

Don Clugston dac at nospam.com.au
Mon Jan 22 01:36:05 PST 2007


Lionello Lunesu wrote:
> donth ave wrote:
>> Xinok Wrote:
>>
>>> T[0]+T[1]
>> To have addition is an additional(sic!) requirement not present in the
>> challenge.
> 
> Would typeof(T[0]>T[1]?T[0]:T[1]) work? I'd have to test it, I guess :)

No, it doesn't work. But this does:
(starting to fail the simplicity requirement though...)
------
template maxtype(T...){
     static if(T.length == 0) static assert(false);
     static if(T.length == 1) alias typeof(T[0]) maxtype;
     static if(T.length == 2 && is( typeof( (T[0] x, T[1] y){ return y < 
x ? y : x;}) Q == return)) {
         alias Q maxtype;
     }
     static if(T.length > 2) {
         alias maxtype!(maxtype!(T[0..1]), T[2..$]) maxtype;
     }
}

maxtype!(T) max(T...)(T arg){
     static assert(arg.length > 0);
     static if(arg.length == 1) return arg[0];
     static if(arg.length == 2)
       return arg[0] >= arg[1] ? arg[0] : arg[1];
     static if(arg.length > 2)
       return max(arg[0] >= arg[1] ? arg[0] : arg[1], arg[2..length]);
}

void main(){
     writefln(max(15, 30, 45.5, 60.4));
}
----------



More information about the Digitalmars-d mailing list