|
The conditional statement has the usual form
if ... then ... else ... end if;.
It has several variants. Within the statement, a special prompt
will appear, indicating that the statement has yet to be closed.
Conditional statements may be nested.
The conditional expression, select ... else, is used for in-line conditionals.
if Boolean expression then statements end if;
The standard conditional statement: the value of the Boolean expression
is evaluated. If the result is true then the first block of statements
is executed, while if the result is false the second block of statements
is executed. If no action is desired in the latter case, the construction
may be abbreviated to the second form above.
Since nested conditions occur frequently, elif provides a convenient
abbreviation for else if, which also restricts the `level':
if boolexpr then
statments1
elif boolxpr2 then
statments2
else
statments3
end if;
is equivalent to
if boolxpr1 then
statments1
else
if boolxpr2 then
statments2
else
statments3
end if;
end if;
> m := Random(2, 10000);
> if IsPrime(m) then
> m, "is prime";
> else
> Factorization(m);
> end if;
[ <23, 1>, <37, 1> ]
Using the select ... else construction, we wish to assign the
sign of y to the variable s.
> y := 11;
> s := (y gt 0) select 1 else -1;
> s;
1
This is not quite right (when y = 0), but
fortunately we can nest select ... else constructions:
> y := -3;
> s := (y gt 0) select 1 else (y eq 0 select 0 else -1);
> s;
-1
> y := 0;
> s := (y gt 0) select 1 else (y eq 0 select 0 else -1);
> s;
0
The select ... else construction is particularly important in building
sets and sequences, because it enables in-line if constructions.
Here is a sequence containing the first 100 entries of the Fibonacci
sequence:
> f := [ i gt 2 select Self(i-1)+Self(i-2) else 1 : i in [1..100] ];
The expression following case is evaluated.
The statements following the first expression whose value equals
this value are executed, and then the case statement has finished.
If none of the values of the expressions equal the value of the case expression,
then the statements following else are executed, in the first form.
If no action is desired in the latter case, the construction
may be abbreviated to the second form above.
> x := 73;
> case Sign(x):
> when 1:
> x, "is positive";
> when 0:
> x, "is zero";
> when -1:
> x, "is negative";
> end case;
73 is positive
This is the expression form of case.
The expr is evaluated to the value v. Then each of the left-hand expressions
expr_((left), i) is evaluated until one is found whose value
equals v; if this happens the value of the corresponding right-hand
expression expr_((right), i) is returned. If no left-hand expression
with value v is found the value of the default expression
exprdef is returned.
The default case cannot be omitted, and must come last.
[Next][Prev] [Right] [Left] [Up] [Index] [Root]
|