section‹Implementation of natural numbers as binary numerals›
theory Code_Binary_Nat imports Code_Abstract_Nat begin
text‹
When generating code for functions on natural numbers, the
canonical representation using term‹0::nat› and term‹Suc› is unsuitable for computations involving large
numbers. This theory refines the representation of
natural numbers for code generation to use binary
numerals, which do not grow linear in size but logarithmic. ›
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 ==> 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 und die Messung sind noch experimentell.