The Hyper Programming Language

'loop' Statement

General

The 'loop' statement in Hyper is designed for looping that is bounded by one or more conditions, like the 'while' and 'do' statements from C++ and Java. 'loop', however, is more advanced than 'while' and 'do'.

The statement comes in three forms: one like 'while', one that looks like 'do', and another one we'll discuss below.

Syntax

The first form is identical to 'while'. The loop continues when the condition evaluates to true:

loop when condition
  statements
end loop

Note that you are allowed to write just end instead of the full end loop if you like.

The second form looks like 'do', but the use of the condition is different so that it looks natural with this syntax. Now the loop exits when the condition evaluates to true:

loop
  statements
end loop when exit_condition

Again, you are allowed to write just end when exit_condition instead of the complete end loop when exit_condition.

The third form is probably new to you. It is a loop with multiple conditions. The loop continues when at least one condition is true. Each condition belongs to a branch that contains statements to be executed when that particular condition is true. The branch of the first condition that is found to be true, is executed, and then the loop continues from the beginning. And finally, when all conditions evaluate to false, the loop stops. The number of conditions has to be at least one. Such a loop that has exactly one condition, performs identical to the first form of the 'loop' statement or a 'while'.

loop
  when condition then
    statements
  when condition then
    statements
  when condition then
    statements
end loop

Examples

First a simple example of the first form:

procedure throwDiceSix()
  var dice : nat = 0
  # try to throw a 6
  loop when dice != 6
    dice = system.Math.randomNat(16# get a random number in the range 1 to 6 (1 and 6 included)
  end
end

The same example, now written using the second form:

procedure throwDiceSix()
  var dice : nat = 0
  # try to throw a 6
  loop
    dice = system.Math.randomNat(16# get a random number in the range 1 to 6 (1 and 6 included)
  end when dice = 6
end

Now a simple example showing the third form. It calculates the greatest common denominator of two numbers:

procedure gcd(a & b : nat)
  loop
    when a > b then
      a -= b
    when a < b then
      b -= a
  end

  return a
end

See also


Valid HTML 4.01 Strict Valid CSS!