challenge: implement the max function
Alain
alainpoint at yahoo.fr
Mon Jan 22 00:14:59 PST 2007
Don Clugston Wrote:
> 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;
> }
Fine !
but it doesn't work for the following common use case:
int[] mylist=[1,2,3,4,5];
int mymax=max(mylist);
Alain
More information about the Digitalmars-d
mailing list