previous chapterthe pico pagenext chapter


Loop functions

Pico provides three native loop functions: while, until and for. These are used to evaluate some expression iteratively; the only difference between these three loop functions lies with start and stop criteria for the iterative process. while, until and for closely reflect how loops are performed in the majority of programming languages; we will make relatively little use of them at this stage, which is why their behaviour is only superficially sketched here. In the next chapter all three will be formally defined.

The preceding transcript illustrates how the native while function is used to compute the truncated logarithm with base 2 of the number 1000. The function while takes two arguments; the first one should have a logical value. For as long as this value remains true, the second argument keeps on being evaluated. In this example, the expression log2:=log2+1 is evaluated 9 times, because that is the number of steps it takes for k:=k//2 to become zero.

The preceding transcript illustrates how the native function until is used to compute the first Fibonacci number exceeding 100000000.

The function until takes two arguments; the first one should have a logical value. The second argument keeps on being evaluated until this value becomes false. In this example, the expression {r:=p+q;q:=p;p:=r} is actually evaluated 38 times for p to reach the value 102334155. This transcript concludes by computing p/q which is an approximation for the golden ratio.

The following transcript illustrates how the native function for is used to compute the tenth power of the number 3:

The function for takes four arguments; the third one should have a logical value. For as long as this value remains true, the fourth argument keeps on being evaluated. This is similar to the while function; however, the other two arguments provide additional features. The first argument is evaluated once before the loop is started, while the second argument is evaluated at the conclusion of each iteration step. In this example, this mechanism is used to define a counter, that is a variable n counting the number of iterations and used to decide that the loop should stop after exactly 10 iterations. Note that the transcript checks the correctness of this loop against the standard computation 3^10.


previous chapterthe pico pagenext chapter