Difference between revisions of "Language Reference/Terms/If-then-else"
< Language Reference | Terms
m (1 revision(s)) |
|
(No difference)
|
Revision as of 15:22, 15 September 2008
Conditionally executes a group of statements.
IfThenElseTerm: if Condition then Term Elseif-list-opt Else-opt end if Elseif: elseif Condition then Term Else: else Term
The following two terms are equivalents.
if Cond1 then T1 elseif Cond2 then T2 else T3 end if
if Cond1 then T1 else if Cond2 then T2 else T3 end if end if
Consider the schematic if then else term:
if Cond then T1 else T2 end if
First Cond is evaluated, if it succeeds then T1 is evaluated otherwise T2 is evaluated. Cond is not allowed to leave backtrack points; that is, it cannot be multi or nondeterm. Cond is a cut-scope (see Cut Scopes).
Example
clauses w(X) :- if X div 2 = 0 and X > 3 then write("X is good") else write("X is bad"), nl end if, nl.
There are several things to notice about this example:
- You can use "and" and "or" logical operators and other "complex" terms in all three sub-terms.
- There is no comma before the keywords "then", "elseif", "else", and "end if".
For readability sake, we always recommend using "or" instead of ";". Likewise we also recommend using "and" (instead of ",") when it (as in the condition above) represents a logical "condition" rather than a "sequentation".
Leaving out the else-part is just shorthand for writing that else succeed, i.e.
if Cond then T1 end if
is short-hand for
if Cond then T1 else succeed end if