5

I believe there are languages where all names with associated values cannot have their associated values changed. An example would be a language where all names behave like a does in the following C code:

int main(void)
{
  const int a = 0;
  a = 1;
}

i.e., all names act like what C calls a "read-only variable" here.

I know that certain constructs, like C's for loop, wouldn't be possible if one could not reassign variables. But I believe that languages where variables are exclusively read-only will use tail-recursive functions to accomplish looping.

If a language does not permit assigning new values to variables, what features (like tail recursion, in the above example) are needed to allow for programs to be written, that would otherwise be difficult / impossible to write without reassignment?

1 Answers1

7

With only constants, and without any variables, all your programs would be totally predictable and -- through constant propagation -- could be simply rewritten producing directly the expected output.

How would you manage user input in such a world ? How would you define even simple arithmetic functions, like f(x)=x^2 without precalculating and embedding in your program an infinity of combinations ?

However, there are several functional languages around. In these you have constants as in any language. But also variables/parameters, which can take a value (e.g. function parameter, user input), but can't be changed thereafter. We then don't talk about constants but about immutable variables.

In this functional approach you can write programs having the full expressiveness of a turing machine. The code is easier to analyze in terms of value propagation, as each function is stateless (i.e. it depends only on the function's input). And you don't have to cope with side effects on global or local variables. Keep in mind however that such functional language (e.g. Caml, or F#) are not yet mainstream.

Christophe
  • 81,699