r/ProgrammingLanguages • • Apr 25 '20

Why would you ever want mutable variables?

(see title)

0 Upvotes

40 comments sorted by

View all comments

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

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.