Alur Kontrol
Kemampuan untuk menjalankan beberapa kode tergantung pada apakah suatu kondisi benar, dan untuk menjalankan beberapa kode secara berulang selama suatu kondisi benar adalah blok dasar dalam sebagian besar bahasa pemrograman. Konstruksi yang paling umum yang memungkinkan Anda mengendalikan alur eksekusi kode Cairo adalah ekspresi if dan loop.
if
Expressions
Ekspresi if memungkinkan Anda bercabang dalam kode Anda tergantung pada kondisi. Anda memberikan suatu kondisi dan kemudian menyatakan, "Jika kondisi ini terpenuhi, jalankan blok kode ini. Jika kondisinya tidak terpenuhi, jangan jalankan blok kode ini."
Create a new project called branches in your cairo_projects directory to explore the if
expression. In the src/lib.cairo file, input the following:
fn main() {
let number = 3;
if number == 5 {
println!("condition was true and number = {}", number);
} else {
println!("condition was false and number = {}", number);
}
}
Semua ekspresi if
dimulai dengan kata kunci if
, diikuti oleh suatu kondisi. Dalam kasus ini, kondisinya memeriksa apakah variabel number
memiliki nilai yang sama dengan 5. Kami menempatkan blok kode untuk dijalankan jika kondisinya true
langsung setelah kondisi di dalam kurung kurawal.
Opsionalnya, kita juga dapat menyertakan ekspresi else
, seperti yang kita pilih di sini, untuk memberikan program blok kode alternatif yang akan dijalankan jika kondisi dinilai false
. Jika Anda tidak menyediakan ekspresi else
dan kondisinya false
, program akan melewati blok if
dan melanjutkan ke bagian kode berikutnya.
Coba jalankan kode ini; Anda seharusnya melihat keluaran berikut:
$ scarb cairo-run
Compiling no_listing_24_if v0.1.0 (listings/ch02-common-programming-concepts/no_listing_27_if/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Running no_listing_24_if
condition was false and number = 3
Run completed successfully, returning []
Mari mencoba mengubah nilai number
menjadi suatu nilai yang membuat kondisinya menjadi true
untuk melihat apa yang terjadi:
let number = 5;
$ scarb cairo-run
condition was true and number = 5
Run completed successfully, returning []
It’s also worth noting that the condition in this code must be a bool
. If the condition isn’t a bool
, we’ll get an error. For example, try running the following code:
fn main() {
let number = 3;
if number {
println!("number was three");
}
}
The if
condition evaluates to a value of 3 this time, and Cairo throws an error:
$ scarb build
Compiling no_listing_28_bis_if_not_bool v0.1.0 (listings/ch02-common-programming-concepts/no_listing_28_bis_if_not_bool/Scarb.toml)
error: Mismatched types. The type `core::bool` cannot be created from a numeric literal.
--> listings/ch02-common-programming-concepts/no_listing_28_bis_if_not_bool/src/lib.cairo:4:18
let number = 3;
^
error: could not compile `no_listing_28_bis_if_not_bool` due to previous error
The error indicates that Cairo inferred the type of number
to be a bool
based on its later use as a condition of the if
statement. It tries to create a bool
from the value 3
, but Cairo doesn't support instantiating a bool
from a numeric literal anyway - you can only use true
or false
to create a bool
. Unlike languages such as Ruby and JavaScript, Cairo will not automatically try to convert non-Boolean types to a Boolean. If we want the if
code block to run only when a number is not equal to 0, for example, we can change the if expression to the following:
fn main() {
let number = 3;
if number != 0 {
println!("number was something other than zero");
}
}
Running this code will print number was something other than zero
.
Menangani Beberapa Kondisi dengan else if
You can use multiple conditions by combining if
and else
in an else if
expression. For example:
fn main() {
let number = 3;
if number == 12 {
println!("number is 12");
} else if number == 3 {
println!("number is 3");
} else if number - 2 == 1 {
println!("number minus 2 is 1");
} else {
println!("number not found");
}
}
Program ini memiliki empat jalur yang mungkin diambil. Setelah dijalankan, Anda seharusnya melihat keluaran berikut:
$ scarb cairo-run
Compiling no_listing_25_else_if v0.1.0 (listings/ch02-common-programming-concepts/no_listing_30_else_if/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Running no_listing_25_else_if
number is 3
Run completed successfully, returning []
When this program executes, it checks each if
expression in turn and executes the first body for which the condition evaluates to true
. Note that even though number - 2 == 1
is true
, we don’t see the output number minus 2 is 1
nor do we see the number not found
text from the else
block. That’s because Cairo only executes the block for the first true condition, and once it finds one, it doesn’t even check the rest. Using too many else if
expressions can clutter your code, so if you have more than one, you might want to refactor your code. Chapter 6 describes a powerful Cairo branching construct called match
for these cases.
Using if
in a let
Statement
Because if
is an expression, we can use it on the right side of a let
statement to assign the outcome to a variable.
fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
if number == 5 {
println!("condition was true and number is {}", number);
}
}
$ scarb cairo-run
Compiling no_listing_26_if_let v0.1.0 (listings/ch02-common-programming-concepts/no_listing_31_if_let/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Running no_listing_26_if_let
condition was true and number is 5
Run completed successfully, returning []
The number
variable will be bound to a value based on the outcome of the if
expression, which will be 5 here.
Pengulangan dengan Loop
It’s often useful to execute a block of code more than once. For this task, Cairo provides a simple loop syntax, which will run through the code inside the loop body to the end and then start immediately back at the beginning. To experiment with loops, let’s create a new project called loops.
Cairo has three kinds of loops: loop
, while
, and for
. Let’s try each one.
Mengulang Kode dengan loop
Kata kunci loop
memberitahu Cairo untuk menjalankan suatu blok kode berulang kali selamanya atau sampai Anda secara eksplisit memberi tahu untuk berhenti.
Sebagai contoh, ubah file src/lib.cairo di direktori loops Anda sehingga terlihat seperti ini:
fn main() {
loop {
println!("again!");
}
}
When we run this program, we’ll see again!
printed over and over continuously until either the program runs out of gas or we stop the program manually. Most terminals support the keyboard shortcut ctrl-c to interrupt a program that is stuck in a continual loop. Give it a try:
$ scarb cairo-run --available-gas=20000000
Compiling loops v0.1.0 (file:///projects/loops)
Finished release target(s) in 0 seconds
Running loops
again!
again!
again!
^Cagain!
The symbol ^C
represents where you pressed ctrl-c. You may or may not see the word again!
printed after the ^C, depending on where the code was in the loop when it received the interrupt signal.
Note: Cairo prevents us from running program with infinite loops by including a gas meter. The gas meter is a mechanism that limits the amount of computation that can be done in a program. By setting a value to the
--available-gas
flag, we can set the maximum amount of gas available to the program. Gas is a unit of measurement that expresses the computation cost of an instruction. When the gas meter runs out, the program will stop. In the previous case, we set the gas limit high enough for the program to run for quite some time.
It is particularly important in the context of smart contracts deployed on Starknet, as it prevents from running infinite loops on the network. If you're writing a program that needs to run a loop, you will need to execute it with the
--available-gas
flag set to a value that is large enough to run the program.
Now, try running the same program again, but this time with the --available-gas
flag set to 200000
instead of 2000000000000
. You will see the program only prints again!
3 times before it stops, as it ran out of gas to keep executing the loop.
Fortunately, Cairo also provides a way to break out of a loop using code. You can place the break
keyword within the loop to tell the program when to stop executing the loop.
fn main() {
let mut i: usize = 0;
loop {
if i > 10 {
break;
}
println!("i = {}", i);
i += 1;
}
}
The continue
keyword tells the program to go to the next iteration of the loop and to skip the rest of the code in this iteration. Let's add a continue
statement to our loop to skip the println!
statement when i
is equal to 5
.
fn main() {
let mut i: usize = 0;
loop {
if i > 10 {
break;
}
if i == 5 {
i += 1;
continue;
}
println!("i = {}", i);
i += 1;
}
}
Menjalankan program ini tidak akan mencetak nilai dari i
ketika nilainya sama dengan 5
.
Mengembalikan Nilai dari Loop
Salah satu penggunaan dari loop
adalah untuk mencoba operasi yang mungkin gagal, seperti memeriksa apakah suatu operasi berhasil. Anda mungkin juga perlu meneruskan hasil dari operasi tersebut keluar dari perulangan ke sisa kode Anda. Untuk melakukannya, Anda dapat menambahkan nilai yang ingin Anda kembalikan setelah ekspresi break
yang Anda gunakan untuk menghentikan perulangan; nilai tersebut akan dikembalikan keluar dari perulangan sehingga Anda dapat menggunakannya, seperti yang ditunjukkan di sini:
fn main() {
let mut counter = 0;
let result = loop {
if counter == 10 {
break counter * 2;
}
counter += 1;
};
println!("The result is {}", result);
}
Sebelum perulangan, kita mendeklarasikan variabel bernama counter
dan menginisialisasinya dengan 0
. Kemudian kita mendeklarasikan variabel bernama result
untuk menyimpan nilai yang dikembalikan dari perulangan. Pada setiap iterasi perulangan, kita memeriksa apakah counter
sama dengan 10
, dan kemudian menambahkan 1
ke variabel counter
. Ketika kondisi terpenuhi, kita menggunakan kata kunci break
dengan nilai counter * 2
. Setelah perulangan, kita menggunakan titik koma untuk mengakhiri pernyataan yang memberikan nilai ke result
. Akhirnya, kita mencetak nilai dalam result
, yang dalam hal ini adalah 20
.
Conditional Loops with while
A program will often need to evaluate a condition within a loop. While the condition is true
, the loop runs. When the condition ceases to be true
, the program calls break
, stopping the loop. It’s possible to implement behavior like this using a combination of loop
, if
, else
, and break
; you could try that now in a program, if you’d like. However, this pattern is so common that Cairo has a built-in language construct for it, called a while
loop.
In Listing 2-2, we use while
to loop the program three times, counting down each time after printing the value of number
, and then, after the loop, print a message and exit.
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
};
println!("LIFTOFF!!!");
}
Listing 2-2: Using a while
loop to run code while a condition holds true
.
This construct eliminates a lot of nesting that would be necessary if you used loop
, if
, else
, and break
, and it’s clearer. While a condition evaluates to true
, the code runs; otherwise, it exits the loop.
Looping Through a Collection with for
You can also use the while construct to loop over the elements of a collection, such as an array. For example, the loop in Listing 2-3 prints each element in the array a
.
fn main() {
let a = [10, 20, 30, 40, 50].span();
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
Listing 2-3: Looping through each element of a collection using a while
loop
Here, the code counts up through the elements in the array. It starts at index 0
, and then loops until it reaches the final index in the array (that is, when index < 5
is no longer true
). Running this code will print every element in the array:
$ scarb cairo-run
Compiling no_listing_45_iter_loop_while v0.1.0 (listings/ch02-common-programming-concepts/no_listing_45_iter_loop_while/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Running no_listing_45_iter_loop_while
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
Run completed successfully, returning []
All five array values appear in the terminal, as expected. Even though index
will reach a value of 5
at some point, the loop stops executing before trying to fetch a sixth value from the array.
However, this approach is error prone; we could cause the program to panic if the index value or test condition is incorrect. For example, if you changed the definition of the a
array to have four elements but forgot to update the condition to while index < 4
, the code would panic. It’s also slow, because the compiler adds runtime code to perform the conditional check of whether the index is within the bounds of the array on every iteration through the loop.
As a more concise alternative, you can use a for
loop and execute some code for each item in a collection. A for
loop looks like the code in Listing 2-4.
fn main() {
let a = [10, 20, 30, 40, 50].span();
for element in a {
println!("the value is: {element}");
}
}
Listing 2-4: Looping through each element of a collection using a for
loop
When we run this code, we’ll see the same output as in Listing 2-3. More importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items.
Using the for
loop, you wouldn’t need to remember to change any other code if you changed the number of values in the array, as you would with the method used in Listing 2-3.
The safety and conciseness of for
loops make them the most commonly used loop construct in Cairo. Even in situations in which you want to run some code a certain number of times, as in the countdown example that used a while loop in Listing 2-2. Another way to run code a certain number of times would be to use a Range
, provided by the core library, which generates all numbers in sequence starting from one number and ending before another number.
Here’s how you can use a Range
to count from 1 to 3:
fn main() {
for number in 1..4_u8 {
println!("{number}!");
};
println!("Go!!!");
}
This code is a bit nicer, isn’t it?
Equivalence Between Loops and Recursive Functions
Loops and recursive functions are two common ways to repeat a block of code multiple times. The loop
keyword is used to create an infinite loop that can be broken by using the break
keyword.
fn main() -> felt252 {
let mut x: felt252 = 0;
loop {
if x == 2 {
break;
} else {
x += 1;
}
};
x
}
Loops can be transformed into recursive functions by calling the function within itself. Here is an example of a recursive function that mimics the behavior of the loop
example above.
fn main() -> felt252 {
recursive_function(0)
}
fn recursive_function(mut x: felt252) -> felt252 {
if x == 2 {
x
} else {
recursive_function(x + 1)
}
}
In both cases, the code block will run indefinitely until the condition x == 2
is met, at which point the value of x will be displayed.
In Cairo, loops and recursions are not only conceptually equivalent: they are also compiled down to similar low-level representations. To understand this, we can compile both examples to Sierra, and analyze the Sierra Code generated by the Cairo compiler for both examples. Add the following in your Scarb.toml
file:
[lib]
sierra-text = true
Then, run scarb build
to compile both examples. You will find the Sierra code generated by for both examples is extremely similar, as the loop is compiled to a recursive function in the Sierra statements.
Note: For our example, our findings came from understanding the statements section in Sierra that shows the execution traces of the two programs. If you are curious to learn more about Sierra, check out Exploring Sierra.
Ringkasan
Anda berhasil! Ini adalah bab yang cukup besar: Anda telah mempelajari tentang variabel, tipe data, fungsi, komentar, ekspresi if
, dan perulangan! Untuk berlatih dengan konsep-konsep yang dibahas dalam bab ini, cobalah membuat program untuk melakukan hal-hal berikut:
- Menghasilkan bilangan Fibonacci ke-n.
- Menghitung faktorial dari suatu bilangan n.
Selanjutnya, kita akan meninjau jenis-jenis koleksi umum dalam Cairo pada bab berikutnya.