In this section, we would be talking about if-else statements, Recursions and Loops for repetitive tasks.
The concept of conditional statements is general and quite straightforward but in comparison to Cairo 0.x, Cairo 1.0 came with a new option for conditionals: else if
.
let status = true;
if (status == true){
...
} else if (status == false){
...
} else {
...
}
Recursions were the only option for repetitive tasks in Cairo 0.x.
To demonstrate how they work, we'll create a function that sums up the first ten natural numbers using recursion:
use array::ArrayTrait;
use option::OptionTrait;
// `start` should be 1_u32 and `sum` be 0_32
fn sum(start: u32, sum: u32) -> Option<u32> {
match gas::withdraw_gas() {
Option::Some(_) => {},
Option::None(_) => {
let mut data = ArrayTrait::new();
data.append('Out of gas');
panic(data);
},
}
// Terminator
if(start == 11_u32){
return Option::Some(sum);
}
// Sum
let currentSum = sum + start;
return sum(start + 1_u32, currentSum);
}
Loops are useful for creating logic that executes repetitively while a specific condition holds. The loop keyword in Cairo will repeatedly execute a block of code until stopped by the break keyword.
use debug::PrintTrait;
fn main() {
let mut i: usize = 0;
loop {
if i > 10 {
break;
}
'again'.print();
i += 1;
}
}
use array::ArrayTrait;
allows us use arraysuse option::OptionTrait;
gives us theOption
enum which we will talk about in chapter 12.- From
line 32
toline 39
is just a boilerplate code we should always add when writing recursive functions in Cairo 1.0 for gas management. - From
line 42
toline 44
, we have the terminator that makes sure the function stops at some point. let currentSum = sum + start;
does the increamenting- And,
return sum(start + 1_u32, currentSum)
calls the function again with the start value plus 1 and the current summation of the values.