Thread overview | |||||
---|---|---|---|---|---|
|
August 29, 2012 Call a function on an entire slice | ||||
---|---|---|---|---|
| ||||
D provides ways to operate on an entire (sub) slice: int[] a = ... ; a[] *= 5; //Multiply everything by 5. a[0 .. 2] = 3; //Set indexes 0 to 1 to the value 3. I was wondering if there was any way to do this for a specified function? ---- struct S { void foo() { writeln("foo"); } } void bar(S s) { writeln("bar"); } void main() { S[5] a; a[].foo(); //undefined identifier 'foo' a[].bar(); //cannot implicitly convert expression (a[]) of type S[] to S }; ---- I know I can just foreach it, but it doesn't quite have the same expressive power. If the built in arithmetic types have this power, why not functions? |
August 29, 2012 Re: Call a function on an entire slice | ||||
---|---|---|---|---|
| ||||
Posted in reply to monarch_dodra | On 08/29/2012 03:38 PM, monarch_dodra wrote: > D provides ways to operate on an entire (sub) slice: > int[] a = ... ; > a[] *= 5; //Multiply everything by 5. > a[0 .. 2] = 3; //Set indexes 0 to 1 to the value 3. > > I was wondering if there was any way to do this for a specified function? > > ---- > struct S > { > void foo() > { > writeln("foo"); > } > } > > void bar(S s) > { > writeln("bar"); > } > > void main() > { > S[5] a; > a[].foo(); //undefined identifier 'foo' > a[].bar(); //cannot implicitly convert expression (a[]) of type S[] to S > }; > ---- > I know I can just foreach it, but it doesn't quite have the same > expressive power. > Yes it does. > If the built in arithmetic types have this power, why not functions? Because the built-in arithmetic vector operators are supported by hardware. |
September 01, 2012 Re: Call a function on an entire slice | ||||
---|---|---|---|---|
| ||||
Posted in reply to Timon Gehr | >Because the built-in arithmetic vector operators are supported by hardware.
Should that matter from a user's point of view? It's a clean syntax that should be made more univeral. It'd be nice to be able to do things like:
return a[] + b[];
and using that in lambdas as well without needing the unnecessary repetition of
return a[] = a[] + b[];
|
Copyright © 1999-2021 by the D Language Foundation