Idea: Immutable blocks within functions

Dmitry Olshansky dmitry.olsh at gmail.com
Sat Sep 7 16:22:51 PDT 2013


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 ();

But if you don't require purity you may escape a mutable reference 
somewhere (from within the immutable block where it is mutable):

int[] global;

{
   immutable
   {
	int[] arr = ...;
	global = arr;
   }
   ... whopse now immutable arr can be changed elsewhere...
}

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

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list