Identity Declarations, Variables & REF Modes

An identity declaration MODE identifier = value binds an identifier to a value permanently — like const in C, but for any mode including procedures and rows.

26.1 Identity declarations: names for values

An identity declaration MODE identifier = value binds an identifier to a value permanently — like const in C, but for any mode including procedures and rows.

INT n = 10;                   # n IS the value 10 — it cannot be assigned #
REAL e = exp(1);
[] INT primes = (2, 3, 5, 7, 11);
PROC square = (REAL x) REAL: x * x;

26.2 Variables are references

A variable is a name (a reference, i.e. an address) that refers to a value. Its mode is REF *something*:

Read the long form as: "generate a new local INT cell (LOC INT), assign 5 to it, and let x be the identity of that cell". So x has mode REF INT, and assignment x := 7 stores into the cell that x names.

Mode of identifier INT x:= 5 / INT x REF INT alias = x REF INT (the same cell as x) yes, changes x REF INT p:= x REF REF INT (a pointer variable)

p := y repoints; REF INT (p) := 3 stores through

INT x := 5;                   # abbreviation ... #
REF INT x = LOC INT := 5;     # ... for this identity declaration #

26.3 Aliases and pointer variables

BEGIN
   INT x := 1, y := 2;
   REF INT alias = x;           # another name for x's cell #
   alias := 10;
   print((x, newline));         # 10 #

   REF INT p := x;              # p is a variable holding a reference to x #
   REF INT (p) := 20;           # store 20 into what p refers to (x) #
   print((x, newline));         # 20 #
   p := y;                      # now p refers to y #
   REF INT (p) := 30;
   print((y, newline));         # 30 #
   INT v = p;                   # dereferenced twice automatically: v = 30 #
   print((v, newline))
END

26.4 Identity relations: IS and ISNT

:=: (or IS) and :/=: (or ISNT) compare references, not values:

NIL is the reference to nothing; it can be of any REF mode.

REF INT r = x;
print((r IS x, newline));        # TRUE: same cell #
INT z := 20;
print((REF INT (z) IS x, newline));   # FALSE: different cells (even if equal values) #

26.5 Why this design?

Making variables just "identities of references" removes the special status of variables: references can be stored in structures, passed as parameters (REF INT parameters give call by reference), returned from procedures, and combined orthogonally with every other mode. The cost is that programmers must understand dereferencing — the subject of the next chapter.