challenge: implement the max function

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Jan 21 12:09:48 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!

Some first thoughts:

Presumably, (b) is only required when using full optimization options?

What is the "smartest type" for the max of long and ulong?
There's no primitive integer type that can handle the entire range from 
long.min to ulong.max :(.
One option would be to use a floating point type or some to-be-added 
"BigInt" (library) struct/class. But floating point types would lose 
accuracy. And more importantly, both would break return-by-reference...

(c) & (e) are exclude each other in current D since return values are 
always rvalues, and a forwarding struct goes against requirement (e). 
Some implementation options would be:
* Add C++-like references to the language (at the very least for return 
values)
* Add implicit casts and bend requirement (e) a little to return a 
forwarding struct that implicitly converts to the wanted type. Probably 
breaks requirement (f) because of too much required operator overloading 
though.
* Something I haven't thought of yet ;)



More information about the Digitalmars-d mailing list