std.array suggestion

Oskar Linde oskar.lindeREM at OVEgmail.com
Thu Mar 9 05:31:02 PST 2006


Don Clugston wrote:
> Oskar Linde wrote:
> I'll just comment on one function:
> 
>  > T sum(T[] arr)
>  >
>  > Returns the sum of the element in arr as defined by the + operator.
> 
> This one has an interesting twist. I'm not sure that the sum should 
> necessarily be of type T. I've been playing around with the concept of 
> what I've called the Archetype of a type, which is the largest type with 
> the same semantics as T (possibly with the same calculation speed). (ie,
> Archetype!(byte)= Archetype!(short)
> Archetype!(int) = long
> Archetype!(float) = Archetype!(double) = real,
> Archetype!(cfloat)= creal, etc). Obviously it's a trivial template.

Interesting...

> I think that at least,  sum(double[] ) should internally use a real 
> while accumulating the sum, so that it can satisfy this test (at least 
> on x86 platforms):
> 
> unittest {
>    const double a = [ double.max, double.max, -double.max];
>    assert(sum(a) == double.max);
> }
> 
> After all, this is one of the reasons why reals exist. I'm still not 
> sure if sum(double []) should return a double or a real, although I'm 
> inclined to think that *any* function that returns a single floating 
> point value should return a real (on x87, the 80-bit result is just left 
> on the FPU stack anyway). But, I'm less confident about how a sum of 
> ints should behave.

Int overflows is well defined, making the sum of ints behave correctly 
in the case above. Int is also the promotion type for integral 
operations and would be the natural return type for sum(int[]). A sum of 
shorts should probably return an int though, following integer promotion 
rules. Should Archetype for integers follow the integer promotion rules 
or all be long?

> However, all the other functions seem to be free of mathematical 
> subtleties. sum() is the only one which involves arithmetic operators, 
> and therefore it might not belong with the rest.

You make a strong argument and I agree. sum() is used as join() in other 
languages that lack the distinction between addition and concatenation. 
D doesn't need a non-arithmetic sum function. With the proposed fold 
function, you could also easily implement sum as:

sum = fold(arr,0,int function(int a, int b) { return a+b; });

prod = fold(arr,1,int function(int a, int b) { return a*b; });

Or generic, using Archetype:

fold(arr,0,Archetype!(T) function(Archetype!(T) a, T b) {return a+b;});

/Oskar



More information about the Digitalmars-d mailing list