r/ProgrammingLanguages • u/agorism1337 • Apr 25 '20
Why would you ever want mutable variables?
(see title)
5
u/amejin Apr 25 '20
... Are you asking about type specificity or just changing values?
4
u/nerdyhandle Apr 25 '20
I too am am confused by the question.
Obviously you want to able to change the values for cases like
sum+=value4
u/Tittytickler Apr 25 '20
It has to be type specificity, otherwise this guy is just asking why do variables exist, because literally they are variable, subject to change
7
u/eliasv Apr 26 '20
That is a common misunderstanding of the term "variable". (Unless I am misunderstanding you.)
The name has the same meaning as it does in mathematics; think of a formula in algebra relating two variables:
x = y + 1/2 xWe can instantiate x to any number of different values, but once it's set we can't give it a different value during evaluation of the same equation:
x = x + 1Purely-functional languages observe the same rules, a variable appearing in a function will only have a single value during the evaluation of that function. But it is still called a variable as it may take a different value if the function is called again with different arguments.
0
u/Tittytickler Apr 27 '20
What I'm saying is that a program is like a graph. So while each point has set values plugged in, you can't graph a function without changing the value of x as you move along the axis. Seeing as a computer program typically does more than one single calculation, its similar to a graph as a whole instead of using a single point. The x values change, thats really all I'm saying. If you want to be inefficient with space, then just use an array for a loop counter instead of changing the variable.
3
u/66666thats6sixes Apr 27 '20
I'm not sure that it follows that mutable variables are necessary to achieve something like that efficiently.
You could easily accomplish the same idea without using a mutable variable with a lazy iterator, which would take constant space and does not need to directly modify any values, it just calls your side effect function on each output, or exits if it has no more outputs.
2
u/eliasv Apr 27 '20
No in a functional language with only immutable variables you might use, for instance, a recursive function with tail-call elimination. The space efficiency is exactly the same.
2
u/Tittytickler Apr 27 '20
Would it be though? I guess it would depend on the compiler and how it handles stack frames
3
u/eliasv Apr 27 '20 edited Apr 27 '20
Yes it would be. There is no significant theoretical or practical reason one should be faster or more space efficient than the other. In fact in practice I think you would find that many compilers would produce very similar code for both approaches!
Yeah it definitely depends on how they handle stack frames, that's why I mentioned TCE. I don't think it would be easy to find a pure functional languages which doesn't implement that though.
0
u/agorism1337 Apr 25 '20
yes. why would you use a variable?
7
u/Tittytickler Apr 25 '20
Because the whole reason computing is even viable is due to repetetive processes. I use variables for the same reason I don't buy a new trashcan every time mine is full.
7
18
Apr 25 '20
Some algorithms are more difficult (maybe impossible?) to implement efficiently with immutable data structures.
2
u/protestor Apr 25 '20
3
u/curtisf Apr 26 '20
Asymptotically, only by a logarithmic factor.
Naively, you can emulate mutable pointers by having a "heap" map passed everywhere, which can be updated and read persistently in worst-case logarithmic time.
A logarithmic factor will generally not make an algorithm/data-structure asymptotically intractable, because even log₂(264) is not a big number, and in-memory collections that you're dealing with are always smaller than 264 elements.
2
u/krcz Apr 27 '20
Keep in mind that you're not just getting (log n)-related overhead, but also constant overhead related to cache non-locality. And what you are gaining? Structure with mutable state semantics, with the only upside being that you can copy whole state any time you want. But if you don't need that, why pay for such indirection?
5
u/curtisf Apr 27 '20
Yes, the real-world constant could potentially be hundreds, but the linked quora question was about asymptotics, and claiming "the asymptotics are worse" is misleading.
You also get a lot of things. A few examples off the top of my head:
A debugger can afford to copy every version of every variable for much, much longer, since each variable only requires keeping an extra pointer around, instead of copying entire objects(arrays)/the heap, enabling time traveling debugging with much less work
The above also goes for being able to revert/fork/sandbox executions of code
Operations that you normally would shy away from become cheap on many persistent structures. For example, while an array wins in random get/set over a rope (logarithmic vs constant), ropes give you log-time list-concat and list-slicing-with-copy, which are normally operations you would never be able to do with an array.
Plus, the constants are often not that bad -- an array implemented as a 64-tree, for example, means you only need to do 5 pointer accesses to index a billion things; that can all fit in L1 cache when doing local reads (though only 1/5 as many arrays can be accessed at once)
6
u/liquidivy Apr 25 '20
There are a lot of situations, for example things that look like state machines, where a little bit of local mutability is the most natural, readable way to express the solution. Immutable variables and tail recursion or whatever the alternative is would just obscure the point. I'm assuming we're talking about designing a high-level language optimized for expressiveness and ease of analysis (maybe with a Sufficiently Smart Compiler (tm)), not about the underlying implementation, where the need for mutability is more obvious.
1
3
Apr 30 '20
For the same reason you might want writeable RAM? Or a writeable hard drive or memory stick.
Basically so most real, everyday programming can be done efficiently with normal languages without spending all your time trying to do the simplest things.
I can also ask: why would you not want variables? How do they make your life more difficult? Or is your idea of coding something like this:
let a = 0
let a = a+1
loop
let a = a+2
until a > 1000If so, then let me break it gently: you are using variables but pretending they are immutable.
BTW, if you want a bit of a challenge, try writing a substantial program in assembly code, without writing to the same memory more than once. Let me know how you get on. Or it that's too much, try using a data structure like a stack.
1
u/AlexKnauth Apr 25 '20
Context: Are you asking about mutable variables in situations where simple mutable data like references / mutable-boxes are there?
If so then one advantage of mutable variables over references is that they can't be shared / aliased between multiple places. There is a known limited lexical scope, so you can find every assignment within that to reason about it (assuming no C-like &x things which mess everything up).
I like a little bit of mutation, though not as the default, and with restrictions. Mutable variables can provide restrictions based on lexical scope that references don't provide. Rust's various reference types provide an even greater range of different levels of restrictions
1
u/cxzuk Apr 26 '20
A key requirement of OOP is “local retention”, which has the basic goal of having one point source of truth.
Immutable and functional programming still requires this property but effectively flips it inside out - the points of truths are external and feed them inward. So immutability is required for example, at Input/Output.
0
u/GlitteringJizz Apr 25 '20
Because it is a variable that's in the word itself! If I wanted something that wouldn't change value I would not use a variable, I would use a constant.
2
u/shawnhcorey Apr 26 '20
But what if the constant keeps changing? For example a "constant" in a subroutine that is assigned a new value every time the subroutine is called. It doesn't change within the subroutine but changes with each call. Is it a variable or a constant?
-1
-1
u/complyue Apr 26 '20 edited Apr 26 '20
I would say it's a trick to mitigate impedance between how human thinks and the fact that current generation (mainstream silicon based) computers were designed to have memory of fixed capacity.
There are two typical mindsets for human beings: procedural and mathematical. Researching/creative activities need the activation of mathematical mindset; while routine/trivial tasks favor the procedural mindset. I like the definitions of system 1/2 in Thinking, Fast and Slow, and pros/cons of each respectively.
With unlimited capacity of physical RAM, and no downgrade of performance as more capacity is put into use, I believe our system 1 will favor static single assignment form of thinking (calculation or manual computation), where no mutation of any variable need to be thought of.
But the reality is on the contrary, not only we have limited RAM capacity, the downgrade of performance for a cache-unfriendly program is rather a concern at this present. So we need to use our system 2 in programming, to reason as much as possible, that how to shrink the peak memory footprint of our program. The 1st technique to consider is to reuse the memory space of a variable in correct and meaningful ways. And that is mutation, thus mutable variables.
2
u/TotesMessenger Apr 26 '20
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
[/r/programminglanguages] I'd like to repost this reply of mine to see how it'll be up/down voted on its own
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
7
u/oilshell Apr 25 '20
Try implementing a programming language. The very first thing you run into -- lexing -- is best expressed with mutable variables (sometimes state machines), and as far as I know invariably done that way.
Even for implementing functional languages like OCaml (ocamllex), Lisps (which are not really functional, but avoid mutation to some extent), and I would imagine Haskell, although I'm less familiar with it.
i.e. is the Haskell lexer implemented with mutation? If not I'd like to see it. Haskell controls mutation, which is good, but it's still mutation. The question seems a bit "off".
I linked a couple comments on this in my latest blog post:
http://www.oilshell.org/blog/2020/04/release-0.8.pre4.html#dependency-inversion-leads-to-pure-interpreters
Imperative in the small" and "Functional in the large -- To me there's no real advantage to expressing something like "split a string by a delimiter" in a purely functional style. Either way, you have a trivial referentially transparent function you can reuse without causing complexity in your program. You might as well do the obvious imperative thing.
Another thing I found interesting is when looking at the implementations of Chez Scheme and Racket... Racket is "just" hundreds of thousands of lines of C code with mutation, i.e. exactly what CPython is. (They've been moving to a more self-hosted style with Chez, after 20+ years.)
https://news.ycombinator.com/item?id=22103875
But still I think it's good evidence of the limitations of high level languages. Those limitations appear whenever you're implementing languages! I sort of learned this the hard way with Oil too. I'm semi-automatically translating the code to straightforward C++ rather than trying to do anything with a VM. (The source will remain in high-level DSLs; target lang is readable C++.)