Chapter 5

Assignments and Loops

On this page

This chapter discusses variable assignments, loop constructs, and list and array comprehensions in Picat. It describes the scope of an assigned variable, indicating where the variable is defined, and where it is not defined. Finally, it shows how assignments, loops, and list comprehensions are related, and how they are compiled.

5.1 Assignments

Picat variables are single-assignment, meaning that once a variable is bound to a value, the variable cannot be bound again. In order to simulate imperative language variables, Picat provides the assignment operator :=. An assignment takes the form LHS : =RHS, where LHS is either a variable or an access of a compound value in the form X[…]. When LHS is an access in the form X[I], the component of X indexed I is updated. This update is undone if execution backtracks over this assignment.

Example

test => X = 0, X := X + 1,  X := X + 2, write(X).

The compiler needs to give special consideration to the scope of a variable. The scope of a variable is the region of the program in which its name refers to that variable.

Consider the test example. This example binds X to 0. Then, the example tries to bind X to X + 1. However, X is still visible at the assignment, and the preceding X = 0 has bound it. Since X cannot be bound again, the compiler must perform extra operations in order to manage assignments that use the := operator.

In order to handle assignments, Picat creates new variables at compile time. In the test example, at compile time, Picat creates a new variable, say X1, to hold the value of X after the assignment X := X + 1. Picat replaces X by X1 on the LHS of the assignment. All occurrences of X after the assignment are replaced by X1. When encountering X1 := X1 + 2, Picat creates another new variable, say X2, to hold the value of X1 after the assignment, and replaces the remaining occurrences of X1 by X2. When write(X2) is executed, the value held in X2, which is 3, is printed. This means that the compiler rewrites the above example as follows:

test => X = 0, X1 = X + 1, X2 = X1 + 2, write(X2).

5.1.1 If-Else

This leads to the question: what does the compiler do if the code branches? Consider the following code skeleton.

Example

if_ex(Z) =>
    X = 1, Y = 2,
    if (Z > 0)
       X := X * Z    
    else
       Y := Y + Z
    end,
    println([X,Y]).

The if_ex example performs exactly one assignment. At compilation time, the compiler does not know whether or not Z >0 evaluates to true. Therefore, the compiler does not know whether to introduce a new variable for X or for Y.

Therefore, when an if-else statement contains an assignment, the compiler rewrites the if-else statement as a predicate. For example, the compiler rewrites the above example as follows:

if_ex(Z) => 
   X = 1, Y = 2, 
   p(X, Xout, Y, Yout, Z),
   println([Xout,Yout]).

p(Xin, Xout, Yin, Yout, Z), Z > 0 =>
   Xout = Xin * Z,
   Yout = Yin.
p(Xin, Xout, Yin, Yout, Z) =>
   Xout = Xin,
   Yout = Yin + Z.

One rule is generated for each branch of the if-else statement. For each variable V that occurs on the LHS of an assignment statement that is inside of the if-else statement, predicate p is passed two arguments, Vin and Vout. In the above example, X and Y each occur on the LHS of an assignment statement. Therefore, predicate p is passed the parameters Xin, Xout, Yin, and Yout.

5.2 Types of Loops

Picat has three types of loop statements for programming repetitions: foreach, while, and do-while.

5.2.1 Foreach Loops

A foreach loop has the form:

  foreach (E1 in D1 , Cond1 , …, En in Dn , Condn )
   Goal
  end

Each Ei is an iterating pattern. Each Di is an expression that gives a compound value. Each Condi is an optional condition on iterators E1 through Ei .

Foreach loops can be used to iterate through compound values, as in the following examples.

Example

loop_ex1 =>
    L = [17, 3, 41, 25, 8, 1, 6, 40],
    foreach (E in L)
        println(E)
    end.

loop_ex2(Map) =>
    foreach ((Key = Value) in Map)
        writef("%w = %w\n", Key, Value)
    end.

The loop_ex1 example iterates through a list. The loop_ex2 example iterates through a map, where Key = Value is the iterating pattern.

The loop_ex1 example can also be written, using a failure-driven loop, as follows.

Example

loop_ex1 =>
    L = [17, 3, 41, 25, 8, 1, 6, 40],
    (    member(E, L),
         println(E),
         fail
    ;
         true
    ).

Recall that the range Start..Step..End stands for a list of numbers. Ranges can be used as compound values in iterators.

Example

loop_ex3 =>
    foreach (E in 1 .. 2 .. 9)
        println(E)
    end.

