type: special form (fsubr) location: built-in source file: xlcont.c Common LISP compatible: similar supported on: all machines
(case <expr> [ ( <value> <action> ) ... ] ) <expr> - an expression <value> - an unevaluated expression or list of unevaluated expressions to compare against <expr> <action> - an expression
The CASE special form is a selection control form. CASE evaluates <expr>. This value is then compared against all the <value> entries. If <value> is a single atom, the atom is compared against <expr>. If <value> is a list, each of the elements of the list are compared against <expr>. The <action> associated with the first <value> that matches <expr> is evaluated and returned as CASE's result. If no <value> matches, a NIL is returned. If the last <value> is the T symbol and no other <value> has matched <expr>, then CASE will evaluate the <action> associated with T. If there are multiple T entries, the first is considered to be the end of the CASE.
(case 'a ('a "a")) ; returns "a" (case 'a ('b "b")) ; returns NIL (case 9 ( 1 "num") (t "ho") (t "hi")) ; returns "ho" (case 'a ((1 2 3 4) "number") ; ( (a b c d) "alpha")) ; returns "alpha" (case 'a) ; returns NIL (case) ; returns NIL (defun print-what (parm) ; define a function (case (type-of parm) ; check PARM type ( flonum (print "float")) ; ( fixnum (print "integer")) ; ( string (print "string")) ; ( cons (print "list")) ; ( T (print "other"))) ; otherwise NIL) ; and always return NIL (print-what 1.2) ; prints "float" returns NIL (print-what 3) ; prints "integer" returns NIL (print-what "ab") ; prints "string" returns NIL (print-what '(a b)) ; prints "list" returns NIL (print-what 'a) ; prints "other" returns NIL
NOTE: The CASE special form does not work with a list or string as the <expr>. This is because CASE defines the test used to be the EQL test which does not work with lists or strings, only symbols and numbers.
COMMON LISP COMPATIBILITY: In XLISP, you can use the value T as the last value to get the effect of 'otherwise'. Common LISP uses the symbol OTHERWISE and T for this. If you are porting in code from Common LISP, be careful to make sure T is used instead of OTHERWISE in CASE statements. (Note that no error will be generated, XLISP will just try to match the <expr> to OTHERWISE.