Immutable nested functions

Daniel Murphy yebblies at nospamgmail.com
Thu Jan 6 19:34:35 PST 2011


"Tomek Sowinski" <just at ask.me> wrote in message 
news:20110104222343.00004d47 at unknown...
> Nested functions to be immutably pure must also guarantee that nothing 
> gets mutated through its stack frame pointer. But there's a problem -- the 
> compiler won't accept 'immutable' on a nested function. I think it 
> should -- just like an immutable member function (e.g. in a class) is 
> allowed to play only with immutable members of that class, an immutable 
> nested function should be allowed to play only with the immutable members 
> of the stack frame. It may seem a lesser change but I'm pretty excited as 
> it solves the long-standing problems with immutable structure 
> initialization.
>

>just like an immutable member function (e.g. in a class) is allowed to play 
>only with immutable members of that class

Defining a member function to be immutable doesn't mean it can only access 
immutable member variables, it means it must be called with an immutable 
class reference.

class C
{
  void fun() immutable {}
}

void main()
{
  auto c = new C();
  c.fun(); // error
  auto i = new immutable C();
  i.fun(); // ok
}

For nested functions, the reference is to the enclosing function's stack 
frame.  What does it mean to have this be immutable?  Maybe this makes sense 
if EVERY variable in the enclosing stack frame is immutable?

Is there any reason you couldn't just use static nested pure functions?

void main()
{
  static pure Node* grow_tree(int breadth) // strongly pure
  {
    ....
  }
  immutable Node* tree = grow_tree(...);
}




More information about the Digitalmars-d mailing list