82099
|
1 |
(*
|
|
2 |
Author: Jonas Stahl
|
|
3 |
|
|
4 |
Nonstandard examples of the time function definition commands.
|
|
5 |
*)
|
|
6 |
|
|
7 |
theory Time_Examples
|
|
8 |
imports Define_Time_Function
|
|
9 |
begin
|
|
10 |
|
|
11 |
fun even :: "nat \<Rightarrow> bool"
|
|
12 |
and odd :: "nat \<Rightarrow> bool" where
|
|
13 |
"even 0 = True"
|
|
14 |
| "odd 0 = False"
|
|
15 |
| "even (Suc n) = odd n"
|
|
16 |
| "odd (Suc n) = even n"
|
|
17 |
time_fun even odd
|
|
18 |
|
|
19 |
locale locTests =
|
|
20 |
fixes f :: "'a \<Rightarrow> 'b"
|
|
21 |
and T_f :: "'a \<Rightarrow> nat"
|
|
22 |
begin
|
|
23 |
|
|
24 |
fun simple where
|
|
25 |
"simple a = f a"
|
|
26 |
time_fun simple
|
|
27 |
|
|
28 |
fun even :: "'a list \<Rightarrow> 'b list" and odd :: "'a list \<Rightarrow> 'b list" where
|
|
29 |
"even [] = []"
|
|
30 |
| "odd [] = []"
|
|
31 |
| "even (x#xs) = f x # odd xs"
|
|
32 |
| "odd (x#xs) = even xs"
|
|
33 |
time_fun even odd
|
|
34 |
|
|
35 |
fun locSum :: "nat list \<Rightarrow> nat" where
|
|
36 |
"locSum [] = 0"
|
|
37 |
| "locSum (x#xs) = x + locSum xs"
|
|
38 |
time_fun locSum
|
|
39 |
|
|
40 |
fun map :: "'a list \<Rightarrow> 'b list" where
|
|
41 |
"map [] = []"
|
|
42 |
| "map (x#xs) = f x # map xs"
|
|
43 |
time_fun map
|
|
44 |
|
|
45 |
end
|
|
46 |
|
|
47 |
definition "let_lambda a b c \<equiv> let lam = (\<lambda>a b. a + b) in lam a (lam b c)"
|
|
48 |
time_fun let_lambda
|
|
49 |
|
|
50 |
partial_function (tailrec) collatz :: "nat \<Rightarrow> bool" where
|
|
51 |
"collatz n = (if n \<le> 1 then True
|
|
52 |
else if n mod 2 = 0 then collatz (n div 2)
|
|
53 |
else collatz (3 * n + 1))"
|
|
54 |
|
|
55 |
text \<open>This is the expected time function:\<close>
|
|
56 |
partial_function (option) T_collatz' :: "nat \<Rightarrow> nat option" where
|
|
57 |
"T_collatz' n = (if n \<le> 1 then Some 0
|
|
58 |
else if n mod 2 = 0 then Option.bind (T_collatz' (n div 2)) (\<lambda>k. Some (Suc k))
|
|
59 |
else Option.bind (T_collatz' (3 * n + 1)) (\<lambda>k. Some (Suc k)))"
|
|
60 |
time_fun_0 "(mod)"
|
|
61 |
time_partial_function collatz
|
|
62 |
|
|
63 |
text \<open>Proof that they are the same up to 20:\<close>
|
|
64 |
lemma setIt: "P i \<Longrightarrow> \<forall>n \<in> {Suc i..j}. P n \<Longrightarrow> \<forall>n \<in> {i..j}. P n"
|
|
65 |
by (metis atLeastAtMost_iff le_antisym not_less_eq_eq)
|
|
66 |
lemma "\<forall>n \<in> {2..20}. T_collatz n = T_collatz' n"
|
|
67 |
apply (rule setIt, simp add: T_collatz.simps T_collatz'.simps, simp)+
|
|
68 |
by (simp add: T_collatz.simps T_collatz'.simps)
|
|
69 |
|
|
70 |
end |