Idea: Immutable blocks within functions
Xinok
xinok at live.com
Sat Sep 7 15:57:38 PDT 2013
For me, one of the annoyances of working with immutable data is
simply initializing data. Immutable variables have to be
initialized upon declaration and cannot be modified after that
point. This is made more difficult if you have several immutable
variables to initialize in conjunction with one another
Currently, the following syntax is not allowed within functions:
immutable{ }
I propose enabling this syntax to have special usage within
functions for initializing immutable variables. Variables would
be mutable within the scope of the immutable block, and immutable
outside of that scope. That scope would be limited to the same
access restrictions as pure functions to ensure mutable
references to the data can't escape.
While something similar could be accomplished using nested
functions, they're limited to initializing one immutable variable
at a time and less efficient since they must utilize a context
pointer to access outside data. I think my idea has a nice allure
for greater simplicity and flexibility for initializing immutable
variables.
An impractical example:
void foo()
{
immutable
{
int[] arr = ...;
int[] arr2 = arr.dup;
sort(arr); // arr is still mutable
int[] arr2 = arr.dup;
reverse(arr2);
arr ~= arr2;
}
sort(arr); // Error is thrown because arr is now immutable
}
Considerations:
* Global and thread-local variables within an immutable block
would be immutable; otherwise, the control flow could re-enter
the immutable scope and change the values of those variables.
* There may be issues with reflection since the type of the
variable suddenly changes from mutable to immutable.
So what do nested immutable blocks imply? The same as having a
pure function within a pure function.
void foo()
{
immutable
{
int[] arr = ...;
immutable
{
// This statement would throw an error
int value = arr[0];
// Here, arr is still mutable.
// So like a pure function, access to outside
// mutable variables isn't allowed.
}
}
}
More information about the Digitalmars-d
mailing list