challenge: implement the max function

Xinok xnknet at gmail.com
Sun Jan 21 13:58:40 PST 2007


Take Two :)

template maxtype(T...){
	static if(T.length == 0) static assert(false);
	static if(T.length > 2) alias maxtype!(typeof(T[0]+T[1]), T[2..length]) maxtype;
	static if(T.length == 2) alias typeof(T[0]+T[1]) maxtype;
	static if(T.length == 1) alias typeof(T[0]) maxtype;
}

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

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


a) generic
Not sure 100% what you mean, but the function accepts arguments of any type.

b) efficient
Function recursion. Not the most efficient, perhaps using a static foreach would be best?

c) preserve lvalueness
This is impossible when using a mix of types. When using the same type though, you could rewrite the function to make use of pointers.

d) should accept two or more arguments
check

e) should return the "smartest" type
This is what the 'maxtype' template is for. All that matters now is how smart the D compiler is.
I already tested it, it automatically prefers unsigned types over signed types.
For a 'min' function though, the template would require a bit of conditioning to prioritize signed types.

f) short and easy to understand
Not sure about this, but the function is surely easy to use. Just give it the arguments, and it returns the greatest value.



More information about the Digitalmars-d mailing list