Theory Partial_Function_MR_Examples
section ‹Examples›
theory Partial_Function_MR_Examples
imports
Partial_Function_MR
"HOL-Library.Monad_Syntax"
HOL.Rat
begin
subsection ‹Collatz function›
text ‹In the following, we define the Collatz function,
which is artificially encoded via mutually recursive functions.
As second argument we store the intermediate values.
It is currently unknown whether this function is terminating for all inputs or not.›
partial_function_mr (tailrec) collatz and even_case and odd_case where
"collatz (x :: int) xs =
(if (x ≤ 1) then rev (x # xs) else
(if (x mod 2 = 0) then even_case x (x # xs)
else odd_case x xs))"
| "even_case x xs = collatz (x div 2) xs"
| [simp]: "odd_case x xs = collatz (3 * x + 1) (x # xs)"
text ‹The equations are registered as code-equations.›
lemma "length (collatz 327 []) = 144" by eval
text ‹The equations are accessible via .simps, but are not put in the standard simpset.›
lemma "collatz 5 [] = [5,16,8,4,2,1]" by (simp add: collatz.simps even_case.simps)
subsection ‹Evaluating expressions›
text ‹Note that we also provide a least fixpoint operator.
Hence, the evaluation function will clearly be partial.
The example also illustrates the usage
of polymorphism and of different return types.›
text ‹In the following datatype, \isa{Mu b f a} encodes the least $n$ such that $b(f^n(a))$.›