next up previous

12.6.9 Switch

The switch function allows a particular group of actions (among several groups of actions) to be performed based on a specified value.

Syntax

(switch <test-expression>
   <case-statement>
   <case-statement>+
   [<default-statement>])

<case-statement> ::=
   (case <comparison-expression> then <action>*)

<default-statement> ::= (default <action>*)

As indicated by the BNF, there must be at least two case statements, and the optional default statement must succeed all case statements. None of the case comparison expressions should be the same.

The switch function evaluates the <test-expression> first and then evaluates each <comparison-expression> in order of definition. Once the evaluation of the <comparison-expression> is equivalent to the evaluation of the <test-expression>, the actions of that case are evaluated (in order) and the switch function is terminated. If no cases are satisfied, the default actions (if any) are evaluated (in order).

The return value of the switch function is the last action evaluated in the switch function. If no actions are evaluated, the return value is the symbol FALSE.

Example

CLIPS> (defglobal ?*x* = 0)
CLIPS> (defglobal ?*y* = 1)
CLIPS>
(deffunction foo (?val)
  (switch ?val
  (case ?*x* then *x*)
  (case ?*y* then *y*)
  (default none)))
CLIPS> (foo 0)
*x*
CLIPS> (foo 1)
*y*
CLIPS> (foo 2)
none
CLIPS>


next up previous