src/Doc/Tutorial/Misc/Option2.thy
changeset 48985 5386df44a037
parent 36176 3fe7e97ccca8
child 58860 fee7cfa69c50
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/Doc/Tutorial/Misc/Option2.thy	Tue Aug 28 18:57:32 2012 +0200
     1.3 @@ -0,0 +1,33 @@
     1.4 +(*<*)
     1.5 +theory Option2 imports Main begin
     1.6 +hide_const None Some
     1.7 +hide_type option
     1.8 +(*>*)
     1.9 +
    1.10 +text{*\indexbold{*option (type)}\indexbold{*None (constant)}%
    1.11 +\indexbold{*Some (constant)}
    1.12 +Our final datatype is very simple but still eminently useful:
    1.13 +*}
    1.14 +
    1.15 +datatype 'a option = None | Some 'a;
    1.16 +
    1.17 +text{*\noindent
    1.18 +Frequently one needs to add a distinguished element to some existing type.
    1.19 +For example, type @{text"t option"} can model the result of a computation that
    1.20 +may either terminate with an error (represented by @{const None}) or return
    1.21 +some value @{term v} (represented by @{term"Some v"}).
    1.22 +Similarly, @{typ nat} extended with $\infty$ can be modeled by type
    1.23 +@{typ"nat option"}. In both cases one could define a new datatype with
    1.24 +customized constructors like @{term Error} and @{term Infinity},
    1.25 +but it is often simpler to use @{text option}. For an application see
    1.26 +\S\ref{sec:Trie}.
    1.27 +*}
    1.28 +(*<*)
    1.29 +(*
    1.30 +definition infplus :: "nat option \<Rightarrow> nat option \<Rightarrow> nat option" where
    1.31 +"infplus x y \<equiv> case x of None \<Rightarrow> None
    1.32 +               | Some m \<Rightarrow> (case y of None \<Rightarrow> None | Some n \<Rightarrow> Some(m+n))"
    1.33 +
    1.34 +*)
    1.35 +end
    1.36 +(*>*)