Let Bindings#
Variables are bound in Sage using the let
keyword. You can optionally include the type of the variable to be typechecked against.
// Create a variable named a, with the value 5
let a = 5;
let b = {x=5, y=6};
let c: (Int, Int, Int) = (1, 2, 3); // Optionally include the type
println(a);
println(b);
println(c);
Output:
5
{x=5, y=6}
(1, 2, 3)
5
{x=5, y=6}
(1, 2, 3)
Mutability#
You can make a variable as mutable with the mut
keyword. If you try to assign to a variable that isn’t mutable, the compiler will yell at you!
let mut a = 5;
println(a);
a = 6;
println(a);
Output:
5
6
5
6
Destructured Let Bindings#
In many instances, users want to be able to decompose the attributes of structures or tuples into variables.
let (a, {mut x, y}) = (1, {x=5, y=6});
println(a, ", ", x, ", ", y);
x = 999;
println(a, ", ", x, ", ", y);
Output:
1, 5, 6
1, 999, 6
1, 5, 6
1, 999, 6
Variables And Scope#
Variables are not captured by functions – functions mainly act as procedures. Additionally, variables may not be referenced before their definition.
println(a);
let a = 5;
Error:
LIR error: symbol a not defined
2 │ println(a);
LIR error: symbol a not defined
Scopes may also be created with {}
blocks.
{
let a = 5;
println(a);
}
println(a);
Error:
LIR error: symbol a not defined
5 │ println(a);
LIR error: symbol a not defined