2 theory case_exprs = Main:
5 subsection{*Case expressions*}
7 text{*\label{sec:case-expressions}
8 HOL also features \isaindexbold{case}-expressions for analyzing
9 elements of a datatype. For example,
11 @{term[display]"case xs of [] => 1 | y#ys => y"}
13 evaluates to @{term"1"} if @{term"xs"} is @{term"[]"} and to @{term"y"} if
14 @{term"xs"} is @{term"y#ys"}. (Since the result in both branches must be of
15 the same type, it follows that @{term"y"} is of type @{typ"nat"} and hence
16 that @{term"xs"} is of type @{typ"nat list"}.)
18 In general, if $e$ is a term of the datatype $t$ defined in
19 \S\ref{sec:general-datatype} above, the corresponding
20 @{text"case"}-expression analyzing $e$ is
23 @{text"case"}~e~@{text"of"} & C@1~x@ {11}~\dots~x@ {1k@1} & \To & e@1 \\
25 \mid & C@m~x@ {m1}~\dots~x@ {mk@m} & \To & e@m
30 \emph{All} constructors must be present, their order is fixed, and nested
31 patterns are not supported. Violating these restrictions results in strange
35 Nested patterns can be simulated by nested @{text"case"}-expressions: instead
39 @{text"case xs of [] => 1 | [x] => x | x#(y#zs) => y"}
40 %~~~case~xs~of~[]~{\isasymRightarrow}~1~|~[x]~{\isasymRightarrow}~x~|~x~\#~y~\#~zs~{\isasymRightarrow}~y
44 @{term[display,eta_contract=false,margin=50]"case xs of [] => 1 | x#ys => (case ys of [] => x | y#zs => y)"}
47 Note that @{text"case"}-expressions may need to be enclosed in parentheses to
51 subsection{*Structural induction and case distinction*}
54 \indexbold{structural induction}
55 \indexbold{induction!structural}
56 \indexbold{case distinction}
57 Almost all the basic laws about a datatype are applied automatically during
58 simplification. Only induction is invoked by hand via \isaindex{induct_tac},
59 which works for any datatype. In some cases, induction is overkill and a case
60 distinction over all constructors of the datatype suffices. This is performed
61 by \isaindexbold{case_tac}. A trivial example:
64 lemma "(case xs of [] \<Rightarrow> [] | y#ys \<Rightarrow> xs) = xs";
68 results in the proof state
70 ~1.~xs~=~[]~{\isasymLongrightarrow}~(case~xs~of~[]~{\isasymRightarrow}~[]~|~y~\#~ys~{\isasymRightarrow}~xs)~=~xs\isanewline
71 ~2.~{\isasymAnd}a~list.~xs=a\#list~{\isasymLongrightarrow}~(case~xs~of~[]~{\isasymRightarrow}~[]~|~y\#ys~{\isasymRightarrow}~xs)~=~xs%
73 which is solved automatically:
79 Note that we do not need to give a lemma a name if we do not intend to refer
80 to it explicitly in the future.