C++
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Sat Jul 8 00:47:39 PDT 2006
Fredrik Olsson wrote:
> Walter Bright skrev:
>
>> Chris Nicholson-Sauls wrote:
>>
>>> Except for "Array operations not implemented" as yet. Any idea when
>>> this much-coveted, much-anticipated feature will come to life? I
>>> don't mean to push, but I've dreamt of array-ops nearly since I first
>>> got involved with D back in 2003.
>>
>>
>>
>> It'll have to be a 2.0 thing.
>
> Perhaps not part of core language, put thought operator overloads. I
> guess there are a million reasons as to why not have them, but if I
> could choose this would be a nice syntax for both introducing operator
> overloads and properties to existing types:
>
> type int[] {
>
> int[] opAdd(int[] a) {
> assert(this.length == a.length);
> int[] r; r.length = this.length;
> foreach (i, v; this) {
> r[i] = v + a[i];
> }
> return r;
> }
>
> int sum() {
> int r = 0;
> foreach(v; this) {
> r += v;
> }
> return v;
> }
>
> }
>
> // Making these work;
> int[] a = [1, 2, 3];
> int[] b = [4, 5, 6];
> int[] c = a + b; // [5, 7, 9];
> int d = c.sum(); // 15
>
>
> // Fredrik
This gives me a thought. Currently we have the pseudo-member effect, which causes the
following to be possible:
# int sum (int[] arr) {
# int result = 0 ;
#
# foreach (i; arr)
# result += arr;
#
# return result;
# }
#
# int[] foo = [1, 2, 3, 4] ;
# int bar = foo.sum ; // bar == 1 + 2 + 3 + 4 == 10
Also, in D (theoretically at least) it seems all operators are rewritten as function
calls. Such that the expression (a + b) becomes (a.opAdd(b)). So, perhaps we could do
something like this:
# int[] opAdd (int[] a, int[] b)
# in {
# assert( a.length == b.length, "Array-Ops only applicable to arrays of equal length" );
# }
# body {
# int[] result = new int[a.length] ;
#
# foreach (i, x; a) {
# result[i] = x + b[i];
# }
# return result.dup;
# }
#
# int[] foo = [1, 2, 3] ,
# bar = [4, 5, 6] ;
#
# int[] xyz = foo + bar ; // (foo.opAdd(bar)) -> (.opAdd(foo, bar)) == [5, 7, 9]
Just a crazy thought.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list