challenge: implement the max function
Don Clugston
dac at nospam.com.au
Sun Jan 21 23:52:08 PST 2007
Andrei Alexandrescu (See Website For Email) wrote:
> Here's a simple challenge: implement the max function. Requirements:
>
> a) generic
> b) efficient
> c) preserve lvalueness when possible such that one can write e.g.
>
> max(arr[0], arr[1]) *= 0.9;
>
> d) should accept two or more arguments
> e) should return the "smartest" type, e.g. max of an unsigned int and
> unsigned long should return unsigned long
> f) short and easy to understand
>
> I don't think it's possible to implement the function to the spec in
> current D, so designs are allowed to invent new features, as long as
> they define them thoroughly.
>
> Looking forward to any takers!
>
>
> Andrei
----
Here's an implementation I put into Tango a few days ago. Unlike some
other ones which have been posted, it does *not* require the types to
support operator '+'. This was only for two arguments, but I believe it
satisfies the other requirements. Should be easy to generalise.
----
private {
// Implicitly convert to the smallest type which can store both T
and U; acts like an 'auto' template return type.
template SharedComparisonType(T, U) {
static if (is( typeof( (T x, U y){ return y<x? y: x;}) Q == return))
alias Q SharedComparisonType;
}
}
/** Return the minimum of x and y.
*
* Note: If x and y are floating-point numbers, and either is a NaN,
* x will be returned.
*/
SharedComparisonType!(T, U) min(T, U)(T x, U y) {
return y<x? y : x;
}
/** Return the maximum of x and y.
*
* Note: If x and y are floating-point numbers, and either is a NaN,
* x will be returned.
*/
SharedComparisonType!(T,U) max(T, U)(T x, U y) {
return y>x? y : x;
}
More information about the Digitalmars-d
mailing list