Skip to main content

Control Flow

·349 words·2 mins
Documentation - This article is part of a series.
Part 9: This Article

If Statements
#

If statements in Sage are similar to those in other languages. The syntax is as follows:

let a = 5;
if a == 5 {
    println("a is 5!");
} else {
    println("a is not 5!");
}
Output:
a is 5!

You can also use else if to chain multiple conditions together.

let a = 6;
if a == 5 {
    println("a is 5!");
} else if a == 6 {
    println("a is 6!");
} else {
    println("a is not 5 or 6!");
}
Output:
a is 6!

Loops
#

Sage has two types of loops: for and while.

For Loops
#

For loops in Sage are similar to those in C – they have an initialization, a condition, and an increment.

for let mut i=0; i<5; i+=1; {
    println(i);
}
Output:
0
1
2
3
4

While Loops
#

While loops are also similar to those in C.

let mut i = 0;
while i < 5 {
    println(i);
    i += 1;
}
Output:
0
1
2
3
4

Match Statements
#

Match statements in Sage are similar to switch statements in C, but more powerful. They can be used to destructure data from structs, enums, tuples, and match against constant expressions.

enum Direction {
    North,
    South,
    East,
    West
}

let dir = Direction of North;
match dir {
    of North => println("Going North!"),
    of South => println("Going South!"),
    of East => println("Going East!"),
    of West => println("Going West!")
}

let point = {x=0, y=0};
match point {
    {x=0, y=0} => println("At the origin!"),
    {x=0, y} => println("On the y-axis at (0, ", y, ")"),
    {x, y=0} => println("On the x-axis at (", x, ", 0)"),
    _ => println("Somewhere else!")
}
Output:
Going North!
At the origin!

If Let Statements
#

If let statements are a shorthand for matching against an enum and binding the value to a variable.

enum Option<T> {
    Some(T),
    Nothing
}

let o = Option<Int> of Some(5);

if let of Some(x) = o {
    println("The value is ", x);
} else {
    println("The value is Nothing");
}
Output:
The value is 5
Documentation - This article is part of a series.
Part 9: This Article