challenge: implement the max function

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Jan 23 02:23:00 PST 2007


Don Clugston wrote:
> 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..$]);
> }
> 
[snip min]
> 
> Not too terrible.

Except you broke it ;)
-----
urxae at urxae:~/tmp$ cat test.d
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..$]);
}


import std.stdio;

void main(){
     auto x = max(5, 1, 100);
     writefln(x);
}
urxae at urxae:~/tmp$ dmd -run test.d
5
-----

'max' should be this:
-----
maxtype!(T) max(T...)(T arg){
     static if(arg.length == 1) return arg[0];
     else return max(arg[0] >= arg[1] ? arg[0] : arg[1], arg[2..$]);
}
-----



More information about the Digitalmars-d mailing list