tail-recursive implementation for length
authorAndreas Lochbihler
Wed, 10 Oct 2012 15:16:44 +0200
changeset 49808 418991ce7567
parent 49807 9a0843995fd3
child 49809 39db47ed6d54
tail-recursive implementation for length
src/HOL/List.thy
--- a/src/HOL/List.thy	Wed Oct 10 15:05:07 2012 +0200
+++ b/src/HOL/List.thy	Wed Oct 10 15:16:44 2012 +0200
@@ -5514,8 +5514,22 @@
   "list_ex P [i..j] \<longleftrightarrow> \<not> (all_interval_int (Not \<circ> P) i j)"
   by (simp add: list_ex_iff all_interval_int_def)
 
-hide_const (open) member null maps map_filter all_interval_nat all_interval_int
-
+text {* optimized code (tail-recursive) for @{term length} *}
+
+definition gen_length :: "nat \<Rightarrow> 'a list \<Rightarrow> nat"
+where "gen_length n xs = n + length xs"
+
+lemma gen_length_code [code]:
+  "gen_length n [] = n"
+  "gen_length n (x # xs) = gen_length (Suc n) xs"
+by(simp_all add: gen_length_def)
+
+declare list.size(3-4)[code del]
+
+lemma length_code [code]: "length = gen_length 0"
+by(simp add: gen_length_def fun_eq_iff)
+
+hide_const (open) member null maps map_filter all_interval_nat all_interval_int gen_length
 
 subsubsection {* Pretty lists *}