Kontrol Akışı

Bir koşul doğru olduğunda bazı kodların çalıştırılması ve bir koşul doğru olduğu sürece bazı kodların tekrar tekrar çalıştırılması, çoğu programlama dilinde temel yapı taşlarıdır. Cairo kodunun yürütme akışını kontrol etmenize izin veren en yaygın yapılar if ifadeleri ve döngülerdir.

if İfadesi

Bir if ifadesi, koşullara bağlı olarak kodunuzu dallandırmanıza olanak tanır. Bir koşul sağlarsınız ve ardından, “Bu koşul karşılanırsa, bu kod bloğunu çalıştır. Koşul karşılanmazsa, bu kod bloğunu çalıştırma.” dersiniz.

cairo_projects dizininizde branches adında yeni bir proje oluşturun ve if ifadesini keşfedin. src/lib.cairo dosyasına aşağıdakileri girin:

fn main() {
    let number = 3;

    if number == 5 {
        println!("condition was true and number = {}", number);
    } else {
        println!("condition was false and number = {}", number);
    }
}

Tüm if ifadeleri if anahtar kelimesiyle başlar, ardından bir koşul gelir. Bu durumda, koşul number değişkeninin değerinin 5'e eşit olup olmadığını kontrol eder. Koşul true ise yürütülecek kod bloğunu koşulun hemen ardından süslü parantezler içine yerleştiririz.

İsteğe bağlı olarak, koşul false olarak değerlendirilirse programın yürüteceği alternatif bir kod bloğu vermek için burada yaptığımız gibi bir else ifadesi de ekleyebiliriz. Bir else ifadesi sağlamazsanız ve koşul false ise, program if bloğunu atlayıp kodun bir sonraki kısmına geçer.

Bu kodu çalıştırmayı deneyin; aşağıdaki çıktıyı görmelisiniz:

$ 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 []

Koşulun true olmasını sağlayacak bir değere number değerini değiştirip ne olacağını görelim:

    let number = 5;
$ scarb cairo-run
condition was true and number = 5
Run completed successfully, returning []

Bu kodda koşulun bir bool olması gerektiğini belirtmek de önemlidir. Koşul bir bool değilse, bir hata alırız. Örneğin, aşağıdaki kodu çalıştırmayı deneyin:

fn main() {
    let number = 3;

    if number {
        println!("number was three");
    }
}

if koşulu bu kez 3 değerini değerlendirir ve Cairo bir hata atar:

$ 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

Hata, number'ın daha sonra if ifadesinin koşulu olarak kullanılmasına dayanarak Cairo'nun number için bool türünü çıkardığını gösterir. Değer 3'ten bir bool oluşturmaya çalışır, ancak Cairo zaten bir sayısal literalden bool oluşturmayı desteklemez - bir bool oluşturmak için sadece true veya false kullanabilirsiniz. Ruby ve JavaScript gibi dillerin aksine, Cairo otomatik olarak Boolean olmayan türleri Boolean'a dönüştürmeye çalışmaz. Örneğin, bir sayı 0'a eşit olmadığında if kod bloğunun yalnızca çalışmasını istiyorsak, if ifadesini şu şekilde değiştirebiliriz:

fn main() {
    let number = 3;

    if number != 0 {
        println!("number was something other than zero");
    }
}

Bu kodu çalıştırmak, number was something other than zero yazdıracaktır.

Birden Fazla Koşulu else if ile İşleme

if ve else'i bir else if ifadesinde birleştirerek birden fazla koşulu kullanabilirsiniz. Örneğin:

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");
    }
}

Bu programın alabileceği dört olası yolu vardır. Çalıştırdıktan sonra, şu çıktıyı görmelisiniz:

$ 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 []

Bu program çalıştırıldığında, sırayla her if ifadesini kontrol eder ve koşul true olarak değerlendirilen ilk gövdeyi yürütür. number - 2 == 1 true olsa da, çıktı olarak number minus 2 is 1 ya da else bloğundan number not found metnini görmeyiz. Çünkü Cairo, ilk true koşulunun bloğunu yürütür ve bir tane bulduğunda, geri kalanını bile kontrol etmez. Çok fazla else if ifadesi kullanmak kodunuzu karışık hale getirebilir, bu yüzden birden fazla varsa kodunuzu yeniden düzenlemek isteyebilirsiniz. 6. Bölüm bu durumlar için match adında güçlü bir Cairo dallanma yapısını tanımlar.

Using if in a let Statement

if bir ifade olduğu için, sonucu bir değişkene atamak için bir let ifadesinin sağ tarafında kullanabiliriz.

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 []

number değişkeni, if ifadesinin sonucuna bağlı olarak bir değere bağlanır, burada bu değer 5 olacaktır.

Döngülerle Tekrarlama

