[Next] [Prev] [Right] [Left] [Up] [Index] [Root]
Conditional Statements and Expressions

Conditional Statements and Expressions

The conditional statement has the obvious 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.


Example Lang_InLineConditional (H1E11)

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;
> print 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);
> print s;
-1
> y := 0;
> s := (y gt 0) select 1 else (y eq 0 select 0 else -1);
> print 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] ];

Example Lang_if (H1E12)

> m := Random( 2, 10000 );
> if IsPrime(m) then
>    print m, "is prime";
> else
>    print Factorization(m);
> end if;
[ <23, 1>, <37, 1> ]

Example Lang_case (H1E13)

> x := 73; 
> case Sign(x):
>    when 1: 
>       print x, "is positive";
>    when 0: 
>       print x, "is zero";    
>    when -1:
>       print x, "is negative";
> end case;
73 is positive

[Next] [Prev] [Right] [Left] [Up] [Index] [Root]