Theory Suc_Notation
theory Suc_Notation
imports Main
begin
text ‹Nested ‹Suc› terms of depth ‹2 ≤ n ≤ 9› are abbreviated with new notations ‹Suc⇧n›:›
abbreviation (input) Suc2 where "Suc2 n ≡ Suc (Suc n)"
abbreviation (input) Suc3 where "Suc3 n ≡ Suc (Suc2 n)"
abbreviation (input) Suc4 where "Suc4 n ≡ Suc (Suc3 n)"
abbreviation (input) Suc5 where "Suc5 n ≡ Suc (Suc4 n)"
abbreviation (input) Suc6 where "Suc6 n ≡ Suc (Suc5 n)"
abbreviation (input) Suc7 where "Suc7 n ≡ Suc (Suc6 n)"
abbreviation (input) Suc8 where "Suc8 n ≡ Suc (Suc7 n)"
abbreviation (input) Suc9 where "Suc9 n ≡ Suc (Suc8 n)"
notation Suc2 ("Suc⇧2")
notation Suc3 ("Suc⇧3")
notation Suc4 ("Suc⇧4")
notation Suc5 ("Suc⇧5")
notation Suc6 ("Suc⇧6")
notation Suc7 ("Suc⇧7")
notation Suc8 ("Suc⇧8")
notation Suc9 ("Suc⇧9")
text ‹Beyond 9, the syntax ‹Suc⇗n⇖› kicks in:›
syntax
"_Suc_tower" :: "num_token ⇒ nat ⇒ nat" ("Suc⇗_⇖")
parse_translation ‹
let
fun mk_sucs_aux 0 t = t
| mk_sucs_aux n t = mk_sucs_aux (n - 1) (\<^const>‹Suc› $ t)
fun mk_sucs n = Abs("n", \<^typ>‹nat›, mk_sucs_aux n (Bound 0))
fun Suc_tr [Free (str, _)] = mk_sucs (the (Int.fromString str))
in [(\<^syntax_const>‹_Suc_tower›, K Suc_tr)] end
›
print_translation ‹
let
val digit_consts =
[\<^const_syntax>‹Suc2›, \<^const_syntax>‹Suc3›, \<^const_syntax>‹Suc4›, \<^const_syntax>‹Suc5›,
\<^const_syntax>‹Suc6›, \<^const_syntax>‹Suc7›, \<^const_syntax>‹Suc8›, \<^const_syntax>‹Suc9›]
val num_token_T = Simple_Syntax.read_typ "num_token"
val T = num_token_T --> HOLogic.natT --> HOLogic.natT
fun mk_num_token n = Free (Int.toString n, num_token_T)
fun dest_Suc_tower (Const (\<^const_syntax>‹Suc›, _) $ t) acc =
dest_Suc_tower t (acc + 1)
| dest_Suc_tower t acc = (t, acc)
fun Suc_tr' [t] =
let
val (t', n) = dest_Suc_tower t 1
in
if n > 9 then
Const (\<^syntax_const>‹_Suc_tower›, T) $ mk_num_token n $ t'
else if n > 1 then
Const (List.nth (digit_consts, n - 2), T) $ t'
else
raise Match
end
in [(\<^const_syntax>‹Suc›, K Suc_tr')]
end
›
end