Bir kod bloğunu birden fazla kez çalıştırmak sıklıkla faydalıdır. Bu görev için, Cairo, döngü gövdesi içindeki kodun sonuna kadar çalıştırıp ardından hemen başa dönecek basit bir döngü sözdizimi sağlar. Döngülerle deney yapmak için loops adında yeni bir proje oluşturalım.

Cairo has three kinds of loops: loop, while, and for. Let’s try each one.

Döngü ile Kod Tekrarı

loop anahtar kelimesi, Cairo'ya bir kod bloğunu sürekli olarak ya da siz açıkça durmasını söyleyene kadar tekrar tekrar çalıştırmasını söyler.

Örnek olarak, loops dizininizdeki src/lib.cairo dosyasını şu şekilde değiştirin:

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!

^C sembolü, ctrl-c'ye bastığınız yeri temsil eder. Kod döngüde kesme sinyalini aldığında neredeyse bağlı olarak, ^C'den sonra again! yazılıp yazılmadığını görebilir veya göremeyebilirsiniz.

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.

Akıllı kontratların Starknet üzerinde dağıtılması bağlamında, ağda sonsuz döngülerin çalışmasını önlemek özellikle önemlidir. Eğer bir döngü çalıştırması gereken bir program yazıyorsanız, programı çalıştırmak için yeterince büyük bir değere sahip --available-gas bayrağı ile çalıştırmanız gerekecek.

Şimdi, aynı programı tekrar çalıştırın, ancak bu sefer --available-gas bayrağını 2000000000000 yerine 200000 olarak ayarlayın. Programın yalnızca 3 kez tekrar! yazdırdığını ve döngüyü sürdürmek için gazı tükendiği için durduğunu göreceksiniz.

Şans eseri, Cairo ayrıca kod kullanarak bir döngüden çıkmanın bir yolunu da sağlar. Programa döngüyü ne zaman durdurması gerektiğini söylemek için döngü içine break anahtar kelimesini yerleştirebilirsiniz.

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;
    }
}

Bu program çalıştırıldığında, i değeri 5'e eşit olduğunda yazdırılmayacaktır.

Döngülerden Değer Döndürme

loop kullanımının yollarından biri, başarılı olup olmadığını kontrol etmek gibi, başarısız olabileceğini bildiğiniz bir işlemi tekrar denemektir. Ayrıca, bu işlemin sonucunu döngüden kodunuzun geri kalanına aktarmanız gerekebilir. Bunu yapmak için, döngüyü durdurmak için kullandığınız break ifadesinin ardından döndürmek istediğiniz değeri ekleyebilirsiniz; bu değer döngüden döndürülecek ve aşağıda gösterildiği gibi kullanabilirsiniz:

fn main() {
    let mut counter = 0;

    let result = loop {
        if counter == 10 {
            break counter * 2;
        }
        counter += 1;
    };

    println!("The result is {}", result);
}

Döngüden önce, counter adında bir değişken tanımlarız ve onu 0 olarak başlatırız. Sonra döngüden dönen değeri tutacak result adında bir değişken tanımlarız. Döngünün her yinelemesinde, counter'ın 10'a eşit olup olmadığını kontrol eder ve sonra counter değişkenine 1 ekleriz. Koşul karşılandığında, counter * 2 değeri ile break anahtar kelimesini kullanırız. Döngüden sonra, result'a değeri atayan ifadeyi sonlandırmak için bir noktalı virgül kullanırız. Sonunda, bu durumda 20 olan result değerini yazdırırız.

while ile Koşullu Döngüler

Bir program sıklıkla döngü içinde bir koşulu değerlendirmeye ihtiyaç duyar. Koşul true olduğu sürece döngü çalışır. Koşul artık true olmadığında, program break'i çağırır, döngüyü durdurur. Bu tür bir davranışı loop, if, else ve break kombinasyonunu kullanarak uygulamak mümkündür; isterseniz şimdi bir programda bunu deneyebilirsiniz. Ancak, bu desen o kadar yaygındır ki, Cairo bunun için yerleşik bir dil yapısı sunar, buna while döngüsü denir.

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.

Bu yapı, loop, if, else ve break kullanıldığında gerekli olacak çok fazla iç içe geçmeyi ortadan kaldırır ve daha açıktır. Bir koşul true olarak değerlendirildiğinde, kod çalışır; aksi takdirde, döngüden çıkar.

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.

Özet

Başardınız! Oldukça büyük bir bölümdü: değişkenler, veri tipleri, fonksiyonlar, yorumlar, if ifadeleri ve döngüler hakkında öğrendiniz! Bu bölümde tartışılan kavramlarla pratik yapmak için, aşağıdaki programları oluşturmayı deneyin

  • n'inci Fibonacci sayısını oluşturun.
  • Bir n sayısının faktöriyelini hesaplayın.

Şimdi, bir sonraki bölümde Cairo'daki yaygın koleksiyon türlerini inceleyeceğiz.