challenge: implement the max function
Don Clugston
dac at nospam.com.au
Mon Jan 22 03:26:32 PST 2007
Jari-Matti Mäkelä wrote:
> Don Clugston kirjoitti:
>> 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...)
>
> Squeezing a bit might help f) a minor bit more:
>
> 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 if(arg.length == 1) return arg[0];
> static if(arg.length > 1) return arg[0] >= arg[1] ? arg[0] :
> max(arg[1..$]);
> }
>
>
> Doesn't it work as an lvalue for classes now?
Maybe. (does ? : preserve lvalues for classes?)
Pared down to the minimum, it is now:
template maxtype(T...){
static if(T.length == 1) alias typeof(T[0]) maxtype;
else static if(T.length > 2)
alias maxtype!(maxtype!(T[0..1]), T[2..$]) maxtype;
else static if(is( typeof( (T[0] x, T[1] y){ return y > x ? y : x;})
Q == return))
alias Q maxtype;
}
maxtype!(T) max(T...)(T arg){
static if(arg.length == 1) return arg[0];
else return arg[0] >= arg[1] ? arg[0] : max(arg[1..$]);
}
mintype!(T) min(T...)(T arg){
static if(arg.length == 1) return arg[0];
else return arg[0] <= arg[1] ? arg[0] : min(arg[1..$]);
}
Not too terrible.
More information about the Digitalmars-d
mailing list