immutable types & variables by default

188 views
Skip to first unread message

Tuur Benoit

unread,
Jun 7, 2014, 5:39:34 AM6/7/14
to juli...@googlegroups.com
It's nice to see that immutable types have been added to Julia.

1. I'm wondering if there is a reason not to have types immutable by default? 

The advantages are clear: the compiler can take advantage of the fact that the type is immutable. In addition, it's easier to reason about the instances of the type.
From my experience with some medium-size projects in F# regarding numeric computation, I can say it that for me it was not a constraint at all. I did not have to create a mutable type at all for these projects. Of course, an array for example has to be mutable: if you have a large matrix, then you cannot afford to make lots of copies of it, so you should be able to modify its elements in place. But it could be advantageous if the elements it contains are immutable. 

By making types immutable by default, you encourage the user to declare them that way.


2. Furthermore, what about immutable variables/bindings? 

Again refering to F#, in that language bindings are immutable by default (http://www.tryfsharp.org/Learn/getting-started#bindings-values). In numerical computations, most of the time you are just transforming/mapping inputs to outputs, giving intermediate results a proper name. 
With a light-weight syntax, this is not cumbersome. In addition, you see it explicitely when something is mutable.

E.g. immutable binding (standard):
x = 3
x
= 5 #error

E.g. mutable binding:
mutable x::Int = 3
x
<- 5 #no error

I'm just thinking, please give me your thoughts.

Stefan Karpinski

unread,
Jun 8, 2014, 4:17:16 PM6/8/14
to Julia Dev
We debated making immutable composites the default, but ultimately decided that it would be friendlier to programmers coming from conventional imperative programming languages to default to composites being mutable. It's also not really the case that one is the default, it's just that the more obvious keyword, "type", gives you a mutable type.

Immutable bindings by default would be very annoying and provide no real benefit. The current scoping rules for variables allow most code to be written without any variable declarations or annotations. Since updating local variables is common, defaulting to constant bindings would force annotations all over the place, making the language significantly noisier and more fussy. I also don't really see the point of constant bindings for local variables – it's completely straightforward for the parser to determine if a local variable is ever changed or not, so why bother telling it what it already knows? We allow the const keyword for local variables, but it currently doesn't have any effect because it's unnecessary – if you want a constant local binding, just assign the variable once and then don't change it.
Reply all
Reply to author
Forward
0 new messages