views:

303

answers:

2

In an imperative, object orients language, would make more sense to have mutable or immutable closures?

For example:

int i=5;
function() f={print(i);};
f();
i=6;
f();

If the closure is mutable, this would print:

5
6

If it is immutable, it would print:

5
5

I realize that even with immutable closures, you could still do this:

class I {int i;}
I i=new I();
i.i=5;
function() f={
    I j=i;
    print(j.i);
};
f();
i.i=6;
f();

So, would it be better to have mutable, or immutable closures, or have the option for both? Immutable closures seem easier to implement, so at this point, I think I'll go with that, unless there is a good reason not to.

+4  A: 

Imperative languages are typically built around the concept of state. Hence it makes more sense for language features to reflect that, including closures. Yes, this behavior can be confusing at times but it's part of the problem and advantage to having state in your application.

I think the best proof of this argument is to look at some of the more recently languages which have closure support. Both C# and VB.Net, imperative OO languages, chose to have mutable closures. While F#, a functional language, has immutable closures (mainly deriving from the idea that F# is immutable by default).

Also what would it actually mean to have an immutable closure in an imperative language? Most people think of this as making the variables equivalent to C#'s readonly. Sure value types would be protected from modification, but what about mutable reference types. You wouldn't be able to change where the variable pointed to, but you could call a mutating function and get a similar effect. For example.

class Student {
  public string Name { get; set; }
}

void Example() {
  var student = new Student() { Name = "foo" };
  Action() del = () => 
    { student.Name = "bar"; };
  del();
}

This could be implemented with an immutable closure as I don't actually modify where the variables point to. However I am clearly still doing a mutating operation.

JaredPar
+3  A: 

Ought languages have lambdas that capture by value or capture by reference? Decide for yourself, but see "On lambdas, capture, and mutability" for more commentary.

Brian