May 16, 2013
On 05/16/2013 03:20 AM, bearophile wrote:
> TommiT:
>
>> If I needed to initialize only one const variable, I could use a lambda:
>>
>> const string[100] int__str = {
>>     string[100] tmp;
>>     // ... init tmp ...
>>     return tmp;
>> }();
>>
>> ...But I can't see any easy solution for initializing two or more
>> const variables at the same time.
>
> Once we have a tuple unpacking syntax, you return and assign to two
> const variables at the same time.
>
> Bye,
> bearophile

Until then, we have to define a local Tuple variable ('vars' below):

import std.conv;
import std.typecons;

void foo(size_t N)()
{
    auto init() {
        string[N] int__str;
        int[string] str__int;

        foreach (i; 0 .. N) {
            auto str = to!string(i);
            int__str[i] = str;
            str__int[str] = to!int(i);
        }

        return tuple(int__str, str__int);
    }

    const vars = init();

    const string[N] int__str = vars[0];
    const int[string] str__int = vars[1];
}

void main()
{
    foo!100();
}

Ali
May 16, 2013
On Thursday, May 16, 2013 11:32:39 TommiT wrote:
> On Thursday, 16 May 2013 at 08:31:27 UTC, Jonathan M Davis wrote:
> > Normally, there's no performance hit to doing any of this, but
> > it is true that
> > that's a potential issue in your example, because it's a static
> > variable. [..]
> 
> I assume you mean the variable is statically allocated. Which, I assume, means that there's an actual memory copy involved when such variable is cast to immutable.

I mistyped. I meant static array. The variable isn't static. But yes, the problem is that the array is copied when the assignment is made.

> Here's some more of the logic behind my suggestion:
> 
> Any hoops, that the programmer has to go through in order to make his function-local variable a const/immutable, discourages him from making the variable const/immutable. To me, it seems that the path of least resistance for the programmer is simply not make it const/immutable. By discouraging const-correctness we encourage writing bugs.

Except that what you're suggesting is effectively saying that you can write to a const variable, which violates the type system. It must be fully initialized in one go if it's const or immutable. Creating it as mutable and casting avoids this problem entirely and is very easy to do. I really don't see it as much of a problem. And by simply using a nested function, you not only are able to just initialize the variable in one go, but the code is cleaner because all of the mutation is encapsulated.

- Jonathan M Davis
1 2 3
Next ›   Last »