logo
Creating an array

Overview (Arrays):

Arrays or lists are critical to any programming language. In Cairo you can think of arrays as a pointer to the first memory address in a list of contiguous memory addresses, all of which make up the array. We can create an array of felts (felt*) in one of several ways:

from starkware.cairo.common.alloc import alloc

...

let felt_array : felt* = alloc();

assert [felt_array] = 1;

assert [felt_array+1] = 2;

assert [felt_array+2] = 3;

or

tempvar felt_array : felt* = new (1, 2, 3);



Both of these will work! The first one is more dynamic as you can continue to add to the array, while the second one is made for a fixed size array but is also much easier to write. In order to use the first example above, be sure the import statement is included at the top of your script.



Overview (tempvar):

Now you might be curious about what a tempvar is and how it differs from the keyword let. This is something to refer to in the docs for more detailed information, but effectively let stores the expression itself from the right side of the equal sign to the variable instead of the expression's value. On the other hand, tempvar actually evaluates the expression and stores the value in the variable.

So if you have:

let x = 3;

let y = x * x * x;

let z = y * y * y;

z is actually storing the expression y was storing three times which is storing x three times. So z is actually computing (x^9).

x * x * x * x * x * x * x * x * x

Meanwhile if you have:

tempvar x = 3;

tempvar y = x * x * x;

tempvar z = y * y * y;

then x = 3, y = 27 and then z = 19683 (27^3).

Enough variable talk, the Mummies want to make sure you can analyze the slopes of their pyramid walls, so that is where we will start.



Your turn:

Create arrays called quad_pyramid_slope_angles and tri_pyramid_slope_angles that are of type felt* that allow the assertions to pass. For this lesson use the tempvar notation.



References:

For official docs on arrays: $ https://www.cairo-lang.org/docs/reference/syntax.html$ 

For official docs on tempvar vs let: $ https://www.cairo-lang.org/docs/how_cairo_works/consts.html$ 


Back

1 / 6


Twitter