Also recall that the function zip(List1, List2 , …, Listn ) returns a list of tuples. This function can be used to simultaneously iterate over multiple lists.

Example:

loop_ex_parallel =>
    foreach (Pair in zip(1..2, [a,b]))
        println(Pair)
    end.

5.2.2 Foreach Loops with Multiple Iterators

Each of the previous examples uses a single iterator. Foreach loops can also contain multiple iterators.

Example:

loop_ex4 =>
    L = [2, 3, 5, 10],
    foreach (I in L, J in 1 .. 10, J mod I != 0)
        printf("%d is not a multiple of %d%n", J, I)
    end.

If a foreach loop has multiple iterators, then it is compiled into a series of nested foreach loops in which each nested loop has a single iterator. In other words, a foreach loop with multiple iterators executes its goal once for every possible combination of values in the iterators.

The foreach loop in loop_ex4 is the same as the nested loop:

loop_ex5 =>
    L = [2, 3, 5, 10],
    foreach (I in L)
        foreach (J in 1..10)
            if (J mod I != 0)
               printf("%d is not a multiple of %d%n", J, I)
            end
        end
    end.

5.2.3 Foreach Loops with the break Condition

When the condition break(Cond) occurs to the right of an iterator in a foreach loop, it terminates the loop if Cond is true. Note that the loop body is not executed when Cond is true.

The foreach loop in loop_ex6 prints out the elements of the array A, stopping when it encounters a 0.

loop_ex6 =>
    A = {2, 3, 5, 0, 10, 4},
    foreach (I in 1..len(A),  break(A[I] == 0))
        println(A[I])
    end.

5.2.4 While Loops

A while loop has the form:

  while (Cond)
   Goal
  end

As long as Cond succeeds, the loop will repeatedly execute Goal.

Example:

loop_ex7 =>
    I = 1, 
    while (I <= 9)
        println(I),
        I := I + 2
    end.

loop_ex8 =>
    J = 6,
    while (J <= 5)
        println(J),
        J := J + 1
    end.

loop_ex9 =>
    E = read_int(),
    while (E mod 2 == 0; E mod 5 == 0)
        println(E),
        E := read_int()
    end.

loop_ex10 =>
    E = read_int(),
    while (E mod 2 == 0, E mod 5 == 0)
        println(E),
        E := read_int()
    end.

The while loop in loop_ex7 prints all of the odd numbers between 1 and 9. It is similar to the foreach loop

foreach (I in 1 .. 2 .. 9)
    println(I)
end.

The while loop in loop_ex8 never executes its goal. J begins at 6, so the condition J <= 5 is never true, meaning that the body of the loop does not execute.

The while loop in loop_ex9 demonstrates a compound condition. The loop executes as long as the value that is read into E is either a multiple of 2 or a multiple of 5.

The while loop in loop_ex10 also demonstrates a compound condition. Unlike in
loop_ex9, in which either condition must be true, in loop_ex10, both conditions must be true. The loop executes as long as the value that is read into E is both a multiple of 2 and a multiple of 5.

5.2.5 Do-while Loops

A do-while loop has the form:

  do
   Goal
  while (Cond)

A do-while loop is similar to a while loop, except that a do-while loop executes Goal one time before testing Cond. The following example demonstrates the similarities and differences between do-while loops and while loops.

Example

loop_ex11 =>
    J = 6,
    do
        println(J),
        J := J + 1
    while (J <= 5).

Unlike loop_ex8, loop_ex11 executes its body once. Although J begins at 6, the do-while loop prints J, and increments J before evaluating the condition J <= 5.

5.3 List and Array Comprehensions

A list comprehension is a special functional notation for creating lists. List comprehensions have a similar format to foreach loops.

   [T : E1 in D1 , Cond1 , …, En in Dn , Condn ]

T is an expression. Each Ei is an iterating pattern. Each Di is an expression that gives a compound value. Each Condi is an optional condition on iterators E1 through Ei .

An array comprehension takes the following form:

   {T : E1 in D1 , Cond1 , …, En in Dn , Condn }

It is the same as:

   to_array([T : E1 in D1 , Cond1 , …, En in Dn , Condn ])

Example

Picat> L = [(A, I) : A in [a, b], I in 1 .. 2].
L = [(a , 1),(a , 2),(b , 1),(b , 2)]

Picat> L = {(A, I) : A in [a, b], I in 1 .. 2}.
L = {(a , 1),(a , 2),(b , 1),(b , 2)}

5.4 Compilation of Loops

Variables that occur in a loop, but do not occur before the loop in the outer scope, are local to each iteration of the loop. For example, in the rule

