Idea: Immutable blocks within functions

Xinok xinok at live.com
Sat Sep 7 16:36:55 PDT 2013


On Saturday, 7 September 2013 at 23:22:59 UTC, Dmitry Olshansky 
wrote:
> 08-Sep-2013 02:57, Xinok пишет:
>> 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
>
> [snip]
>
>>
>> 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
>> }
>
> A pure lambda can achieve the same unless, of course, purity is 
> out of question:
>     immutable arr = {
>         int[] arr = ...;
>         int[] arr2 = arr.dup;
>         sort(arr); // arr is still mutable
>
>         int[] arr2 = arr.dup;
>         reverse(arr2);
>         arr ~= arr2;
> 	return arr;
>     } pure ();

Both arr and arr2 would exist as immutable arrays outside of that 
scope. That's what I meant by, nested functions could only 
initialize one immutable variable at a time, because you can only 
return one value to initialize the immutable variable with. With 
immutable blocks, you can initialize several immutable variables 
simultaneously.

> Basically even not yet completely outlined the feature already 
> pulls in escape analysis. Not going to fly IMHO.

They follow the same rules as pure functions. They can only 
access immutable  data, can only call pure functions, etc. No 
need for escape analysis, no need to reinvent the wheel. 
Furthermore, if the capabilities of pure functions is extended, 
so is the capabilities of immutable blocks.


More information about the Digitalmars-d mailing list