my ideas for array operations
Bill Baxter
dnewsgroup at billbaxter.com
Fri Oct 5 18:59:57 PDT 2007
Gregor Richards wrote:
> Bill Baxter wrote:
>> dennis luehring wrote:
>>> i have some ideas for array operation
>>> hope they are "context free" and don't break any syntactic rules :-}
>>>
>>> OP ==> + - / ~ * and all the others
>>>
>>> #1 operator between (operator concatenated) array elements:
>>>
>>> syntax: array ~OP
>>>
>>> result-type: value-type of array
>>>
>>> examples:
>>>
>>> [1,2,3] ~+ ==> 1+2+3 = 6
>>>
>>> [1,3,4] ~* ==> 1*3*4 = 12
>>>
>>> ["a","b","c"] ~~ ==> "abc"
>>>
>>> #2 operator and "value" on each array element
>>>
>>> syntax: array @OP value
>>>
>>> value: array.value/applicable-type/function
>>>
>>> result-type: typeof(array)
>>>
>>> [1,2,3] @+ 10 ==> [1+10,2+10,3+10] = [11,12,13]
>>>
>>> (maybe .+)
>>>
>>> #3 operator between 2 arrays
>>>
>>> syntax: array1 OP array2
>>>
>>> result-type: typeof(array1)
>>>
>>> precondition:
>>> array1.value/applicable-type == array2.value/applicable-type
>>> array1.dimension == array2.dimension
>>>
>>> [a,b,c] + [d,e,f] ==> [a+d,b+e,c+f]
>>>
>>> usage:
>>>
>>> double v1[3] = [1,2,3]
>>> double v2[3] = [3,4,5]
>>>
>>> double norm = sqrt( ( v1 * v1 ) ~+ );
>>> double dot_prod = ( v1 * v2 ) ~+ );
>>> double mid = ( v1 ~+ ) / v1.length;
>>>
>>
>> -1
>>
>> Write some templates that use the existing operators.
>>
>> --bb
>
> Agreed. Votes--. Pointless.
>
> Besides, operators should avoid being O(n).
>
> - Gregor Richards
Here's a 10min prototype:
module accum;
template accum(string op, T){
T accum(T[] array) {
if (array.length == 0) assert(false, "Must have at least one
element");
if (array.length == 1) return array[0];
mixin ("T r = array[0] "~op~" array[1];");
foreach(elem; array[2..$]) {
mixin ("r "~op~"= elem;");
}
return r;
}
}
import std.stdio;
void main()
{
writefln( accum!("+",int)([1,2,3,4,5]) );
writefln( accum!("*",int)([1,2,3,4,5]) );
writefln( accum!("~",char[])(["D"," ","pro","gramming"]) );
}
--bb
More information about the Digitalmars-d
mailing list