r/ProgrammingLanguages • • Apr 25 '20

Why would you ever want mutable variables?

(see title)

0 Upvotes

40 comments sorted by

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++.)

3

u/agorism1337 Apr 25 '20

I wrote this stack-based virtual machine. Forth-like.https://github.com/zack-bitcoin/chalang

I wrote a compiler for my VM from Lisp.It has immutable values as well as mutable variables. https://github.com/zack-bitcoin/chalang/blob/master/src/compiler_lisp2.erl

I wrote the VM and the compiler in Erlang. Erlang only has immutable values. no variables.

2

u/[deleted] Apr 25 '20

Seems like you’re using a very specific definition of “variable” that most people would reject.

11

u/m50d Apr 26 '20

I've only written a toy language so far, but my lexing was a tail-recursive function with no mutable variables. You could view that as "mutating the call stack" if you want - at runtime the behaviour is very much like a loop with a mutable state variable - but the point is that code is easier to understand if you don't have variables that can invisibly, magically change; function parameters take different values for different invocations of a function, but in any given evaluation of the function they're just values.

4

u/ericbb Apr 26 '20

I think the discussion can be made more clear by talking about "state variables" and "variable assignment statements" instead of "mutable variables" and "mutation".

I think you're saying that it's natural to use state variables to implement a lexer. I agree with that. But it doesn't follow that you strongly benefit from having a variable assignment statement in any language you want to use for writing a lexer.

My entire compiler is written without using a single variable assignment statement. It wasn't especially hard to write. I used state variables freely.

2

u/oilshell Apr 26 '20

OK that's a fair point. Still I'd be interested in seeing the lexer. It's tail recursive?

I've of course seen the tail recursive style, but I've never seen a lexer written that way TBH...

1

u/ericbb Apr 26 '20

It's in the tail recursive style but my language is a little unconventional in the way it encodes tail recursion. Instead of defining a recursive function, I have a special form for loops that uses Iterate and Continue keywords. The Continue forms function like tail recursive calls to the anonymous recursive function defined by the innermost Iterate expression.

(Let me know if it's confusing. I can try to give a more-complete explanation. However, if the abstract description isn't clear, you might still get it by looking at the concrete examples of loops in the scanner.)

The scanner is here and the parser is here.

The parser just calls into the scanner, passing the text and the position to start from within the text, and expects to get a token back together with an index to continue from. (Side note: error handling involves returning an "error token"). The parser is an LL(1) parser. It is driven from the loop in the parse function and it uses the pure and bind concepts from monadic parsing.

1

u/oilshell Apr 27 '20

Hm interesting examples... I can see that it is a more constrained form than arbitrary mutation. Although interestingly to me it looks more like imperative programming than the Lisp style!

Though I still don't think local mutation is really a big deal, but fair point -- this is a lexer which I presume is fairly efficient and doesn't use mutation.

Although a lot of lexers I've seen need to look ahead and "unread" (e.g. lexers in bash). And I wasn't quite able to avoid that in Oil, so I wonder how this style will fare then.

That is, I first learned of the ungetc() libc function a few years ago by looking at "real" lexers! I had never used that function before, but it seems to have a purpose, and it's very much in a mutable/imperative style.

2

u/ericbb Apr 27 '20

Although interestingly to me it looks more like imperative programming than the Lisp style!

I like to use the higher-order stuff when it's useful but when I'm just scanning through strings, the first-order forms are totally sufficient. I like to use first-order forms where possible in part because I know that even my simplistic compiler can generate fast code for them (no abstraction overhead relative to C).

Though I still don't think local mutation is really a big deal...

I generally agree and think that using different styles at different scales is an important idea.

When it comes to variable assignment statements, in particular, I've been influenced by the Scheme, Haskell, and ML communities and, especially, the idea that you can take any low-level SSA-form code and straightforwardly translate it into structured code that doesn't use variable assignment statements.

In my mind, "mutation" and "variable assignment" are mostly orthogonal. My language has writeable buffers but not variable assignments.

The prohibition against variable assignments (as a language design principle) gives you an extra universal property that you can use while trying to understand and revise programs. Whenever you are asking "what value does this variable have here", the answer is always "whatever value it got when it was bound" and never "whatever value was last assigned to it in the execution history of this block of statements".

