DeAL TutorialThe If-Then-Else Construct

The If-Then-Else Construct

The if-then-else construct can only be used in the body of a rule

The meaning of

h <- if(p then q else w).

is strictly logical. The semantics of this rule is the same as:

h <-  p, q.
h <- ~p, w.

Thus, e.g., the compiler requires that the original program, so expanded, must be stratified.

However, if-then-else is implemented directly, i.e., without rewriting the program. Thus it adds efficiency, since p is executed only once.

When there are side effects, e.g., in updates, the meaning is no longer the same.

Example: Compare two length measures, expressed in yards and inches.

gt_or_eq(length(Y1,I1), length(Y2, I2)) <- if(Y1 = Y2 then I1 >= I2 else Y1 > Y2).

Note that the syntax of the if-predicate is the same as that of a predicate.

Omitting the else clause:

The abbreviation,

h <- if(p then q).

is also allowed. Its meaning is

h <- if(p then q else true).

If-Then-Else and Existential Variables

A common programming mistake is the implicit use of the else true clause, which may result in an unsafe rule, as per the following:

Example: "If exceptions occur, then take corrective action and report the problem, otherwise take normal action."

report_problems(X) <- if(problem(X) then corrective_action else normal_action).
export report_problem($X).

is safe however,

export report_problem(X).

is not; what do we report when there is no problem?

A correct formulation would be:

report_problem(X) <- if(problem(Y) then X = Y, corrective_action else X = "noproblem", normal_action).
DeAL forces you to write complete specifications. A common mistake is to write the previous rules as:

report_problem(X) <- if(problem(X) then corrective_action else X = noproblem, normal_action).

This can be re-expressed using negation as follows:

report_problem(X) <-  problem(X), corrective_action.
report_problem(X) <- ~problem(X), X = noproblem, normal_action.

The error is that a non-existential variable is used before it is bound.


Last Updated 2014