(* Title: HOL/Library/Code_Binary_Nat.thy Author: Florian Haftmann, TU Muenchen
*)
section \<open>Implementation of natural numbers as binary numerals\<close>
theory Code_Binary_Nat imports Code_Abstract_Nat begin
text\<open>
When generating code for functions on natural numbers, the
canonical representation using\<^term>\<open>0::nat\<close> and \<^term>\<open>Suc\<close> is unsuitable for computations involving large
numbers. This theory refines the representation of
natural numbers for code generation touse binary
numerals, which do not grow linear in size but logarithmic. \<close>
qualified definition sub :: "num \ num \ nat option" where "sub k l = (if k \ l then Some (numeral k - numeral l) else None)"
lemma sub_code [code]: "sub Num.One Num.One = Some 0" "sub (Num.Bit0 m) Num.One = Some (nat_of_num (Num.BitM m))" "sub (Num.Bit1 m) Num.One = Some (nat_of_num (Num.Bit0 m))" "sub Num.One (Num.Bit0 n) = None" "sub Num.One (Num.Bit1 n) = None" "sub (Num.Bit0 m) (Num.Bit0 n) = map_option dup (sub m n)" "sub (Num.Bit1 m) (Num.Bit1 n) = map_option dup (sub m n)" "sub (Num.Bit1 m) (Num.Bit0 n) = map_option (\q. dup q + 1) (sub m n)" "sub (Num.Bit0 m) (Num.Bit1 n) = (case sub m n of None \ None
| Some q \<Rightarrow> if q = 0 then None else Some (dup q - 1))" by (auto simp: nat_of_num_numeral Num.dbl_def Num.dbl_inc_def Num.dbl_dec_def
Let_def le_imp_diff_is_add BitM_plus_one sub_def dup_def
sub_non_positive nat_add_distrib sub_non_negative)
lemma minus_nat_code [code]: "0 - n = (0::nat)" "m - 0 = (m::nat)" "nat_of_num k - nat_of_num l = (case sub k l of None \ 0 | Some j \ j)" by (simp_all add: nat_of_num_numeral sub_non_positive sub_def)
lemma times_nat_code [code]: "0 * n = (0::nat)" "m * 0 = (0::nat)" "nat_of_num k * nat_of_num l = nat_of_num (k * l)" by (simp_all add: nat_of_num_numeral)
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.