Cairo’s Temporary Variables Exercise

Rewrite the solution to Exercise – A simple Cairo program using temporary variables.

func main():
    [ap] = 100; ap++
    [ap] = [ap - 1] * [ap - 1]; ap++ # x * x (x^2)
    [ap] = [ap - 1] * [ap - 2]; ap++ # x^2 * x (x^3)
    [ap] = [ap - 2] * 23; ap++       # x^2 * 23
    [ap] = [ap - 4] * 45; ap++       # x * 45
    [ap] = [ap - 3] + [ap - 2]; ap++ # x^3 + x^2 * 23
    [ap] = [ap - 1] + [ap - 2]; ap++ # x^3 + x^2 * 23 + x * 45
    [ap] = [ap - 1] + 67; ap++       # x^3 + x^2 * 23 + x * 45 + 67
    ret
end

Solution

The original exercise asked us to create a program that calculates the equation x^3 + 23 * x^2 + 45 * x + 67 for x = 100. To test the validity of our program we are given the result of the calculation, 1234567. The code shown above is the solution for that exercise explained in a previous article that uses only the ap pointer.

The reason our program looks so verbose for such a simple calculation is because, when using the ap pointer directly, we are limited to simple expressions that have only one operator at most.

Using the tempvar keyword we can now create complex expressions that would allow us to simplify our code but would force us to delegate the management of the ap pointer to the compiler, which is a good thing anyway.

The revised code using the tempvar keyword is shown below.

func main():
    tempvar x = 100
    tempvar x2 = x * x
    tempvar x3 = x * x * x
    tempvar s = x3 + 23 * x2 + 45 * x + 67
    ret
end

We can see now how Cairo starts to resemble a “high” level language instead of an assembly language and we are able to write the same logic in a more succinct way.

To test that we get the same result as before, we can execute the program and inspect its memory trace.

$ cairo-compile exercise.cairo --output exercise.json                   
$ cairo-run --program=exercise.json --print_memory --relocate_prints
>>>
Addr  Value
-----------
⋮
1     5189976364521848832
2     100
3     5210805504208502784
4     5210805499913469952
5     5210805495618568192
6     5189976364521848832
7     23
8     5210805491323600896
9     5201798304953630720
10    5189976364521848832
11    45
12    5210805474143731712
13    5198420613823168512
14    67
15    5201798304953565184
16    2345108766317314046
17    30
18    30
19    100
20    10000
21    10000
22    1000000
23    23
24    230000
25    1230000
26    45
27    4500
28    4567
29    1234567

Not only can we see that we get the same result as before but it’s obvious that the ap pointer has moved multiple places and intermediate values were stored in memory without our direct intervention.

Reference

The exercise in this article can be found in this section of the Cairo docs.

So, what do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.