We can create variables using
:=
which both declares new variables and assigns values to them. The variable name goes on the left and the value goes on the right, e.g.
x := 42
Variables in Ra have some differences from other programming languages. One of the main ones is that we can create relation variables (relvars), e.g.
planet := {planet_name:str, orbit_period:float, gravity:float}{
["Mercury", 88, 0.38],
["Venus", 224.7, 0.91],
["Earth", 365.25, 1.00],
["Mars", 687, 0.38],
["Jupiter", 4331, 2.36],
["Saturn", 10747, 0.92],
["Uranus", 30589, 0.89],
["Neptune", 59800, 1.12],
}
planet
┌─────────────┬──────────────┬─────────┐ │ planet_name │ orbit_period │ gravity │ ├─────────────┼──────────────┼─────────┤ │ Earth │ 365.25 │ 1.00 │ │ Jupiter │ 4331.00 │ 2.36 │ │ Mars │ 687.00 │ 0.38 │ │ Mercury │ 88.00 │ 0.38 │ │ Neptune │ 59800.00 │ 1.12 │ │ Saturn │ 10747.00 │ 0.92 │ │ Uranus │ 30589.00 │ 0.89 │ │ Venus │ 224.70 │ 0.91 │ └─────────────┴──────────────┴─────────┘
And we can then use these variables in relation expressions (ignore the new syntax for now, it will be explained soon), e.g.
planet[orbit_period < 500]{planet_name}
┌─────────────┐ │ planet_name │ ├─────────────┤ │ Earth │ │ Mercury │ │ Venus │ └─────────────┘
Note: in Ra there is no nil, NULL or undefined: variables are given a value whenever they are created.
Here are some more things to note about variables in Ra:
- variable names beginning with a
$are global (so in a sub-routine they cannot be shadowed by a local variable) - global relational variables (relvars) are persistent: their values survive Ra restarts
- global relvars stored in the same directory are known as a schema
- global relvars in a schema are subject to relational constraints stored in the schema
$constraintrelvar
Heading
We can use heading(frame) to return the heading for the current scope, i.e. each local variable.
heading(frame)
| attr | type |
|---|---|
| x | int |
| planet | {planet_name:str,orbit_period:float,gravity:float} |
Drop
We can destroy a variable using drop. e.g.
drop x
heading(frame)
| attr | type |
|---|---|
| planet | {planet_name:str,orbit_period:float,gravity:float} |
If the variable is a global relvar the drop also removes the persistence, so care should be taken before using it.
Drop prevention
For important persistent relvars, a good idea might be to add a constraint to prevent accidental dropping. Constraints are discussed later, but an example to protect a relvar, $R, might be:
$constraint := $constraint | dee(name:="$RC1", rule:="assigned($R)")
Constraint $RC1 checks that $R, once it exists, continues to exist after any assignment or drop (thus preventing any drop).
Another approach would be:
$constraint := $constraint | dee(name:="$RC2", rule:="assigned($R) and not empty($R)")
Constraint $RC2 checks both that $R exists and that it has at least 1 tuple, which guards against dropping but also prevents any emptying e.g. via $R := $R - $R.