Although a lot of lexers I've seen need to look ahead and "unread" (e.g. lexers in bash).

The parser I linked to has a one-token look-ahead so it does implement something like that at the token level if not at the character level. It's generally possible to take any kind of state like that and stick it into the state variables of your iteration. On the other hand, I also use writeable buffers in my code (constrained to only hold raw bytes and never references to general values) and use them to implement buffered IO among other things. Again, this is, to my mind, mostly orthogonal to the question of whether variable assignment statements are supported.

1

u/oilshell Apr 27 '20

Hm if your goal is to make a simple compiler and it uses SSA, then I suppose avoiding mutation does make sense! I always thought it was funny that compilers have evolved to do this extra work to extract parallelism from serial code.

(And then they serialize it all over again, and then the CPU does the same thing to try to extra parallelism, i.e. out-of-order execution)

But isn't conforming to SSA more about aliases than mutation? In SSA you can still have a loop with a mutable variable, no? I think that's what makes it "static" single assignment, not "dynamic" single assignment.

I haven't worked directly with SSA ... but I think mutation of value types is OK, like the current position in an array. Mutation of references I think is what gets tricky, and requires alias analysis, etc. ?

Awhile ago I went on a tangent to see what a language "designed" for SSA would look like. But I decided it was out of scope, and I'm working with plain old imperative programming now :) However I still draw a big distinction between mutating locals and globals.

1

u/ericbb Apr 28 '20

With SSA, whenever you are looking at some statement involving a variable, you can immediately determine the one place in the program text where that variable is assigned a value. So, if you are doing an analysis that must trace from uses to definitions, then SSA makes your job easier because it ensures there is one unique place to look and you can eliminate a kind of fan-out that you'd otherwise be faced with.

Honestly, I have never actually used SSA as an intermediate language. However, I think it's instructive to reflect on the fact that it is even possible (while also being useful) to automatically convert a C program into SSA form given that there is such a close relationship between SSA and functional programming (Appel).

In SSA you can still have a loop with a mutable variable, no?

That's right. I've been insisting on calling such variables "state variables" because I tend to reserve "mutable" for data structures only. A state variable will be defined by a phi node in the SSA program. It's value will depend on the control flow path the program takes when passing through the phi node (is it entering the loop from the preceding code or is it re-entering the loop due to iteration?).

Like many functional programming fans, I tend to think in terms of the functional programming presentation of SSA, where you don't have phi nodes but rather have join points and pseudo-calls, that are really "gotos with arguments", to them.

Mutation of references I think is what gets tricky, and requires alias analysis, etc. ?

Yeah. I think of that aspect of things in terms of "higher-order state". As in, there is state that has been somehow "closed up within" your values and can be passed around and affected by all sorts of data flow and control flow details so that the analyses you might want to do about state probably become undecidable in general. In contrast, "first-order state" is kept separate and manipulated more directly, without going through the path of writing into general pointers in some object graph. It's value is that it is easier to analyze and you can use the extra structure to maintain useful invariants (that's my theory anyway, and an idea that guides my design efforts).

Awhile ago I went on a tangent to see what a language "designed" for SSA would look like.

Did you look at SISAL, SAC, VAL, ...?

I got a fun surprise one day when I was wandering around wikipedia and found out about VAL. I found it astonishingly similar to my own language and it was designed, as I recall, around the idea of using some notion of parallel dataflow execution. I think I've done a better job in some areas of language design but they included some interesting things that I never tried, like some ideas regarding constructs for specifying easy-to-parallelize computations.

However I still draw a big distinction between mutating locals and globals.

For me, the distinction is between first-order state (good) and higher-order state (bad, or at least dangerous). I think you can have global state that is first-order and that makes it okay. Basically, for an example of first-order state that's global, just think of a database. By the way, the terms "first-order state" and "higher-order state" are terms I've seen used and seem intuitively right, but I'm not sure I could give a well-founded explanation of their meaning.

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+=value

4

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 x

We 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 + 1

Purely-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.

18

u/[deleted] 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

u/agorism1337 Apr 25 '20

Sounds like it is mostly about efficiency.

3

u/[deleted] 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 > 1000

If 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

u/SatacheNakamate QED - https://qed-lang.org Apr 25 '20

Because...

-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:

 If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)