p(A) =>
    foreach (I in 1 .. A.length)
        E = A[I],
        println(E)
    end.

the variables I and E are local, and each iteration of the loop has its own values for these variables.

Consider the example:

Example

while_test(N) =>
    I = 1,
    while (I <= N)
        I := I + 1,
        println(I)
    end.

In this example, the while loop contains an assignment statement. As mentioned above, at compilation time, Picat creates new variables in order to handle assignments. One new variable is created for each assignment. However, when this example is compiled, the compiler does not know the number of times that the body of the while loop can be executed. This means that the compiler does not know how many times the assignment I := I + 1 will occur, and the compiler is unable to create new variables for this assignment. In order to solve this problem, the compiler compiles while loops into tail-recursive predicates.

In the while_test example, the while loop is compiled into:

while_test(N) =>
    I = 1,
    p(I, N).

p(I, N), I <= N => 
    I1 = I + 1,
    println(I1),
    p(I1, N).
p(_, _) => true. 

Note that the first rule of the predicate p(I, N) has the same condition as the while loop. The second rule, which has no condition, terminates the while loop, because the second rule is only executed if I > N. The call p(I1, N) is the tail-recursive call, with I1 storing the modified value.

Suppose that a while loop modifies a variable that is then used outside of the while loop. For each modified variable V that is used after the while loop, predicate p is passed two arguments, Vin and Vout. Then, a predicate that has the body true is not sufficient to terminate the compiled while loop.

The next example demonstrates a loop that has multiple accumulators, and that modifies values which are then used outside of the loop.

Example

min_max([H|T], Min, Max) =>
    LMin = H,
    LMax = H,
    foreach (E in T)
        LMin := min(LMin, E),
        LMax := max(LMax, E)
    end,
    Min = LMin,
    Max = LMax.

This loop finds the minimum and maximum values of a list. The loop is compiled to:

min_max([H|T], Min, Max) =>
    LMin = H,
    LMax = H,
    p(T, LMin, LMin1, LMax, LMax1),
    Min = LMin1,
    Max = LMax1.

p([], MinIn, MinOut, MaxIn, MaxOut) =>
    MinOut = MinIn,
    MaxOut = MaxIn.
p([E|T], MinIn, MinOut, MaxIn, MaxOut) =>
    Min1 = min(MinIn, E),
    Max1 = max(MaxIn, E),
    p(T, Min1, MinOut, Max1, MaxOut).

Notice that there are multiple accumulators: MinIn and MaxIn. Since the min_max predicate returns two values, the accumulators each have an in variable (MinIn and MaxIn) and an out variable (MinOut and MaxOut). If the first parameter of predicate p is an empty list, then MinOut is set to the value of MinIn, and MaxOut is set to the value of MaxIn.

Foreach and do-while loops are compiled in a similar manner to while loops.

Nested Loops

As mentioned above, variables that only occur within a loop are local to each iteration of the loop. In nested loops, variables that are local to the outer loop are global to the inner loop. In other words, if a variable occurs in the outer loop, then the variable is also visible in the inner loop. However, variables that are local to the inner loop are not visible to the outer loop.

For example, consider the nested loops:

nested =>
    foreach (I in 1 .. 10)
        printf("Numbers between %d and %d ", I, I * I),
        foreach (J in I .. I * I)
            printf("%d ", J)
        end,
        nl
    end.

Variable I is local to the outer foreach loop, and is global to the inner foreach loop. Therefore, iterator J is able to iterate from I to I * I in the inner foreach loop. Iterator J is local to the inner loop, and does not occur in the outer loop.

Since a foreach loop with N iterators is converted into N nested foreach loops, the order of the iterators matters.

5.4.1 List Comprehensions

List comprehensions are compiled into foreach loops.

Example

comp_ex =>
    L = [(A, X) : A in [a, b], X in 1 .. 2].

This list comprehension is compiled to:

comp_ex =>
    L = List, 
    foreach (A in [a, b], X in 1 .. 2)
        List = [(A, X) | T], 
        List := T
    end,
    List = [].

Example

make_list1 =>
    L = [Y : X in 1..5],
    write(L).

make_list2 =>
    Y = Y,
    L = [Y : X in 1..5],
    write(L).

Suppose that a user would like to create a list [Y, Y, Y, Y, Y]. The make_list1 predicate incorrectly attempts to make this list; instead, it outputs a list of 5 different variables since Y is local. In order to make all five variables the same, make_list2 makes variable Y global, by adding the line Y = Y to globalize Y.