May 22, 2010
Pelle:

> It's not a very good rule anyway:
> 
> void inc_all(int[] xs) {
>      foreach (ref x; xs) {
>          x += 1;
>      }
> }
> 
> Wouldn't gain anything from ref, and wouldn't work with const.

You are wrong, it works correctly with ref:

import std.stdio: writeln;

void inc_all(ref int[] array) {
    foreach (ref x; array)
         x++;
}

void main() {
    auto a = new int[10];
    a.inc_all();
    writeln(a);
}


It prints 1 1 1 1 1 1 1 1 1 1

Bye,
bearophile
May 22, 2010
On 05/22/2010 01:00 PM, bearophile wrote:
> Pelle:
>> Wouldn't gain anything from ref, and wouldn't work with const.
>
> You are wrong, it works correctly with ref:

Yes, it works, but it doesn't gain anything from it, which is what I said. :)
May 22, 2010
Pelle:
> Yes, it works, but it doesn't gain anything from it, which is what I said. :)

Then what you have said was useless.

Bye,
bearophile
May 22, 2010
On 05/22/2010 01:28 PM, bearophile wrote:
> Pelle:
>> Yes, it works, but it doesn't gain anything from it, which is what I
>> said. :)
>
> Then what you have said was useless.
>
> Bye,
> bearophile

How so? Passing by reference is slower, and sometimes completely meaningless. Therefore, having a rule that requires passing by ref is not a good.

Also:

int[] get_xs() { return new int[](100); }

void main() {
    get_xs.inc_all;

    get_xs.inc_all_by_ref; // Error: get_xs() is not an lvalue
}
May 22, 2010
On 05/22/2010 06:28 AM, bearophile wrote:
> Pelle:
>> Yes, it works, but it doesn't gain anything from it, which is what I
>> said. :)
>
> Then what you have said was useless.

No it isn't. The point Pelle was making is that there are three use cases for parameter passed arrays:

1. read-only (corresponds to const)
2. read/write + resizing/reallocation (corresponds to ref)
3. read/write, no resizing (corresponds to no modifier)

With (1) and (2), if I see those modifiers in the signature, I can deduce the use of the array.

With (3), I can't really tell from the signature if the programmer meant that use case or forgot something, but the case is valuable enough that it should be enforceable.

With associative arrays, case (3) is rare (is it even possible?) to the point that it can drop out of consideration.
1 2
Next ›   Last »