challenge: implement the max function

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Sun Jan 21 18:31:29 PST 2007


Xinok wrote:
> 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.

That's what I meant. Any types that accept ">". You require the types to 
accept "+" too, so you need to fix that.

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

No worries. It's compile-time recursion.

> 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.

That's why you are invited to implement your own feature(s) that would 
make your max fit the requirement.

> 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.

Ah, I should have chosen "min" as a challenge :o).

> 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.

I think it fails at the "short" test, but it's a good start.


Andrei



More information about the Digitalmars-d mailing list