Yorick: Loops

Home Manual Packages Global Index Keywords Quick Reference |
### 1.2.4 Loops Most loops in Yorick programs are implicit; remember that operations between array arguments produce array results. Whenever you write a Yorick program, you should be suspicious of all explicit loops. Always ask yourself whether a clever use of array syntax could have avoided the loop. To illustrate an appropriate Yorick loop, let's revise `q_out` to write several values of Q in a single call. Incidentally, this sort of incremental revision of a function is very common in Yorick program development. As you use a function, you notice that the surrounding code is often the same, suggesting a savings if it were incorporated into the function. Again, a careful job leaves all of the previous behavior of `q_out` intact:
    func q_out(Q, file)
    {
      if (structof(file)==string) file = create(file);
      n = numberof(Q);
      for (i=1 ; i<=n ; ++i) {
        write, file, "Q = "+pr1(Q(i));
        write, file, "   theta       amplitude";
        write, file, theta, damped_wave(theta,Q(i));
      }
      return file;
    }
Two new features here are the `numberof` function, which returns the length of the array `Q`, and the array indexing syntax `Q(i)`, which extracts the `i`-th element of the array `Q`. If `Q` is scalar (as it had to be before this latest revision), `numberof` returns 1, and `Q(1)` is the same as `Q`, so scalar `Q` works as before. But the most important new feature is the `for` loop. It says to initialize `i` to 1, then, as long as `i` remains less than or equal to `n`, to execute the loop body, which is a compound of three write statements. Finally, after each pass, the increment expression `++i` is executed before the `i<=n` condition is evaluated. `++i` is equivalent to `i=i+1`; `--i` means `i=i-1`. A loop body may also be a single statement, in which case the curly braces are unecessary. For example, the following lines will write the Q=3, Q=2, and Q=1 curves to the file ``q.out'`, then plot them:
    q_list = [3,2,1]
    q_out, q_list, "q.out"
    fma; for(i=1;i<=3;++i) plg, damped_wave(theta,q_list(i)), theta
> A `for` loop with a `plg` body is the easiest way to overlay a series of curves. After the three simple statement types, `for` statements see the most frequent direct use from the keyboard.
> 1.2.4.1 The `while` and `do while` statements |  |
> 1.2.4.2 The `for` statement |  |
> 1.2.4.3 Using `break`, `continue`, and `goto` |  | How to break, continue, and goto from a loop body.