switch

switch — tests arguments with conditions.

Syntax

switch (symbol) {case condition:
                      statement
                     [statement...]

                 [case condition:
                       statement
                      [statement...]]
                  ...

                 [default:
                       statement
                      [statement...]]}

		

Arguments

symbol

A symbol with a value to test against the value of the condition(s).

condition

Any Gamma or Lisp expression.

statement

Any Gamma statement.

Returns

The return value of the statement that corresponds to the first satisfied condition or the default. Otherwise nil.

Description

This statement is similar to the condition statement, except that it takes an argument. It checks the value of the passed symbol against the value of the condition for each case in turn. The first match returns the return value of the corresponding statement. If there is no match, it returns the return value of the default statement, if any.

The words "case" and "default" and the symbols {, :, and } are unchanging syntactical elements.

Example

Gamma> a = "on";
"on"
Gamma> b = 6;
6
Gamma> c = "Nothing";
"Nothing"
Gamma> switch(a) {case "on": 75; case "off": 20; default: 0;}
75
Gamma> switch(b) {case "on": 40; case "off": 10; default: princ("Huh?\n");}
Huh?
t
Gamma> switch(c) {case "on": 1; case "off": 0;}
nil
Gamma>  
		
#!/usr/cogent/bin/gamma


/*
  This example demonstrates the switch and condition
  statements.  The switch statement checks the command
  line argument and prints a response.  The case argument
  checks the command line argument and the result of the
  switch statement.
*/

function main ()
{
        a =  number ((cadr(argv)));

        switch (a)
        {
          case 1:
                princ ("One\n");
          case 2:
                princ ("Two\n");
          case 2+1:
                princ ("Three\n");
          case 4:
                princ ("Four\n");
          default:
                princ ("Something else: ", a, "\n");
        }
        
        condition
        {
          case a == 1:
                princ ("Condition a == 1\n");
          case cadr(argv) == "Hello":
                princ ("Condition a == Hello\n");
          default:
                princ ("No condition met\n");
        }
}

See Also

condition