{"text": "Require Import Axioms CoqlibC Maps Iteration (* Errors *).\nRequire Import Integers Floats AST Linking.\nRequire Import ValuesC Memory Events Globalenvs Smallstep.\nRequire Import Machregs LocationsC Conventions Op LinearC.\nRequire Import Debugvar.\n(** newly added **)\nRequire Export Debugvarproof.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem AsmregsC MatchSimModSem.\nRequire SimMemId.\nRequire SoundTop.\nRequire Import LiftDummy.\n\nSet Implicit Arguments.\n\n\n\nDefinition strong_wf_tgt (st_tgt0: Linear.state): Prop :=\n exists sg_init ls_init, last_option (LinearC.get_stack st_tgt0) = Some (Linear.dummy_stack sg_init ls_init).\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nVariables prog tprog: program.\nLet md_src: Mod.t := (LinearC.module prog).\nLet md_tgt: Mod.t := (LinearC.module tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\nHypothesis TRANSL: match_prog prog tprog.\nLet ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).\nLet tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).\nDefinition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.\n\nInductive match_states\n (idx: nat) (st_src0: Linear.state) (st_tgt0: Linear.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n (MATCHST: Debugvarproof.match_states st_src0 st_tgt0)\n (MCOMPATSRC: (get_mem st_src0) = sm0.(SimMem.src))\n (MCOMPATTGT: (get_mem st_tgt0) = sm0.(SimMem.tgt))\n (DUMMYTGT: strong_wf_tgt st_tgt0).\n\nTheorem make_match_genvs :\n SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n Genv.match_genvs (match_globdef (fun _ f tf => transf_fundef f = Errors.OK tf) eq prog) ge tge.\nProof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.\n\nTheorem sim_modsem: ModSemPair.sim msp.\nProof.\n eapply match_states_sim with (match_states := match_states) (match_states_at := top4) (sound_state := SoundTop.sound_state);\n eauto; ii; ss.\n - instantiate (1:= Nat.lt). apply lt_wf.\n - eapply SoundTop.sound_state_local_preservation.\n - (* init bsim *)\n inv INITTGT. destruct sm_arg; ss. clarify.\n inv SIMARGS; ss. clarify. inv TYP.\n exploit (fill_arguments_progress ls_init (typify_list vs_tgt (sig_args (fn_sig fd)))\n (Conventions1.loc_arguments (fn_sig fd))); eauto.\n { apply (f_equal (@length _)) in TYP0. rewrite map_length in *. etrans; try apply TYP0; eauto. }\n intro P; des.\n hexploit (@fill_arguments_spec); et. intro Q; des.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n eexists. eexists (SimMemId.mk _ _). esplits; ss; cycle 1.\n + econs; eauto; ss.\n * rpapply match_states_call.\n { econs; eauto.\n - instantiate (1:= (dummy_stack (fn_sig fd) ls_init)). unfold dummy_stack, dummy_function.\n rpapply match_stackframe_intro; eauto; swap 1 2.\n + econs; eauto.\n + econs; eauto. ss. econs; eauto. econs; eauto.\n + ss. f_equal; ss.\n * instantiate (1:= None). instantiate (1:= None). ss.\n * instantiate (1:= None). instantiate (1:= None). ss.\n - econs; et.\n }\n * rr. esplits; ss; eauto.\n + inv SAFESRC. folder. inv TYP.\n exploit (Genv.find_funct_transf_partial_genv SIMGE); eauto. intro FINDFSRC; des; clarify.\n unfold transf_fundef; ss. unfold Errors.bind in *. des_ifs.\n econs; swap 1 3.\n { folder; ss. eauto. }\n all: ss.\n unfold transf_function in *. des_ifs.\n - (* init progress *)\n des. inv SAFESRC. inv SIMARGS; ss.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. clarify. folder.\n inv TYP. unfold Errors.bind in *. des_ifs.\n destruct sm_arg; ss. clarify.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. clarify.\n exploit (fill_arguments_progress (Locmap.init Vundef) (typify_list vs_tgt (sig_args (fn_sig fd)))\n (Conventions1.loc_arguments (fn_sig fd))); eauto.\n { apply (f_equal (@length _)) in TYP0. rewrite map_length in *. etrans; try apply TYP0; eauto. }\n intro P; des.\n hexploit (fill_arguments_spec); eauto. intro Q; des.\n assert(SGEQ: fn_sig fd = fn_sig f).\n { unfold transf_function in *; des_ifs. }\n esplits; eauto. econs; swap 1 3.\n { ss. folder. eauto. }\n all: ss; eauto with congruence.\n + econs; ss; eauto with congruence.\n - (* call wf *)\n inv MATCH; ss. destruct sm0; ss. clarify.\n inv CALLSRC. inv MATCHST; ss.\n - (* call fsim *)\n inv MATCH; ss. destruct sm0; ss. clarify.\n inv CALLSRC. inv MATCHST; ss.\n folder. esplits; eauto.\n + econs; eauto.\n * folder. des.\n r in TRANSL. r in TRANSL.\n exploit (SimSymbId.sim_skenv_revive TRANSL); eauto.\n { apply SIMSKENV. }\n intro GE.\n apply (fsim_external_funct_id GE); ss.\n + econs; ss; eauto.\n * instantiate (1:= SimMemId.mk _ _). ss.\n * ss.\n + ss.\n - (* after fsim *)\n inv AFTERSRC. inv SIMRET; ss. exists sm_ret. destruct sm_ret; ss. clarify.\n inv MATCH; ss. inv MATCHST; ss. esplits; eauto.\n + econs; eauto.\n + econs; ss; eauto. econs; eauto.\n { inv H5; ss. - econs; eauto. - des_ifs. econs; eauto. inv H. econs; eauto. }\n { clear - DUMMYTGT. unfold strong_wf_tgt in *. des. destruct ts; ss. unfold dummy_stack, dummy_function in *. des_ifs; ss; clarify; esplits; et. }\n - (* final fsim *)\n inv MATCH. inv FINALSRC; inv MATCHST; ss.\n inv H3; ss. inv H4; ss. rr in DUMMYTGT. des. ss. clarify. destruct sm0; ss. clarify.\n eexists (SimMemId.mk _ _). esplits; ss; eauto.\n econs; ss; eauto. inv H1; ss. inv H2; ss.\n - left; i. esplits; eauto.\n { apply modsem_receptive; et. }\n inv MATCH.\n ii. rr in STEPSRC. des. hexploit (@transf_step_correct prog skenv_link); eauto.\n { inv SIMSKENV. ss. }\n { apply make_match_genvs; eauto. apply SIMSKENV. }\n i; des.\n exploit (lift_plus Linear.step (fun st => get_stack st <> []) strong_wf_tgt); ss; et.\n { intros st X Y. rr in X. des. rewrite Y in *. ss. }\n { i. folder. unfold strong_wf_tgt in *. des. inv HSTEP; ss; eauto.\n - des_ifs; ss; eauto.\n - des_ifs; ss; eauto. right. ii. inv HSTEP0; ss. }\n { ii. unfold strong_wf_tgt in *; des. inv HSTEP; try inv STACKS; ss; clarify; et; des_ifs; et. }\n { intro T. inv H0; ss; clarify; try inv STACKS; ss; try inv H1; ss. }\n intro TT; des.\n esplits; eauto.\n * left. eapply ModSemProps.spread_dplus; eauto.\n { eapply modsem_determinate; eauto. }\n * instantiate (1:= SimMemId.mk _ _). econs; ss.\nUnshelve.\n all: ss; try (by econs).\nQed.\n\nEnd SIMMODSEM.\n\n\n\n\nSection SIMMOD.\n\nVariables prog tprog: program.\nHypothesis TRANSL: match_prog prog tprog.\nDefinition mp: ModPair.t := SimSymbId.mk_mp (LinearC.module prog) (LinearC.module tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n econs; ss.\n - r. eapply Sk.match_program_eq; eauto.\n ii. destruct f1; ss.\n + clarify. right. unfold Errors.bind, transf_function in *. des_ifs. esplits; eauto.\n + clarify. left. esplits; eauto.\n - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/DebugvarproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.1895210913296776, "lm_q1q2_score": 0.09919919575457278}} {"text": "\n\n(* Mostly taken form https://github.com/sigurdschneider/lvc/blob/23b7fa8cd0640503ff370144fb407192632f9cc6/Infra/AutoIndTac.v *)\n\n(* fail 1 will break from the 'match H with', and indicate to\n the outer match that it should consider finding another \n hypothesis, see documentation on match goal and fail\n This tactic is a variation of Tobias Tebbi's revert_except_until *)\n\nLtac revert_all :=\n repeat match goal with [ H : _ |- _ ] => revert H end.\n\nTactic Notation \"revert\" \"all\" := revert_all.\n\nLtac revert_except i :=\n repeat match goal with [ H : _ |- _ ] => tryif unify H i then fail else revert H end.\n \nTactic Notation \"revert\" \"all\" \"except\" ident(i) := revert_except i.\n\nLtac clear_except i :=\n repeat match goal with [ H : _ |- _ ] => tryif unify H i then fail else clear H end.\n \nTactic Notation \"clear\" \"all\" \"except\" ident(i) := clear_except i.\n\nLtac clear_all :=\n repeat match goal with\n [H : _ |- _] => clear H\n end.\n\n\n(*\n(* succeed if H has a function type, fail otherwise *)\nLtac is_ftype H := \n let t := type of H in\n let t' := eval cbv in t in\n match t' with\n | _ -> _ => idtac\n end.\n*)\n(* match on the type of E and remember each of it's arguments\n that is not a variable by calling tac.\n tac needs to do a remember exactly if x is not a var, and \n fail otherwise. (We need to fail, otherwise the repeat will\n stop prematurely) \n try will silently ignore a fail 0, but will fail if a fail 1 or \n above occurs. Sequentialization makes sure fail 1 is executed \n if is_var is successful, hence try (is_var x; fail 1) will\n fail exactly when x is a var. *)\n\nLtac remember_arguments E :=\n let tac x := (try (is_var x; fail 1); (*try (is_ftype x; fail 1);*) remember (x)) in\n repeat (match type of E with\n | ?t ?x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ _ => tac x\n | ?t ?x _ _ _ _ => tac x\n | ?t ?x _ _ _ => tac x\n | ?t ?x _ _ => tac x\n | ?t ?x _ => tac x\n | ?t ?x => tac x\n end).\n\n(* from Coq.Program.Tactics *)\nLtac clear_dup :=\n match goal with\n | [ H : ?X |- _ ] =>\n match goal with\n | [ H' : ?Y |- _ ] =>\n match H with\n | H' => fail 2\n | _ => unify X Y ; (clear H' || clear H)\n end\n end\n end.\n\nLtac inv_eqs :=\n repeat (match goal with\n | [ H : @eq _ ?x ?x |- _ ] => fail (* nothing to do on x = x *)\n | [ H : @eq _ ?x ?y |- _ ] => progress (inversion H; subst; try clear_dup)\n end).\n\n(* this is a standard tactic *)\nLtac clear_trivial_eqs :=\n repeat (progress (match goal with\n | [ H : @eq _ ?x ?x |- _ ] => clear H\n end)).\n\nTactic Notation \"general\" \"induction\" hyp(H) :=\n remember_arguments H; revert_except H; \n induction H; intros; (try inv_eqs); (try clear_trivial_eqs).\n\n(* Module Test. *)\n(* Require Import List. *)\n\n(* Inductive decreasing : list nat -> Prop := *)\n(* | base : decreasing nil *)\n(* | step m n L : decreasing (n::L) -> n <= m -> decreasing (m :: n :: L). *)\n\n(* Lemma all_zero_by_hand L *)\n(* : decreasing (0::L) -> forall x, In x L -> x = 0. *)\n(* Proof. *)\n(* intros. remember (0::L). *)\n(* revert dependent L. revert x. induction H; intros. *)\n(* inversion Heql. *)\n(* inversion Heql. subst. inversion H0; subst; firstorder. *)\n(* Qed. *)\n\n(* Lemma all_zero L *)\n(* : decreasing (0::L) -> forall x, In x L -> x = 0. *)\n(* Proof. *)\n(* intros. general induction H. *)\n(* inversion H0; subst; firstorder. *)\n(* Qed. *)\n(* End Test. *)\n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/Tactics/AutoIndTac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.22541662103868043, "lm_q1q2_score": 0.09869269047462768}} {"text": "Require Export P04.\n\n\n\n(** **** Problem #2 : 1 star, optional (hd_opt_poly) *)\n(** Complete the definition of a polymorphic version of the\n [hd_opt] function from the last chapter. Be sure that it\n passes the unit tests below. *)\n\nDefinition hd_opt {X : Type} (l : list X) : option X :=\n match l with\n | nil => None\n | a :: l' => Some a\n end.\n \n\n(** Once again, to force the implicit arguments to be explicit,\n we can use [@] before the name of the function. *)\n\nCheck @hd_opt.\n\nExample test_hd_opt1 : hd_opt [1;2] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [[1];[2]] = Some [1].\nProof. reflexivity. Qed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/03/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.09859112038489397}} {"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef1.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n Definition table_unmap2_spec (g_rd: Pointer) (map_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n match map_addr, level with\n | VZ64 map_addr, VZ64 level =>\n rely is_int64 map_addr; rely (level >=? 3); rely GRANULE_ALIGNED map_addr; rely is_int64 level;\n let idx0 := __addr_to_idx map_addr 0 in\n let idx1 := __addr_to_idx map_addr 1 in\n let idx2 := __addr_to_idx map_addr 2 in\n let idx3 := __addr_to_idx map_addr 3 in\n let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n rely (peq (base g_rd) ginfo_loc);\n rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n let rd_gidx := (offset g_rd) in\n let grd := (gs (share adt)) @ rd_gidx in\n rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n rely prop_dec (glock grd = Some CPU_ID);\n let root_gidx := (g_rtt (gnorm grd)) in\n rely is_gidx rd_gidx; rely is_gidx root_gidx;\n when adt == query_oracle adt;\n let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n (* hold root lock *)\n let groot := (gs (share adt)) @ root_gidx in\n rely (tbl_level (gaux groot) =? 0);\n rely prop_dec (glock groot = None);\n rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n rely (gtype groot =? GRANULE_STATE_TABLE);\n (* walk deeper root *)\n let entry0 := (g_data (gnorm groot)) @ idx0 in\n rely is_int64 entry0;\n let phys0 := __entry_to_phys entry0 3 in\n let lv1_gidx := __addr_to_gidx phys0 in\n if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n (* level 1 valid, hold level 1 lock *)\n let glv1 := (gs (share adt)) @ lv1_gidx in\n rely prop_dec (glock glv1 = None);\n rely (tbl_level (gaux glv1) =? 1);\n (* walk deeper level 1 *)\n rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n rely (gtype glv1 =? GRANULE_STATE_TABLE);\n let entry1 := (g_data (gnorm glv1)) @ idx1 in\n rely is_int64 entry1;\n let phys1 := __entry_to_phys entry1 3 in\n let lv2_gidx := __addr_to_gidx phys1 in\n if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n (* level 2 valid, hold level 2 lock *)\n let glv2 := (gs (share adt)) @ lv2_gidx in\n rely (tbl_level (gaux glv2) =? 2);\n rely prop_dec (glock glv2 = None);\n if level =? 3 then\n (* walk until level 2 *)\n let adt := adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n unmap_table lv2_gidx idx2 level map_addr adt\n else\n (* walk deeper level 2 *)\n rely (g_tag (ginfo glv2) =? GRANULE_STATE_TABLE);\n rely (gtype glv2 =? GRANULE_STATE_TABLE);\n let entry2 := (g_data (gnorm glv2)) @ idx2 in\n rely is_int64 entry2;\n let phys2 := __entry_to_phys entry2 3 in\n let lv3_gidx := __addr_to_gidx phys2 in\n if (__entry_is_table entry2) && (GRANULE_ALIGNED phys2) && (is_gidx lv3_gidx) then\n (* level 2 valid, hold level 2 lock *)\n let adt := adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv3_gidx) :: log adt} in\n let glv3 := (gs (share adt)) @ lv3_gidx in\n rely prop_dec (glock glv3 = None);\n rely (tbl_level (gaux glv3) =? 3);\n if level =? 4 then\n (* walk until level 3 *)\n let adt := adt {priv: (priv adt) {wi_llt: lv3_gidx} {wi_index: idx3}} in\n unmap_table lv3_gidx idx3 level map_addr adt\n else (* can't be other level *)\n None\n else\n (* level 3 invalid *)\n Some (adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: log adt}\n {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n else\n (* level 2 invalid *)\n Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n else\n (* level 1 invalid *)\n Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef2/Specs/table_unmap2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.19436780635202988, "lm_q1q2_score": 0.09794313697298926}} {"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import TrapHandlerRaw.Layer.\nRequire Import RData.\nRequire Import Constants.\nRequire Import HypsecCommLib.\nRequire Import AbstractMachine.Spec.\nRequire Import TrapHandlerRaw.Spec.\nRequire Import TrapDispatcher.Spec.\nRequire Import FaultHandler.Spec.\nRequire Import MemHandler.Spec.\nRequire Import MmioOps.Spec.\nRequire Import BootOps.Spec.\nRequire Import MemoryOps.Spec.\nRequire Import MemManager.Spec.\nRequire Import NPTWalk.Spec.\nRequire Import NPTOps.Spec.\nRequire Import MmioSPTWalk.Spec.\nRequire Import MmioSPTOps.Spec.\n\nLocal Open Scope Z_scope.\n\nSection HighPTSpec.\n\n Fixpoint local_mmap_loop_h (n: nat) (gfn: Z) (pfn: Z) (level: Z) (pte: Z) (pt': ZMap.t (Z*Z*Z)) :=\n match n with\n | O => (gfn, pfn, pt')\n | S m =>\n match local_mmap_loop_h m gfn pfn level pte pt' with\n | (gfn', pfn', pt0) => (gfn'+1, pfn'+1, ZMap.set gfn' (pfn', level, pte) pt0)\n end\n end.\n\n Definition local_mmap_h (vmid: Z) (addr: Z) (level: Z) (pte: Z) (npt: NPT) :=\n if level =? 2 then\n let gfn := addr / PAGE_SIZE / PTRS_PER_PMD * PTRS_PER_PMD in\n let pfn := (phys_page pte) / PAGE_SIZE in\n let pgd_next' := (if (pgd_index addr) @ (pgd_t npt) then (pt_pgd_next npt) else (pt_pgd_next npt) + PAGE_SIZE) in\n let pud_next' := (if (pud_index addr) @ ((pgd_index addr) @ (pud_t npt))\n then (pt_pud_next npt) else (pt_pud_next npt) + PAGE_SIZE) in\n if (pgd_next' <=? pud_start vmid) && (pud_next' <=? pmd_start vmid) then\n match local_mmap_loop_h (Z.to_nat PTRS_PER_PMD) gfn pfn 2 pte (pt npt) with\n | (_, _, pt') =>\n let npt' := npt {pt: pt'} {pgd_t: ZMap.set (pgd_index addr) true (pgd_t npt)}\n {pud_t: (pud_t npt) # (pgd_index addr) == (((pgd_index addr) @ (pud_t npt)) # (pud_index addr) == true)}\n {pmd_t: (pmd_t npt) # (pgd_index addr) ==\n (((pgd_index addr) @ (pmd_t npt)) # (pud_index addr) ==\n (((pud_index addr) @ ((pgd_index addr) @ (pmd_t npt))) # (pmd_index addr) == false))}\n {pt_pgd_next: pgd_next'} {pt_pud_next: pud_next'}\n in\n (false, npt')\n end\n else (true, npt)\n else\n let gfn := addr / PAGE_SIZE in\n let pfn := (phys_page pte) / PAGE_SIZE in\n match gfn @ (pt npt) with\n | (pfn0, level0, pte0) =>\n if level0 =? 2 then (true, npt)\n else\n let pgd_next' := (if (pgd_index addr) @ (pgd_t npt) then (pt_pgd_next npt) else (pt_pgd_next npt) + PAGE_SIZE) in\n let pud_next' := (if (pud_index addr) @ ((pgd_index addr) @ (pud_t npt))\n then (pt_pud_next npt) else (pt_pud_next npt) + PAGE_SIZE) in\n let pmd_next' := (if (pmd_index addr) @ ((pud_index addr) @ ((pgd_index addr) @ (pmd_t npt)))\n then (pt_pmd_next npt) else (pt_pmd_next npt) + PAGE_SIZE) in\n if (pgd_next' <=? pud_start vmid) && (pud_next' <=? pmd_start vmid) && (pmd_next' <=? pool_end vmid) then\n match local_mmap_loop_h 1 gfn pfn 3 pte (pt npt) with\n | (_, _, pt') =>\n let npt' := npt {pt: pt'}\n {pgd_t: (pgd_t npt) # (pgd_index addr) == true}\n {pud_t: (pud_t npt) # (pgd_index addr) ==\n (((pgd_index addr) @ (pud_t npt)) # (pud_index addr) == true)}\n {pmd_t: (pmd_t npt) # (pgd_index addr) ==\n (((pgd_index addr) @ (pmd_t npt)) # (pud_index addr) ==\n (((pud_index addr) @ ((pgd_index addr) @ (pmd_t npt))) # (pmd_index addr) == true))}\n {pt_pgd_next: pgd_next'} {pt_pud_next: pud_next'} {pt_pmd_next: pmd_next'}\n in\n (false, npt')\n end\n else(true, npt)\n end.\n\n Definition local_spt_map_h (cbndx: Z) (index: Z) (addr: Z) (pte: Z) (spt: SPT) :=\n let gfn := addr / PAGE_SIZE in\n let pfn := (phys_page pte) / PAGE_SIZE in\n let ttbr := SMMU_TTBR index cbndx in\n let pt := ttbr @ (spt_pt spt) in\n match gfn @ pt with\n | (pfn0, pte0) =>\n let pgd_next' := (if (stage2_pgd_index addr) @ (ttbr @ (spt_pgd_t spt)) then (spt_pgd_next spt) else (spt_pgd_next spt) + PAGE_SIZE) in\n let pmd_next' := (if (pmd_index addr) @ ((stage2_pgd_index addr) @ (ttbr @ (spt_pmd_t spt)))\n then (spt_pmd_next spt) else (spt_pmd_next spt) + PAGE_SIZE) in\n if (pgd_next' <=? SMMU_PMD_START) && (pmd_next' <=? SMMU_POOL_END) then\n let spt' := spt {spt_pt: (spt_pt spt) # ttbr == (pt # gfn == (pfn, pte))}\n {spt_pgd_t: (spt_pgd_t spt) # ttbr == ((ttbr @ (spt_pgd_t spt)) # (stage2_pgd_index addr) == true)}\n {spt_pmd_t: (spt_pmd_t spt) # ttbr ==\n ((ttbr @ (spt_pmd_t spt)) # (stage2_pgd_index addr) ==\n (((stage2_pgd_index addr) @ (ttbr @ (spt_pmd_t spt))) # (pmd_index addr) == true))}\n {spt_pgd_next: pgd_next'} {spt_pmd_next: pmd_next'}\n in\n (false, spt')\n else (true, spt)\n end.\n\n Lemma in_range_n gfn gfn0 n :\n {gfn <= gfn0 < gfn + n} + {~ gfn <= gfn0 < gfn + n}.\n Proof.\n destruct (zle gfn gfn0);\n destruct (zlt gfn0 (gfn + n));\n try omega; try (left; omega); try (right; red; intro; omega).\n Qed.\n\n Lemma local_mmap_level2:\n forall vmid addr pte npt npt',\n local_mmap_h vmid addr 2 pte npt = (false, npt') ->\n let gfn := (addr / PAGE_SIZE / PTRS_PER_PMD * PTRS_PER_PMD) in\n forall gfn0, if in_range_n gfn gfn0 512 then gfn0 @ (pt npt') = (phys_page pte / PAGE_SIZE + gfn0 - gfn, 2, pte)\n else gfn0 @ (pt npt') = gfn0 @ (pt npt).\n Proof.\n intros. unfold local_mmap_h in H. simpl_bool_eq.\n repeat simpl_hyp H; inv H. simpl.\n assert(Hloop: forall n gfn pfn level pte npt gfn' pfn' npt' (Hloop: local_mmap_loop_h n gfn pfn level pte npt = (gfn', pfn', npt')),\n gfn' = gfn + (Z.of_nat n) /\\ pfn' = pfn + (Z.of_nat n) /\\\n forall gfn0, if in_range_n gfn gfn0 (Z.of_nat n) then gfn0 @ npt' = (pfn + gfn0 - gfn, level, pte)\n else gfn0 @ npt' = gfn0 @ npt).\n { clear C0. induction n. intros. simpl in *. inv Hloop. split_and; try omega.\n intros. destruct in_range_n. omega. reflexivity.\n intros. simpl in Hloop. repeat simpl_hyp Hloop; inversion Hloop.\n rewrite Nat2Z.inj_succ, succ_plus_1. apply IHn in C0. destruct C0 as (? & ? & ?).\n split_and; try omega. intros. pose proof (H4 gfn2). repeat destruct in_range_n; try omega.\n assert_gso. omega. rewrite (ZMap.gso _ _ Hneq). assumption.\n assert(gfn2 = z1) by omega. rewrite H6. rewrite ZMap.gss.\n assert(z2 = pfn + z1 - gfn1) by omega. rewrite H7. reflexivity.\n assert(gfn2 <> z1) by omega. rewrite (ZMap.gso _ _ H6). assumption. }\n apply Hloop in C0. destruct C0 as (? & ? & ?). apply H1.\n Qed.\n\n Lemma local_mmap_level3:\n forall vmid addr pte npt npt',\n local_mmap_h vmid addr 3 pte npt = (false, npt') ->\n (pt npt') = (pt npt) # (addr / PAGE_SIZE) == (phys_page pte / PAGE_SIZE, 3, pte).\n Proof.\n intros. unfold local_mmap_h in H. replace (3 =? 2) with false in H by reflexivity.\n repeat simpl_hyp H; try inv H. simpl in C3. inv C3. reflexivity.\n Qed.\n\n Lemma local_spt_map_pt:\n forall cbndx index addr pte spt spt',\n local_spt_map_h cbndx index addr pte spt = (false, spt') ->\n (spt_pt spt') = (spt_pt spt) # (SMMU_TTBR index cbndx) == (((SMMU_TTBR index cbndx) @ (spt_pt spt)) # (addr / PAGE_SIZE) == (phys_page pte / PAGE_SIZE, pte)).\n Proof.\n intros. unfold local_spt_map_h in H.\n repeat simpl_hyp H; try inv H. reflexivity.\n Qed.\n\n Opaque local_mmap_h local_spt_map_h.\n\nEnd HighPTSpec.\n\nSection ConcurrentSpec.\n\n Definition local_map_host addr sdt :=\n let ptid := NPT_ID in\n let pfn := addr / PAGE_SIZE in\n let page := pfn @ (s2page sdt) in\n if (s2_owner page =? INVALID) || (s2_owner page =? HOSTVISOR) || (s2_count page >? 0) then\n let pte := (if s2_owner page =? INVALID then Z.lor (pfn * PAGE_SIZE) (Z.lor PAGE_S2_DEVICE S2_RDWR)\n else Z.lor (pfn * PAGE_SIZE) PAGE_S2_KERNEL) in\n match local_mmap_h HOSTVISOR addr 3 pte (HOSTVISOR @ (npts sdt)) with\n | (halt', npt') =>\n if halt' then\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'} {hlock: ((hlock sdt) # S2PAGE_ID == false) # ptid == false}, true,\n Some (s2page sdt), Some npt')\n else\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'}, false,\n Some (s2page sdt), Some npt')\n end\n else (sdt {hlock: (hlock sdt) # S2PAGE_ID == false}, true, Some (s2page sdt), None).\n\n Definition local_clear_vm_page vmid pfn sdt :=\n let s2p := s2page sdt in\n let fmem := flatmem sdt in\n let page := pfn @ s2p in\n let npt := HOSTVISOR @ (npts sdt) in\n if s2_owner page =? vmid then\n match pfn @ (pt npt) with\n | (pfn', level, pte) =>\n match (if pte =? 0 then (false, npt)\n else local_mmap_h HOSTVISOR (pfn * PAGE_SIZE) 3 PAGE_GUEST npt) with\n | (halt', npt') =>\n if halt' then\n (sdt {hlock: ((hlock sdt) # S2PAGE_ID == false) # NPT_ID == false} {npts: (npts sdt) # HOSTVISOR == npt'},\n true, Some s2p, Some npt', None)\n else\n let page' := mkS2Page HOSTVISOR 0 (pfn + SMMU_HOST_OFFSET) in\n let s2p' := s2p # pfn == page' in\n let fmem' := fmem # pfn == 0 in\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'} {flatmem: fmem'},\n false, Some s2p', Some npt', Some fmem')\n end\n end\n else\n (sdt, false, Some s2p, None, None).\n\n Definition local_assign_pfn_to_vm vmid gfn pfn (dorc: Z -> Z) logn sdt :=\n let s2p := s2page sdt in\n let npt := HOSTVISOR @ (npts sdt) in\n let fmem := flatmem sdt in\n let page := pfn @ s2p in\n if s2_owner page =? HOSTVISOR then\n if s2_count page =? 0 then\n let s2p' := s2p # pfn == (mkS2Page vmid 0 gfn) in\n let fmem' := fmem # pfn == (dorc logn) in\n match pfn @ (pt npt) with\n | (pfn', level, pte) =>\n match (if pte =? 0 then (false, npt)\n else local_mmap_h HOSTVISOR (pfn * PAGE_SIZE) 3 PAGE_GUEST npt) with\n | (halt', npt') =>\n if halt' then\n (sdt {hlock: ((hlock sdt) # S2PAGE_ID == false) # NPT_ID == false} {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'},\n true, logn, Some s2p', Some npt', None)\n else\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'} {flatmem: fmem'},\n false, logn + 1, Some s2p', Some npt', Some fmem')\n end\n end\n else\n (sdt {hlock: (hlock sdt) # S2PAGE_ID == false}, true, logn, Some s2p, None, None)\n else\n if (s2_owner page =? vmid) && ((s2_gfn page =? INVALID64) || (gfn =? s2_gfn page)) then\n let page' := page {s2_count: if s2_count page =? INVALID then 0 else s2_count page}\n {s2_gfn: if s2_gfn page =? INVALID64 then gfn else s2_gfn page}\n in\n let s2p' := s2p # pfn == page in\n (sdt {s2page: s2p'}, false, logn, Some s2p', None, None)\n else\n (sdt {hlock: (hlock sdt) # S2PAGE_ID == false}, true, logn, Some s2p, None, None).\n\n Definition local_map_pfn_vm vmid addr pte level sdt :=\n let npt := vmid @ (npts sdt) in\n let paddr := phys_page pte in\n let perm := PAGE_S2_KERNEL in\n let pte' := (if level =? 2 then Z.land (Z.lor paddr perm) NOT_PMD_TABLE_BIT else Z.lor paddr perm) in\n let level' := (if level =? 2 then 2 else 3) in\n let (halt', npt') := local_mmap_h vmid addr level' pte' npt in\n if halt' then\n (sdt {hlock: (hlock sdt) # (NPT_ID + vmid) == false} {npts: (npts sdt) # vmid == npt'}, true, Some npt')\n else\n (sdt {npts: (npts sdt) # vmid == npt'}, false, Some npt').\n\n Definition local_map_io vmid gpa pa sdt :=\n let info := vmid @ (vminfos sdt) in\n let state := vm_state (VS info) in\n if state =? READY then\n let s2p := s2page sdt in\n let npt := vmid @ (npts sdt) in\n let gfn := gpa / PAGE_SIZE in\n let pfn := pa / PAGE_SIZE in\n let pte := Z.lor (phys_page pa) (Z.lor PAGE_S2_DEVICE S2_RDWR) in\n let page := pfn @ s2p in\n if s2_owner page =? INVALID then\n let (halt', npt') := local_mmap_h vmid gpa 3 pte npt in\n if halt' then\n (sdt {hlock: (((hlock sdt) # (INFO_ID + vmid) == false) # S2PAGE_ID == false) # (NPT_ID + vmid) == false} {npts: (npts sdt) # vmid == npt'},\n true, Some info, Some s2p, Some npt')\n else\n (sdt {npts: (npts sdt) # vmid == npt'}, false, Some info, Some s2p, Some npt')\n else\n (sdt, false, Some info, Some s2p, None)\n else\n (sdt {hlock: (hlock sdt) # (INFO_ID + vmid) == false}, true, Some info, None, None).\n\n Definition local_grant_vm_page vmid pfn sdt :=\n let s2p := s2page sdt in\n let page := pfn @ s2p in\n let s2p' := (if (s2_owner page =? vmid) && (s2_count page Z) logn sdt :=\n let s2p := s2page sdt in\n let npt := HOSTVISOR @ (npts sdt) in\n let fmem := flatmem sdt in\n let page := pfn @ s2p in\n if (s2_owner page =? vmid) && (s2_count page >? 0) then\n let s2p' := s2p # pfn == (page {s2_count: (s2_count page) - 1}) in\n if s2_count page =? 1 then\n let fmem' := fmem # pfn == (dorc logn) in\n match pfn @ (pt npt) with\n | (pfn', level, pte) =>\n match (if pte =? 0 then (false, npt)\n else local_mmap_h HOSTVISOR (pfn * PAGE_SIZE) 3 PAGE_GUEST npt) with\n | (halt', npt') =>\n if halt' then\n (sdt {hlock: ((hlock sdt) # S2PAGE_ID == false) # NPT_ID == false} {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'},\n true, logn, Some s2p', Some npt', None)\n else\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'} {flatmem: fmem'},\n false, logn + 1, Some s2p', Some npt', Some fmem')\n end\n end\n else\n (sdt {s2page: s2p'}, false, logn, Some s2p', None, None)\n else\n (sdt, false, logn, Some s2p, None, None).\n\n Definition local_set_vcpu_active vmid vcpuid sdt :=\n let info := vmid @ (vminfos sdt) in\n match vm_state (VS info), vcpuid @ (vm_vcpu_state (VS info)) with\n | vms, vcpus =>\n if (vms =? VERIFIED) && (vcpus =? READY) then\n let info' := info {vm_vcpu_state: (vm_vcpu_state (VS info)) # vcpuid == ACTIVE} in\n (sdt {vminfos: (vminfos sdt) # vmid == info'}, false, Some info')\n else\n (sdt, true, Some info)\n end.\n\n Definition local_set_vcpu_inactive vmid vcpuid sdt :=\n let info := vmid @ (vminfos sdt) in\n let vcpus := vcpuid @ (vm_vcpu_state (VS info)) in\n if vcpus =? ACTIVE then\n let info' := info {vm_vcpu_state: (vm_vcpu_state (VS info)) # vcpuid == READY} in\n (sdt {vminfos: (vminfos sdt) # vmid == info'}, false, Some info')\n else\n (sdt, true, Some info).\n\n Definition local_set_vm_poweroff vmid sdt :=\n let info := vmid @ (vminfos sdt) in\n let info' := info {vm_state: POWEROFF} in\n (sdt {vminfos: (vminfos sdt) # vmid == info'}, Some info').\n\n Definition local_register_vcpu vmid vcpuid sdt :=\n let info := vmid @ (vminfos sdt) in\n match vm_state (VS info), vcpuid @ (vm_vcpu_state (VS info)) with\n | vms, vcpus =>\n if (vms =? READY) && (vcpus =? UNUSED) then\n let vcpu := shared_vcpu vmid vcpuid in\n let info' := info {vm_vcpu: (vm_vcpu (VS info)) # vcpuid == vcpu} {vm_vcpu_state: (vm_vcpu_state (VS info)) # vcpuid == READY} in\n (sdt {vminfos: (vminfos sdt) # vmid == info'}, false, Some info')\n else\n (sdt, true, Some info)\n end.\n\n Definition local_gen_vmid sdt :=\n let vmid := next_vmid (core_data sdt) in\n if vmid \n let pgnum := (size + 4095) / PAGE_SIZE in\n let target := remap + mapped * PAGE_SIZE in\n if mapped \n match (if pte =? 0 then (false, npt)\n else local_mmap_h HOSTVISOR (pfn * PAGE_SIZE) 3 PAGE_GUEST npt) with\n | (halt', npt') =>\n if halt' then\n (sdt {hlock: ((((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false) # S2PAGE_ID == false) # NPT_ID == false}\n {npts: (npts sdt) # HOSTVISOR == npt'},\n true, Some smmu, Some info, Some s2p, Some npt')\n else\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'}, false, Some smmu, Some info, Some s2p', Some npt')\n end\n end\n else\n (sdt {hlock: (((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false) # S2PAGE_ID == false}, true, Some smmu, Some info, Some s2p, None)\n else\n if s2_owner page =? vmid then\n (sdt, false, Some smmu, Some info, Some s2p, None)\n else\n (sdt {hlock: (((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false) # S2PAGE_ID == false}, true, Some smmu, Some info, Some s2p, None)\n else\n (sdt, false, Some smmu, Some info, None, None).\n\n Definition local_smmu_map_page cbndx index iova pte sdt :=\n let smmu := smmu_vmid sdt in\n let vmid := (smmu_id index cbndx) @ smmu in\n let info := vmid @ (vminfos sdt) in\n let s2p := s2page sdt in\n let spt := spts sdt in\n if vmid =? INVALID then\n (sdt, false, Some smmu, None, None, None)\n else\n let state := vm_state (VS info) in\n if is_vm vmid && (state =? VERIFIED) then\n (sdt {hlock: ((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false}, true, Some smmu, Some info, None, None)\n else\n let pfn := phys_page pte / PAGE_SIZE in\n let gfn := iova / PAGE_SIZE in\n let page := pfn @ s2p in\n if (vmid =? s2_owner page) && (gfn =? s2_gfn page) then\n match local_spt_map_h cbndx index iova pte spt with\n | (halt', spt') =>\n if halt' then\n (sdt {hlock: ((((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false) # S2PAGE_ID == false) # SPT_ID == false}\n {spts: spt'}, true, Some smmu, Some info, Some s2p, Some spt')\n else\n let s2p' := (if (s2_owner page =? HOSTVISOR) && (s2_count page =? VERIFIED) then\n (sdt {hlock: ((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false}, true, Some smmu, Some info, None, None)\n else\n let ttbr := SMMU_TTBR index cbndx in\n let pt := ttbr @ (spt_pt spt) in\n let gfn := iova / PAGE_SIZE in\n let (pfn, pte) := gfn @ pt in\n let (halt', spt') := (if pte =? 0 then (false, spt) else local_spt_map_h cbndx index iova 0 spt) in\n if halt' then\n (sdt {hlock: ((((hlock sdt) # SMMU_ID == false) # (INFO_ID + vmid) == false) # S2PAGE_ID == false) # SPT_ID == false}\n {spts: spt'}, true, Some smmu, Some info, Some s2p, Some spt')\n else\n let pfn0 := phys_page pte / PAGE_SIZE in\n let page := pfn0 @ s2p in\n let s2p' := (if (s2_owner page =? HOSTVISOR) && (s2_count page >? 0)\n then s2p # pfn0 == (page {s2_count: (s2_count page) - 1}) else s2p) in\n (sdt {s2page: s2p'} {spts: spt'}, false, Some smmu, Some info, Some s2p', Some spt').\n\n Definition local_load_encryted_vcpu vmid vcpuid cregs cstates dorc logn sdt :=\n let info := vmid @ (vminfos sdt) in\n let vms := vm_state (VS info) in\n let vcpus := vcpuid @ (vm_vcpu_state (VS info)) in\n if (vms =? READY) && (vcpus =? READY) then\n match decrypt_gp_regs_specx cregs cstates dorc logn with\n | (cregs', cstates', logn') =>\n match decrypt_sys_regs_specx cregs' cstates' dorc logn' with\n | (cregs'', cstates'', logn'') =>\n let info' := info {vm_inc_exe: 1} in\n (sdt {vminfos: (vminfos sdt) # vmid == info'}, false, cregs'', cstates'', logn'', Some info')\n end\n end\n else\n (sdt {hlock: (hlock sdt) # (INFO_ID + vmid) == false}, true, cregs, cstates, logn, Some info).\n\n Definition local_save_encrypt_buf vmid inbuf outbuf dorc logn sdt :=\n let inpfn := inbuf / PAGE_SIZE in\n let outpfn := outbuf / PAGE_SIZE in\n let inpage := inpfn @ (s2page sdt) in\n let outpage := outpfn @ (s2page sdt) in\n if (s2_owner inpage =? vmid) && (s2_owner outpage =? HOSTVISOR) then\n let fmem' := (flatmem sdt) # outpfn == (dorc logn) in\n (sdt {flatmem: fmem'}, false, logn + 1, Some (s2page sdt), Some fmem')\n else\n (sdt {hlock: (hlock sdt) # S2PAGE_ID == false}, true, logn, Some (s2page sdt), None).\n\n Definition local_load_decrypt_buf vmid inbuf dorc logn sdt :=\n let pfn := inbuf / PAGE_SIZE in\n let info := vmid @ (vminfos sdt) in\n let s2p := s2page sdt in\n let npt := HOSTVISOR @ (npts sdt) in\n let vms := vm_state (VS info) in\n let page := pfn @ s2p in\n if vms =? READY then\n if (s2_owner page =? HOSTVISOR) && (s2_count page =? 0) then\n match pfn @ (pt npt) with\n | (pfn', level, pte) =>\n match (if pte =? 0 then (false, npt)\n else local_mmap_h HOSTVISOR (pfn * PAGE_SIZE) 3 PAGE_GUEST npt) with\n | (halt', npt') =>\n if halt' then\n (sdt {hlock: (((hlock sdt) # (INFO_ID + vmid) == false) # S2PAGE_ID == false) # NPT_ID == false}\n {npts: (npts sdt) # HOSTVISOR == npt'}, true, logn, Some info, Some s2p, Some npt', None)\n else\n let page' := mkS2Page vmid 0 INVALID64 in\n let s2p' := s2p # pfn == page' in\n let fmem' := (flatmem sdt) # pfn == (dorc logn) in\n (sdt {npts: (npts sdt) # HOSTVISOR == npt'} {s2page: s2p'} {flatmem: fmem'},\n false, logn + 1, Some info, Some s2p', Some npt', Some fmem')\n end\n end\n else\n (sdt {hlock: ((hlock sdt) # (INFO_ID + vmid) == false) # S2PAGE_ID == false},\n true, logn, Some info, Some s2p, None, None)\n else\n (sdt {hlock: (hlock sdt) # (INFO_ID + vmid) == false}, true, logn, Some info, None, None, None).\n\n Fixpoint CalStateH (slog: SingleLog) (sdt: Shared) :=\n match slog with\n | nil => sdt\n | (SEVENT _ e) :: slog' =>\n let sdt' := CalStateH slog' sdt in\n match e with\n | OMAP_HOST addr =>\n match local_map_host addr sdt with\n | (sdt', _, _, _) => sdt'\n end\n | _ => sdt\n end\n end.\n\n Definition query_oracle adt :=\n adt {slog: ((soracle adt) (curid adt) (slog adt)) ++ (slog adt)} {shared: CalStateH ((soracle adt) (curid adt) (slog adt)) (shared adt)}.\n\n Opaque query_oracle.\n\nEnd ConcurrentSpec.\n\nSection AuxSpec.\n\n Fixpoint reset_sys_regs_loopx n i vcpuid cregs cstates (dorc: Z -> Z) logn :=\n match n with\n | O => (cregs, cstates, logn, i)\n | S n' =>\n match reset_sys_regs_loopx n' i vcpuid cregs cstates dorc logn with\n | (cregs', cstates', logn', i') =>\n if i' =? MPIDR_EL1 then\n let mpidr := (Z.land vcpuid 15) + (Z.land (vcpuid / 16) 255) * 256 +\n (Z.land (vcpuid / 4096) 255) * 65536 in\n match set_shadow_ctxt_specx i' (mpidr + 2147483648) cregs' cstates' with\n | (cregs'', cstates'') => (cregs'', cstates'', logn', i' + 1)\n end\n else\n if i' =? ACTLR_EL1 then\n let val := dorc logn' in\n match set_shadow_ctxt_specx i' val cregs' cstates' with\n | (cregs'', cstates'') => (cregs'', cstates'', logn' + 1, i' + 1)\n end\n else\n let val := reg_desc i' in\n match set_shadow_ctxt_specx i' val cregs' cstates' with\n | (cregs'', cstates'') => (cregs'', cstates'', logn', i' + 1)\n end\n end\n end.\n\n Definition reset_sys_regs_specx vcpuid cregs cstates dorc logn :=\n match reset_sys_regs_loopx (Z.to_nat SHADOW_SYS_REGS_SIZE) SYSREGS_START vcpuid cregs cstates dorc logn with\n | (cregs', cstates', logn', i') => (cregs', cstates', logn')\n end.\n\n Fixpoint sync_dirty_to_shadow_loopx (n: nat) (i: Z) dirty cregs cstates dorc logn :=\n match n with\n | O => (i, cregs, cstates, logn)\n | S n' =>\n match sync_dirty_to_shadow_loopx n' i dirty cregs cstates dorc logn with\n | (i', cregs', cstates', logn') =>\n if (Z.land dirty (Z.shiftl 1 i')) =? 0 then\n (i' + 1, cregs', cstates', logn')\n else\n let reg := dorc logn in\n match set_shadow_ctxt_specx i' reg cregs' cstates' with\n | (cregs'', cstates'') => (i' + 1, cregs'', cstates'', logn' + 1)\n end\n end\n end.\n\n Definition sync_dirty_to_shadow_specx (vmid: Z) (dirty: Z) (cregs: CtxtRegs) (cstates: CtxtStates) (logn: Z) (dorc: Z -> Z) :=\n match sync_dirty_to_shadow_loopx 31%nat 0 dirty cregs cstates dorc logn with\n | (i', cregs', cstates', logn') => (cregs', cstates', logn')\n end.\n\n Definition update_exception_gp_regs_specx (cregs: CtxtRegs) (cstates: CtxtStates) :=\n let pstate0 := pstate cstates in\n let pc0 := pc cstates in\n let new_pc := (exception_vector (VZ64 pstate0)) in\n (cregs {elr_el1: pc0}, cstates {spsr_0: pstate0} {esr_el1: ESR_ELx_EC_UNKNOWN} {pstate: PSTATE_FAULT_BITS_64}).\n\n Fixpoint prot_and_map_vm_loop_h n vmid gfn pfn adt :=\n match n with\n | O => Some (gfn, pfn, adt)\n | S n' =>\n match prot_and_map_vm_loop_h n' vmid gfn pfn adt with\n | Some (gfn', pfn', adt') =>\n if halt adt' then Some (gfn' + 1, pfn' + 1, adt') else\n let adt0 := query_oracle adt' in\n let log' := SEVENT (curid adt0) (OASSIGN_VM vmid gfn pfn (doracle adt0) (vmid @ (data_log adt0))) :: (slog adt0) in\n rely S2PAGE_ID @ (hlock (shared adt0)); rely NPT_ID @ (hlock (shared adt0));\n match local_assign_pfn_to_vm vmid gfn' pfn' ((doracle adt0) vmid) (vmid @ (data_log adt0)) (shared adt0) with\n | (sdt', halt', logn', _, _, _) =>\n Some (gfn' + 1, pfn' + 1, adt0 {shared: sdt'} {halt: halt'} {slog: log'} {data_log: (data_log adt) # vmid == logn'})\n end\n | _ => None\n end\n end.\n\n Definition prot_and_map_vm_s2pt_spec_h vmid addr pte level adt :=\n if halt adt then Some adt else\n let target := phys_page pte in\n let pfn := target / PAGE_SIZE in\n let gfn := addr / PAGE_SIZE in\n if level =? 2 then\n let gfn' := gfn / PTRS_PER_PMD * PTRS_PER_PMD in\n let num := PMD_PAGE_NUM in\n match prot_and_map_vm_loop_h (Z.to_nat num) vmid gfn' pfn adt with\n | Some (gfn'', pfn'', adt') =>\n if halt adt' then Some adt' else\n let adt0 := query_oracle adt' in\n let log' := SEVENT (curid adt0) (OMAP_VM vmid addr pte 2) :: (slog adt0) in\n rely (NPT_ID + vmid) @ (hlock (shared adt0));\n match local_map_pfn_vm vmid addr pte 2 (shared adt0) with\n | (sdt', halt', _) =>\n Some adt0 {halt: halt'} {shared: sdt'} {slog: log'}\n end\n | _ => None\n end\n else\n let adt0 := query_oracle adt in\n let log' := SEVENT (curid adt0) (OASSIGN_VM vmid gfn pfn (doracle adt0) (vmid @ (data_log adt0))) :: (slog adt0) in\n rely S2PAGE_ID @ (hlock (shared adt0)); rely NPT_ID @ (hlock (shared adt0));\n match local_assign_pfn_to_vm vmid gfn pfn ((doracle adt0) vmid) (vmid @ (data_log adt0)) (shared adt0) with\n | (sdt', halt', logn', _, _, _) =>\n let adt'' := adt0 {shared: sdt'} {halt: halt'} {slog: log'} {data_log: (data_log adt) # vmid == logn'} in\n let adt0 := query_oracle adt'' in\n let log' := SEVENT (curid adt0) (OMAP_VM vmid addr pte 3) :: (slog adt0) in\n rely (NPT_ID + vmid) @ (hlock (shared adt0));\n match local_map_pfn_vm vmid addr pte 3 (shared adt0) with\n | (sdt', halt', _) =>\n Some adt0 {halt: halt'} {shared: sdt'} {slog: log'}\n end\n end.\n\n Fixpoint clear_vm_loop_h n pfn vmid adt :=\n match n with\n | O => Some (pfn, adt)\n | S n' =>\n match clear_vm_loop_h n' pfn vmid adt with\n | Some (pfn', adt') =>\n if halt adt' then Some (pfn' + 1, adt') else\n let adt1 := query_oracle adt' in\n rely S2PAGE_ID @ (hlock (shared adt1)); rely NPT_ID @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OCLEAR_VM vmid pfn') :: (slog adt1) in\n match local_clear_vm_page vmid pfn' (shared adt1) with\n | (sdt', halt', _, _, _) =>\n Some (pfn' + 1, adt1 {shared: sdt'} {halt: halt'} {slog: log'})\n end\n | _ => None\n end\n end.\n\n Fixpoint unmap_and_load_loop_h n vmid start target remap adt :=\n match n with\n | O => Some (start, target, remap, adt)\n | S n' =>\n match unmap_and_load_loop_h n' vmid start target remap adt with\n | Some (start', target', remap', adt') =>\n if halt adt' then\n Some (start' + PMD_SIZE, start' + PMD_SIZE, remap' + (start' + PMD_SIZE - target'), adt')\n else\n let adt0 := query_oracle adt' in\n rely (NPT_ID + COREVISOR) @ (hlock (shared adt0));\n let adt'' := adt0 {slog: SEVENT (curid adt0) (OPT_GET COREVISOR) :: (slog adt0)} in\n match (remap' / PAGE_SIZE) @ (pt (COREVISOR @ (npts (shared adt'')))) with\n | (_, _, pte) =>\n let pfn := phys_page pte / PMD_SIZE * PTRS_PER_PMD in\n let gfn := start' / PAGE_SIZE in\n if pte =? 0 then\n Some (start' + PMD_SIZE, start' + PMD_SIZE, remap' + (start' + PMD_SIZE - target'), adt'' {halt: true})\n else\n match prot_and_map_vm_s2pt_spec_h vmid (gfn * PAGE_SIZE) (pfn * PAGE_SIZE) 2 adt'' with\n | Some adt1 =>\n Some (start' + PMD_SIZE, start' + PMD_SIZE, remap' + (start' + PMD_SIZE - target'), adt1)\n | _ => None\n end\n end\n | _ => None\n end\n end.\n\n Fixpoint verify_and_load_loop_h n vmid load_idx adt :=\n match n with\n | O => Some (load_idx, adt)\n | S n' =>\n match verify_and_load_loop_h n' vmid load_idx adt with\n | Some (idx', adt') =>\n let info := vmid @ (vminfos (shared adt')) in\n let load_addr := idx' @ (vm_load_addr (VB info)) in\n let remap_addr := idx' @ (vm_remap_addr (VB info)) in\n let mapped := idx' @ (vm_mapped_pages (VB info)) in\n let start := load_addr / PMD_SIZE * PMD_SIZE in\n let end' := load_addr + mapped * PAGE_SIZE in\n let num := (end' - start + 2097151) / PMD_SIZE in\n match unmap_and_load_loop_h (Z.to_nat num) vmid start load_addr remap_addr adt' with\n | Some (start', target', remap', adt'') =>\n Some (load_idx + 1, adt'')\n | _ => None\n end\n | _ => None\n end\n end.\n\n Fixpoint kvm_phys_addr_ioremap_loop_h n vmid gpa pa adt :=\n match n with\n | O => Some (gpa, pa, adt)\n | S n' =>\n match kvm_phys_addr_ioremap_loop_h n' vmid gpa pa adt with\n | Some (gpa', pa', adt') =>\n if halt adt' then\n Some (gpa' + PAGE_SIZE, pa' + PAGE_SIZE, adt')\n else\n let adt1 := query_oracle adt' in\n rely (INFO_ID + vmid) @ (hlock (shared adt1)); rely S2PAGE_ID @ (hlock (shared adt1));\n rely (NPT_ID + vmid) @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OMAP_IO vmid gpa' pa') :: (slog adt1) in\n match local_map_io vmid gpa' pa' (shared adt1) with\n | (sdt', halt', _, _, _) =>\n Some (gpa' + PAGE_SIZE, pa' + PAGE_SIZE, adt1 {shared: sdt'} {halt: halt'} {slog: log'})\n end\n | _ => None\n end\n end.\n\n Fixpoint is_smmu_range_loop_h n addr i res conf :=\n match n with\n | O => (i, res)\n | S n' =>\n match is_smmu_range_loop_h n' addr i res conf with\n | (i', res') =>\n if (i' @ (smmu_phys_base conf) <=? addr) && (addr \n (false, logn + 1, cregs', cstates', rcregs {esr_el2: (elr_el2 rcregs) + 4})\n end\n else if len =? 4 then\n match set_shadow_ctxt_specx rt (Z.land data INVALID) cregs cstates with\n | (cregs', cstates') =>\n (false, logn + 1, cregs', cstates', rcregs {esr_el2: (elr_el2 rcregs) + 4})\n end\n else (true, logn, cregs, cstates, rcregs)\n else\n let data := get_shadow_ctxt_specx rt cregs cstates in\n let ret_state := (if len =? 8 then (false, logn, cregs, cstates, rcregs {esr_el2: (elr_el2 rcregs) + 4})\n else if len =? 4 then (false, logn, cregs, cstates, rcregs {esr_el2: (elr_el2 rcregs) + 4})\n else (true, logn, cregs, cstates, rcregs)) in\n let offset := Z.land fault_ipa SMMU_OFFSET_MASK in\n if offset =? 0) && (offset <=? ARM_SMMU_GR1_BASE)\n then\n if offset =? ARM_SMMU_GR0_sCR0\n then let smmu_enable := Z.land (Z.shiftr data sCR0_SMCFCFG_SHIFT) 1 in if smmu_enable =? 0 then 0 else 1\n else if offset =? ARM_SMMU_GR0_sCR2 then if Z.land data 255 =? 0 then 1 else 0 else 1\n else\n if (offset >=? ARM_SMMU_GR1_BASE) && (offset (idx, ret)\n | S n' =>\n match search_load_info_loop_h n' idx addr ret binfo with\n | (idx', ret') =>\n match idx' @ (vm_load_addr binfo), idx' @ (vm_load_size binfo), idx' @ (vm_remap_addr binfo) with\n | base, size, remap =>\n if (addr >=? base) && (addr Some (addr, adt)\n | S n' =>\n match grant_stage2_loop n' vmid addr adt with\n | Some (addr', adt') =>\n let gfn' := addr' / PAGE_SIZE in\n let adt0 := query_oracle adt' in\n rely (NPT_ID + vmid) @ (hlock (shared adt0));\n let adt' := adt0 {slog: SEVENT (curid adt0) (OPT_GET vmid) :: (slog adt0)} in\n match gfn' @ (pt (vmid @ (npts (shared adt')))) with\n | (_, _, pte) =>\n let adt1 := query_oracle adt' in\n rely (NPT_ID + vmid) @ (hlock (shared adt1));\n let adt'' := adt1 {slog: SEVENT (curid adt1) (OPT_GET vmid) :: (slog adt1)} in\n match ZMap.get gfn' (pt (vmid @ (npts (shared adt'')))) with\n | (_, level, _) =>\n let pfn := phys_page pte / PAGE_SIZE in\n if pfn =? 0 then Some (addr' + PAGE_SIZE, adt'')\n else\n let pfn' := (if level =? 2 then pfn + Z.land gfn' 511 else pfn) in\n let adt2 := query_oracle adt'' in\n rely S2PAGE_ID @ (hlock (shared adt1));\n match local_grant_vm_page vmid pfn (shared adt2) with\n | (sdt', _) =>\n Some (addr' + PAGE_SIZE, adt2 {shared: sdt'} {slog: SEVENT (curid adt2) (OGRANT vmid pfn) :: (slog adt2)})\n end\n end\n end\n | _ => None\n end\n end.\n\n Fixpoint revoke_stage2_loop (n: nat) (vmid: Z) (addr: Z) (adt: RData) :=\n match n with\n | O => Some (addr, adt)\n | S n' =>\n match revoke_stage2_loop n' vmid addr adt with\n | Some (addr', adt') =>\n let gfn' := addr' / PAGE_SIZE in\n let adt0 := query_oracle adt' in\n rely (NPT_ID + vmid) @ (hlock (shared adt0));\n let adt' := adt0 {slog: SEVENT (curid adt0) (OPT_GET vmid) :: (slog adt0)} in\n match gfn' @ (pt (vmid @ (npts (shared adt')))) with\n | (_, _, pte) =>\n let adt1 := query_oracle adt' in\n rely (NPT_ID + vmid) @ (hlock (shared adt1));\n let adt'' := adt1 {slog: SEVENT (curid adt1) (OPT_GET vmid) :: (slog adt1)} in\n match ZMap.get gfn' (pt (vmid @ (npts (shared adt'')))) with\n | (_, level, _) =>\n let pfn := phys_page pte / PAGE_SIZE in\n if pfn =? 0 then Some (addr' + PAGE_SIZE, adt'')\n else\n let pfn' := (if level =? 2 then pfn + Z.land gfn' 511 else pfn) in\n let adt2 := query_oracle adt'' in\n rely S2PAGE_ID @ (hlock (shared adt1)); rely NPT_ID @ (hlock (shared adt1));\n let log' := SEVENT (curid adt2) (OREVOKE vmid pfn (doracle adt2) (vmid @ (data_log adt2))) :: (slog adt2) in\n match local_revoke_vm_page vmid pfn ((doracle adt2) vmid) (vmid @ (data_log adt2)) (shared adt2) with\n | (sdt', halt', logn', _, _, _) =>\n Some (addr' + PAGE_SIZE, adt2 {halt: halt'} {shared: sdt'} {slog: log'} {data_log: (data_log adt2) # vmid == logn'})\n end\n end\n end\n | _ => None\n end\n end.\n\n Definition vm_exit_dispatcher_spec_h (vmid vcpuid: Z) (adt: RData) :=\n let ctxt := (ctxt_id vmid vcpuid) @ (shadow_ctxts adt) in\n let cregs := ctxt_regs ctxt in\n let esrel2 := esr_el2 cregs in\n let exit_type := (esrel2 / 67108864) mod 64 in\n if exit_type =? ESR_ELx_EC_SYS64 then\n let pc := elr_el2 (ctxt_regs (regs adt)) in\n Some (adt {regs : (regs adt) {ctxt_regs : (ctxt_regs (regs adt)) {esr_el2 : pc + 4}}}, 0)\n else\n if exit_type =? ESR_ELx_EC_HVC64 then\n let arg := x0 cregs in\n let addr := x2 cregs in\n let size := x3 cregs in\n if arg =? HVC_KVM_SET_DESC_PFN then\n let len := (size + 4095) / PAGE_SIZE in\n match grant_stage2_loop (Z.to_nat len) vmid addr adt with\n | Some (_, adt') => Some (adt', 0)\n | _ => None\n end\n else\n if arg =? HVC_KVM_UNSET_DESC_PFN then\n let len := (size + 4095) / PAGE_SIZE in\n match revoke_stage2_loop (Z.to_nat len) vmid addr adt with\n | Some (_, adt') => Some (adt', 0)\n | _ => None\n end\n else Some (adt, 1)\n else Some (adt {halt: true}, 0).\n\n Definition prep_wfx_specx (cstates: CtxtStates) :=\n cstates {dirty: DIRTY_PC_FLAG}.\n\n Definition prep_abort_specx (cregs: CtxtRegs) (cstates: CtxtStates) (logn: Z) (doc: Z -> Z) :=\n let esr := doc logn in\n let Rd := esr / 65536 mod 32 in\n let hpfar_el2 := hpfar_el2 cregs in\n let fault_ipa := (hpfar_el2 / 16) * 4096 in\n if fault_ipa Some adt0 {shared: sdt'} {slog: l'}\n end\n else Some adt.\n\n Lemma set_shadow_ctxt_dirty:\n forall index val cregs cstates cregs' cstates',\n set_shadow_ctxt_specx index val cregs cstates = (cregs', cstates') ->\n index <> DIRTY ->\n dirty cstates' = dirty cstates.\n Proof.\n intros. hsimpl_func H; try reflexivity.\n bool_rel; autounfold in *; omega.\n Qed.\n\nEnd AuxSpec.\n\nSection TrapHandlerSpec.\n\n Definition host_hvc_handler_spec (adt: RData) : option RData :=\n match (ihost adt, icore adt) with\n | (true, false) =>\n if halt adt then Some adt else\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let ctxt' := ctxt {ctxt_regs: host_to_core_specx (ctxt_regs ctxt) (ctxt_regs (regs adt))} in\n let adt' := adt {shadow_ctxts: (shadow_ctxts adt) # ctxtid == ctxt'} {icore: true} in\n let cregs' := ctxt_regs ctxt' in\n let cstates' := ctxt_states ctxt' in\n match x0 cregs', x1 cregs', x2 cregs', x3 cregs', x4 cregs', x5 cregs' with\n | arg, arg1, arg2, arg3, arg4, arg5 =>\n match (\n if arg =? HVC_TIMER_SET_CNTVOFF then\n Some adt'\n else\n if arg =? HVC_CLEAR_VM_S2_RANGE then\n if is_vm arg1 && is_paddr arg2 && is_paddr arg3 then\n let adt1 := query_oracle adt' in\n rely (NPT_ID + arg1) @ (hlock (shared adt1));\n let info := arg1 @ (vminfos (shared adt1)) in\n let adt'' := adt1 {slog: SEVENT (curid adt1) (OVM_GET vmid) :: (slog adt1)} in\n if vm_state (VS info) =? POWEROFF then\n let pfn := arg2 / PAGE_SIZE in\n let num := arg3 / PAGE_SIZE in\n match clear_vm_loop_h (Z.to_nat num) pfn arg1 adt'' with\n | Some (_, adt0) => Some adt0\n | _ => None\n end\n else Some adt''\n else Some adt' {halt: true}\n else\n if arg =? HVC_SET_BOOT_INFO then\n if is_vm arg1 && is_paddr arg2 && is_paddr arg1 && is_pfn (arg2 + arg3) then\n let adt1 := query_oracle adt' in\n rely (INFO_ID + arg1) @ (hlock (shared adt1)); rely CORE_ID @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OBOOT_INFO arg1 arg2 arg3) :: (slog adt1) in\n match local_set_boot_info arg1 arg2 arg3 (shared adt1) with\n | (sdt', halt', _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_REMAP_VM_IMAGE then\n if is_vm arg1 && is_pfn arg3 && is_load_idx arg3 then\n let adt1 := query_oracle adt' in\n rely (INFO_ID + arg1) @ (hlock (shared adt1)); rely (NPT_ID + COREVISOR) @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OREMAP_IMAGE arg1 arg2 arg3) :: (slog adt1) in\n match local_remap_vm_image arg1 arg2 arg3 (shared adt1) with\n | (sdt', halt', _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_VERIFY_VM_IMAGE then\n if is_vm arg1 then\n let adt1 := query_oracle adt' in\n rely (INFO_ID + arg1) @ (hlock (shared adt1));\n let info := arg1 @ (vminfos (shared adt1)) in\n let state := vm_state (VS info) in\n let sdt' := (shared adt1) {hlock: (hlock (shared adt1)) # (INFO_ID + vmid) == false} in\n let adt'' := adt1 {slog: SEVENT (curid adt1) (OVERIFY arg1) :: (slog adt1)} {shared: sdt'} in\n if state =? READY then\n let cnt := vm_next_load_info (VB info) in\n match verify_and_load_loop_h (Z.to_nat cnt) arg1 0 adt'' with\n | Some (_, adt0) =>\n if halt adt0 then Some adt0 else\n let info' := info {vm_state: VERIFIED} in\n let hlock' := (hlock (shared adt0)) # (INFO_ID + arg1) == true in\n Some adt0 {shared: (shared adt0) {hlock: hlock'} {vminfos: (vminfos (shared adt0)) # arg1 == info'}}\n {slog: SEVENT (curid adt0) (OVERIFY arg1) :: (slog adt0)}\n | _ => None\n end\n else Some adt'' {halt: true}\n else Some adt' {halt: true}\n else\n if arg =? HVC_SMMU_FREE_PGD then\n if is_smmu_cfg arg1 && is_smmu arg2 then\n let adt1 := query_oracle adt' in\n rely SMMU_ID @ (hlock (shared adt1)); rely (INFO_ID + vmid) @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OSMMU_FREE arg1 arg2) :: (slog adt1) in\n match local_free_smmu_pgd arg1 arg2 (shared adt1) with\n | (sdt', halt', _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_SMMU_ALLOC_PGD then\n if is_smmu_cfg arg1 && (HOSTVISOR <=? arg2) && (arg2 \n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_SMMU_LPAE_MAP then\n if is_paddr arg1 && is_paddr arg2 && (0 <=? arg3) && (arg3 \n let adt'' := adt1 {shared: sdt'} {halt: halt'} {slog: log'} in\n if halt adt'' then Some adt'' else\n let adt2 := query_oracle adt'' in\n let vmid := (smmu_id arg4 arg5) @ (smmu_vmid (shared adt2)) in\n rely SMMU_ID @ (hlock (shared adt2)); rely (INFO_ID + vmid) @ (hlock (shared adt2));\n rely SPT_ID @ (hlock (shared adt2)); rely SPT_ID @ (hlock (shared adt2));\n let log'' := SEVENT (curid adt2) (OSMMU_MAP arg4 arg5 arg1 pte) :: (slog adt2) in\n match local_smmu_map_page arg4 arg5 arg1 pte (shared adt2) with\n | (sdt'', halt'', _, _, _, _) =>\n Some adt2 {shared: sdt''} {halt: halt''} {slog: log''}\n end\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_SMMU_LPAE_IOVA_TO_PHYS then\n if is_paddr arg1 && is_smmu_cfg arg2 && is_smmu arg3 then\n let adt1 := query_oracle adt' in\n rely SPT_ID @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OSMMU_GET) :: (slog adt1) in\n let ttbr := SMMU_TTBR arg3 arg2 in\n match (arg1 / PAGE_SIZE) @ (ttbr @ (spt_pt (spts (shared adt1)))) with\n | (pfn, pte) =>\n let ret := phys_page pte + (Z.land arg1 4095) in\n Some adt1 {shadow_ctxts: (shadow_ctxts adt') # ctxtid == (ctxt' {ctxt_regs: (ctxt_regs ctxt') {x0: ret}})}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_SMMU_CLEAR then\n if is_paddr arg1 && is_smmu_cfg arg2 && is_smmu arg3 then\n let adt1 := query_oracle adt' in\n let vmid := (smmu_id arg2 arg3) @ (smmu_vmid (shared adt1)) in\n rely SMMU_ID @ (hlock (shared adt1)); rely (INFO_ID + vmid) @ (hlock (shared adt1));\n rely S2PAGE_ID @ (hlock (shared adt1)); rely SPT_ID @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OSMMU_CLEAR arg1 arg2 arg3) :: (slog adt1) in\n match local_smmu_clear arg1 arg2 arg3 (shared adt1) with\n | (sdt', halt', _, _, _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_PHYS_ADDR_IOREMAP then\n if is_vm arg1 && is_addr arg2 && is_paddr arg3 && is_paddr arg4 && is_addr (arg2 + ((arg4 + 4095) / PAGE_SIZE) * PAGE_SIZE) && \n\t\t\t is_paddr (arg3 + ((arg4 + 4095) / PAGE_SIZE) * PAGE_SIZE) && (0 <=? arg4) then\n let num := (arg4 + 4095) / PAGE_SIZE in\n match kvm_phys_addr_ioremap_loop_h (Z.to_nat num) arg1 arg2 arg3 adt' with\n | Some (_, _, adt'') => Some adt''\n | _ => None\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_REGISTER_KVM then\n let adt1 := query_oracle adt' in\n rely CORE_ID @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OGEN_VMID) :: (slog adt1) in\n let vmid := next_vmid (core_data (shared adt1)) in\n match local_gen_vmid (shared adt1) with\n | (sdt', halt', _) =>\n let adt'' := adt1 {shared: sdt'} {halt: halt'} {slog: log'} in\n if halt adt'' then Some adt'' else\n let adt2 := query_oracle adt'' in\n rely (INFO_ID + vmid) @ (hlock (shared adt2));\n let log'' := SEVENT (curid adt2) (OREG_KVM vmid) :: (slog adt2) in\n match local_register_kvm vmid (shared adt2) with\n | (sdt'', halt'', _) =>\n Some adt2 {shared: sdt''} {halt: halt''} {slog: log''}\n {shadow_ctxts: (shadow_ctxts adt') # ctxtid == (ctxt' {ctxt_regs: (ctxt_regs ctxt') {x0: vmid}})}\n end\n end\n else\n if arg =? HVC_REGISTER_VCPU then\n if is_vm arg1 && is_vcpu arg2 then\n let adt1 := query_oracle adt' in\n rely (INFO_ID + arg1) @ (hlock (shared adt1));\n let log' := SEVENT (curid adt1) (OREG_VCPU arg1 arg2) :: (slog adt1) in\n match local_register_vcpu arg1 arg2 (shared adt1) with\n | (sdt', halt', _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_ENCRYPT_BUF then\n if is_vm arg1 && is_paddr arg2 && is_paddr arg3 then\n let adt1 := query_oracle adt' in\n rely S2PAGE_ID @ (hlock (shared adt1));\n let dorc := (doracle adt1) HOSTVISOR in\n let logn := HOSTVISOR @ (data_log adt1) in\n let log' := SEVENT (curid adt1) (OSAVE_ENC_BUF arg1 arg2 arg3 dorc logn) :: (slog adt1) in\n match local_save_encrypt_buf arg1 arg2 arg3 dorc logn (shared adt1) with\n | (sdt', halt', logn', _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'} {data_log: (data_log adt1) # HOSTVISOR == logn'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_DECRYPT_BUF then\n if is_vm arg1 && is_paddr arg2 then\n let adt1 := query_oracle adt' in\n rely S2PAGE_ID @ (hlock (shared adt1)); rely (INFO_ID + arg1) @ (hlock (shared adt1));\n rely NPT_ID @ (hlock (shared adt1));\n let dorc := (doracle adt1) HOSTVISOR in\n let logn := HOSTVISOR @ (data_log adt1) in\n let log' := SEVENT (curid adt1) (OLOAD_ENC_BUF arg1 arg2 dorc logn) :: (slog adt1) in\n match local_load_decrypt_buf arg1 arg2 dorc logn (shared adt1) with\n | (sdt', halt', logn', _, _, _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'} {data_log: (data_log adt1) # HOSTVISOR == logn'}\n end\n else Some adt' {halt: true}\n else\n if arg =? HVC_SAVE_CRYPT_VCPU then\n if is_vm arg1 && is_vcpu arg2 then\n Some adt'\n else Some adt' {halt: true}\n else\n if arg =? HVC_LOAD_CRYPT_VCPU then\n if is_vm arg1 && is_vcpu arg2 then\n let adt1 := query_oracle adt' in\n rely (INFO_ID + arg1) @ (hlock (shared adt1));\n let dorc := (doracle adt1) HOSTVISOR in\n let logn := HOSTVISOR @ (data_log adt1) in\n let log' := SEVENT (curid adt1) (OLOAD_ENC_VCPU arg1 arg2 cregs' cstates' dorc logn) :: (slog adt1) in\n match local_load_encryted_vcpu arg1 arg2 cregs' cstates' dorc logn (shared adt1) with\n | (sdt', halt', cregs'', cstates'', logn', _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'} {data_log: (data_log adt1) # HOSTVISOR == logn'}\n {shadow_ctxts: (shadow_ctxts adt') # ctxtid == (ctxt' {ctxt_regs: cregs''} {ctxt_states: cstates''})}\n end\n else Some adt' {halt: true}\n else Some adt'\n )\n with\n | Some adt'' =>\n if halt adt'' then Some adt'' else\n let ctxt := ctxtid @ (shadow_ctxts adt'') in\n Some adt'' {regs: (regs adt'') {ctxt_regs: core_to_host_specx (ctxt_regs ctxt) (ctxt_regs (regs adt''))}}\n {icore: false}\n | _ => None\n end\n end\n | _ => None\n end.\n\n Definition host_npt_handler_spec (adt: RData) : option RData :=\n match (ihost adt, icore adt) with\n | (true, false) =>\n if halt adt then Some adt else\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let ctxt' := ctxt {ctxt_regs: host_to_core_specx (ctxt_regs ctxt) (ctxt_regs (regs adt))} in\n let adt' := adt {shadow_ctxts: (shadow_ctxts adt) # ctxtid == ctxt'} {icore: true} in\n let hpfar := hpfar_el2 (ctxt_regs (regs adt')) in\n let addr := Z.land hpfar HPFAR_MASK * 256 in\n if is_addr addr then\n let esr := esr_el2 (ctxt_regs (regs adt')) in\n match (\n let fault_ipa := Z.lor addr (Z.land (far_el2 (ctxt_regs (regs adt'))) 4095) in\n let len := host_dabt_get_as' esr in\n let is_write := host_dabt_is_write' esr in\n let rt := host_dabt_get_rd' esr in\n let adt0 := query_oracle adt' in\n let log' := SEVENT (curid adt) (OSMMU_GET) :: (slog adt0) in\n rely SMMU_ID @ (hlock (shared adt0));\n let conf := smmu_conf adt' in\n let num := smmu_num conf in\n let (_, res) := is_smmu_range_loop_h (Z.to_nat num) addr 0 INVALID conf in\n if res =? INVALID then\n let adt'' := adt0 {slog: log'} in\n let adt1 := query_oracle adt'' in\n let log' := SEVENT (curid adt1) (OMAP_HOST addr) :: (slog adt1) in\n rely S2PAGE_ID @ (hlock (shared adt1)); rely NPT_ID @ (hlock (shared adt1));\n match local_map_host addr (shared adt1) with\n | (sdt', halt', _, _) =>\n Some adt1 {shared: sdt'} {halt: halt'} {slog: log'}\n end\n else\n let smmu := smmu_vmid (shared adt0) in\n let logn := HOSTVISOR @ (data_log adt0) in\n match handle_host_mmio_spec_h res fault_ipa len is_write rt (ctxt_regs ctxt') (ctxt_states ctxt') (ctxt_regs (regs adt0)) ((doracle adt0) HOSTVISOR) logn smmu with\n | (halt', logn', cregs', cstates', rcregs') =>\n Some adt0 {halt: halt'} {slog: log'} {regs: (regs adt) {ctxt_regs: rcregs'}} {data_log: (data_log adt) # HOSTVISOR == logn'}\n {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt' {ctxt_regs: cregs'} {ctxt_states: cstates'})}\n end\n )\n with\n | Some adt'' =>\n if halt adt'' then Some adt'' else\n let ctxt := ctxtid @ (shadow_ctxts adt'') in\n Some adt'' {regs: (regs adt'') {ctxt_regs: core_to_host_specx (ctxt_regs ctxt) (ctxt_regs (regs adt''))}}\n {icore: false}\n | _ => None\n end\n else Some adt' {halt: true}\n | _ => None\n end.\n\n Definition vcpu_run_swith_to_core (adt: RData) :=\n let ctxtid := ctxt_id HOSTVISOR (cur_vcpuid adt) in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let regc := regs adt in\n let cregs1 := host_to_core_specx (ctxt_regs ctxt) (ctxt_regs regc) in\n let cregs2 := save_sysregs_specx cregs1 (ctxt_regs regc) in\n let cregs3 := fpsimd_save_state_specx cregs2 (ctxt_regs regc) in\n let vmid := x0 cregs3 in\n if is_vm vmid then\n adt {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt {ctxt_regs: cregs3})} {icore: true} {cur_vmid: vmid} {cur_vcpuid: -1}\n else\n adt {halt: true}.\n\n Definition vcpu_run_process (adt: RData) :=\n let vmid := cur_vmid adt in\n let clogn := vmid @ (core_data_log adt) in\n let vcpuid := (core_doracle adt) vmid clogn in\n let ctxtid' := ctxt_id vmid vcpuid in\n if is_vcpu vcpuid then\n let adt' := adt {cur_vcpuid: vcpuid} {core_data_log: (core_data_log adt) # vmid == (clogn + 1)} in\n let adt'' := query_oracle adt' in\n let l' := SEVENT (curid adt'') (OVM_ACTIVE vmid vcpuid) :: (slog adt'') in\n match local_set_vcpu_active vmid vcpuid (shared adt'') with\n | (sdt', halt', _) =>\n let adt0 := adt'' {halt: halt'} {shared: sdt'} {slog: l'} in\n if halt' then Some adt0 else\n let dirty0 := dirty (ctxt_states (ctxtid' @ (shadow_ctxts adt0))) in\n if dirty0 =? INVALID64 then\n let adt1 := query_oracle adt0 in\n rely (INFO_ID + vmid) @ (hlock (shared adt1));\n let l'' := SEVENT (curid adt1) (OVM_GET vmid) :: (slog adt1) in\n let inc_exe := vm_inc_exe (VB (vmid @ (vminfos (shared adt1)))) in\n if inc_exe =? 0 then\n let logn := vmid @ (data_log adt1) in\n let pc' := (doracle adt1) vmid logn in\n let adt2 := adt1 {slog: l''} {data_log: (data_log adt1) # vmid == (logn + 1)} in\n let adt3 := query_oracle adt2 in\n rely (INFO_ID + vmid) @ (hlock (shared adt3));\n let ll := SEVENT (curid adt3) (OVM_GET vmid) :: (slog adt3) in\n let info := vmid @ (vminfos (shared adt3)) in\n let num := vm_next_load_info (VB info) in\n let (_, ret) := search_load_info_loop_h (Z.to_nat num) 0 pc' 0 (VB info) in\n if ret =? 0 then Some adt3 {slog: ll} {halt: true}\n else\n let cregs' := clear_shadow_gp_regs_specx (ctxt_regs (ctxtid' @ (shadow_ctxts adt3))) in\n let logn' := vmid @ (data_log adt3) in\n let pstate' := (doracle adt3) vmid logn' in\n let cstates' := (ctxt_states (ctxtid' @ (shadow_ctxts adt3))) {pstate: pstate'} {pc: pc'} in\n let cregs'' := reset_fp_regs_specx cregs' in\n match reset_sys_regs_specx vcpuid cregs'' cstates' ((doracle adt3) vmid) (logn' + 1) with\n | (cregs''', cstates'', logn'') =>\n let cstats''' := cstates'' {dirty: 0} in\n Some adt0 {slog: ll} {data_log: (data_log adt3) # vmid == logn''}\n {shadow_ctxts: (shadow_ctxts adt3) # ctxtid' == ((ctxtid' @ (shadow_ctxts adt3)) {ctxt_regs: cregs'''} {ctxt_states: cstats'''})}\n end\n else\n let cstates' := (ctxt_states (ctxtid' @ (shadow_ctxts adt1))) {dirty: 0} in\n Some adt1 {slog: l''} {shadow_ctxts: (shadow_ctxts adt1) # ctxtid' == ((ctxtid' @ (shadow_ctxts adt1)) {ctxt_states: cstates'})}\n else\n let cregs := ctxt_regs (ctxtid' @ (shadow_ctxts adt0)) in\n let cstates := ctxt_states (ctxtid' @ (shadow_ctxts adt0)) in\n let ec0 := ec cregs in\n let logn := vmid @ (data_log adt0) in\n match (if ec0 =? ARM_EXCEPTION_TRAP\n then sync_dirty_to_shadow_specx vmid dirty0 cregs cstates logn ((doracle adt0) vmid)\n else (cregs, cstates, logn))\n with\n | (cregs', cstates', logn') =>\n match (if (Z.land dirty0 PENDING_EXCEPT_INJECT_FLAG) =? 0\n then update_exception_gp_regs_specx cregs' cstates'\n else (cregs', cstates'))\n with\n | (cregs'', cstates'') =>\n match (if (Z.land dirty0 DIRTY_PC_FLAG) =? 0\n then cstates''\n else (cstates'' {pc: (pc cstates'') + 4}))\n with\n | cstates3 =>\n let cstates4 := cstates3 {dirty: 0} in\n let cregs3 := cregs'' {far_el2: 0} in\n let clogn := vmid @ (core_data_log adt0) in\n let addr := (core_doracle adt0) vmid clogn in\n if (PAGE_SIZE <=? addr) && (addr \n if halt adt then Some adt else\n let adt' := vcpu_run_swith_to_core adt in\n if halt adt' then Some adt' else\n when adt'' == vcpu_run_process adt';\n if halt adt'' then Some adt'' else\n vcpu_run_switch_to_vm adt''\n | _ => None\n end.\n\n Definition prep_exit_vm (adt: RData) :=\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let cregs := ctxt_regs ctxt in\n let rcregs := ctxt_regs (regs adt) in\n let cregs1 := save_sysregs_specx cregs rcregs in\n let cregs2 := fpsimd_save_state_specx cregs1 rcregs in\n let rtregs1 := deactivate_traps_specx (trap_regs (regs adt)) in\n let rtregs2 := timer_enable_traps_specx rtregs1 in\n let ec' := ec cregs2 in\n match (\n if ec' =? ARM_EXCEPTION_TRAP then\n let hsr := esr_el2 cregs2 in\n let hsr_ec := Z.shiftr (Z.land hsr ESR_ELx_EC_MASK) ESR_ELx_EC_SHIFT in\n if hsr_ec =? ESR_ELx_EC_WFx then\n let cstates' := prep_wfx_specx (ctxt_states ctxt) in\n Some adt {regs: (regs adt) {trap_regs: rtregs2}}\n {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt {ctxt_regs: cregs2} {ctxt_states: cstates'})}\n else\n if hsr_ec =? ESR_ELx_EC_HVC64 then\n let adt' := adt {regs: (regs adt) {trap_regs: rtregs2}}\n {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt {ctxt_regs: cregs2})} in\n prep_hvc_spec_h vmid vcpuid adt'\n else\n if (hsr_ec =? ESR_ELx_EC_IABT_LOW) || (hsr_ec =? ESR_ELx_EC_DABT_LOW) then\n match prep_abort_specx cregs2 (ctxt_states ctxt) (vmid @ (data_log adt)) ((doracle adt) vmid) with\n | (cstates', logn') =>\n Some adt {regs: (regs adt) {trap_regs: rtregs2}} {data_log: (data_log adt) # vmid == logn'}\n {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt {ctxt_regs: cregs2} {ctxt_states: cstates'})}\n end\n else Some adt {halt: true}\n else\n Some adt {regs: (regs adt) {trap_regs: rtregs2}} {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt {ctxt_regs: cregs2})})\n with\n | Some adt1 =>\n if halt adt1 then Some adt1 else\n let adt2 := query_oracle adt1 in\n let l' := SEVENT (curid adt2) (OVM_INACTIVE vmid vcpuid) :: slog adt2 in\n match local_set_vcpu_inactive vmid vcpuid (shared adt2) with\n | (sdt', halt', _) =>\n Some adt2 {shared: sdt'} {halt: halt'} {slog: l'}\n end\n | _ => None\n end.\n\n Definition vm_exit_pre_process (adt: RData) :=\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let cregs := ctxt_regs ctxt in\n let rcregs := ctxt_regs (regs adt) in\n let cregs1 := vm_to_core_specx cregs rcregs in\n let cregs2 := exit_populate_fault_specx cregs1 rcregs in\n let adt' := adt {shadow_ctxts: (shadow_ctxts adt) # ctxtid == (ctxt {ctxt_regs: cregs2})} {icore: true} in\n let ec' := ec cregs2 in\n if ec' =? ARM_EXCEPTION_TRAP then\n match vm_exit_dispatcher_spec_h vmid vcpuid adt' with\n | Some (adt'', ret) =>\n if ret =? 0 then\n let ctxt := ctxtid @ (shadow_ctxts adt'') in\n Some (adt'' {regs: (regs adt'') {ctxt_regs: core_to_vm_specx (ctxt_regs ctxt) (ctxt_regs (regs adt''))}} {icore: false}, 0)\n else\n when adt3 == prep_exit_vm adt'';\n Some (adt3, 1)\n | _ => None\n end\n else\n if ec' =? ARM_EXCEPTION_INTERRUPT then\n when adt'' == prep_exit_vm adt';\n Some (adt'', 1)\n else Some (adt' {halt: true}, 1).\n\n Definition switch_to_host (adt: RData) :=\n let vmid := HOSTVISOR in\n let adt0 := adt {cur_vmid: vmid} {cur_vcpuid: -1} in\n let vcpuid := curid adt0 in\n let ctxtid := ctxt_id vmid vcpuid in\n let cregs := ctxt_regs ctxtid @ (shadow_ctxts adt0) in\n let cstates := ctxt_states ctxtid @ (shadow_ctxts adt0) in\n let rcregs := ctxt_regs (regs adt0) in\n let vttbr := pt_vttbr HOSTVISOR in\n let rcregs1 := host_el2_restore_state_specx rcregs vttbr in\n let rcregs2 := restore_sysregs_specx cregs cstates rcregs1 in\n let rcregs3 := fpsimd_restore_state_specx cregs rcregs2 in\n let rcregs4 := core_to_host_specx cregs rcregs3 in\n adt0 {regs: (regs adt0) {ctxt_regs: rcregs4}} {cur_vcpuid: vcpuid} {ihost: true} {icore: false}.\n\n Definition vm_exit_handler_spec (adt: RData) : option RData :=\n match (ihost adt, icore adt) with\n | (false, false) =>\n if halt adt then Some adt else\n when ret, adt' == vm_exit_pre_process adt;\n if halt adt' then Some adt' else\n if ret =? 0 then Some adt'\n else Some (switch_to_host adt')\n | _ => None\n end.\n\n Definition mem_load_spec (gfn: Z64) (reg: Z) (adt: RData) : option RData :=\n match gfn, icore adt with\n | VZ64 gfn, false =>\n let adt := query_oracle adt in\n let log' := (SEVENT (curid adt) (OPT_GET (cur_vmid adt))) :: (slog adt) in\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n match\n (if vmid =? HOSTVISOR then\n match gfn @ (pt (vmid @ (npts (shared adt)))) with\n | (pfn, level, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? HOSTVISOR\n then Some (pfn @ (flatmem (shared adt)))\n else Some ((doracle adt) vmid (vmid @ (data_log adt)))\n end\n else\n rely (vm_state (VS (cur_vmid adt) @ (vminfos (shared adt))) =? VERIFIED);\n match gfn @ (pt (vmid @ (npts (shared adt)))) with\n | (pfn, level, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? INVALID then None\n else\n if s2_count (pfn @ (s2page (shared adt))) =? 0\n then Some (pfn @ (flatmem (shared adt)))\n else Some ((doracle adt) vmid (vmid @ (data_log adt)))\n end\n )\n with\n | Some val =>\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n rely (reg \n let ctxt' := ctxt {ctxt_regs: cregs'} {ctxt_states: cstates'} in\n Some adt {shadow_ctxts: (shadow_ctxts adt) # ctxtid == ctxt'} {slog: log'}\n end\n | _ => None\n end\n | _, _ => None\n end.\n\n Definition mem_store_spec (gfn: Z64) (reg: Z) (adt: RData) : option RData :=\n match gfn, icore adt with\n | VZ64 gfn, false =>\n let adt := query_oracle adt in\n let log' := (SEVENT (curid adt) (OPT_GET (cur_vmid adt))) :: (slog adt) in\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let val := get_shadow_ctxt_specx reg (ctxt_regs ctxt) (ctxt_states ctxt) in\n if vmid =? HOSTVISOR then\n match gfn @ (pt (vmid @ (npts (shared adt)))) with\n | (pfn, level, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? HOSTVISOR\n then Some adt {shared: (shared adt) {flatmem: (flatmem (shared adt)) # pfn == val}} {slog: log'}\n else Some adt {slog: log'}\n end\n else\n rely (vm_state (VS (cur_vmid adt) @ (vminfos (shared adt))) =? VERIFIED);\n match gfn @ (pt (vmid @ (npts (shared adt)))) with\n | (pfn, level, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? INVALID then None\n else\n if s2_count (pfn @ (s2page (shared adt))) =? 0\n then Some adt {shared: (shared adt) {flatmem: (flatmem (shared adt)) # pfn == val}} {slog: log'}\n else Some adt {slog: log'}\n end\n | _, _ => None\n end.\n\n Definition dev_load_spec (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n match gfn, icore adt with\n | VZ64 gfn, false =>\n rely is_smmu index; rely is_smmu_cfg cbndx;\n let adt := query_oracle adt in\n let log' := (SEVENT (curid adt) (OPT_GET (cur_vmid adt))) :: (slog adt) in\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let smmuid := smmu_id index cbndx in\n rely smmuid @ (smmu_vmid (shared adt)) =? vmid;\n let spt := (SMMU_TTBR index cbndx) @ (spt_pt (spts (shared adt))) in\n match\n (if vmid =? HOSTVISOR then\n match gfn @ spt with\n | (pfn, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? HOSTVISOR\n then Some (pfn @ (flatmem (shared adt)))\n else Some ((doracle adt) vmid (vmid @ (data_log adt)))\n end\n else\n rely (vm_state (VS (cur_vmid adt) @ (vminfos (shared adt))) =? VERIFIED);\n match gfn @ spt with\n | (pfn, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? INVALID then None\n else\n if s2_count (pfn @ (s2page (shared adt))) =? 0\n then Some (pfn @ (flatmem (shared adt)))\n else Some ((doracle adt) vmid (vmid @ (data_log adt)))\n end\n )\n with\n | Some val =>\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n rely (reg \n let ctxt' := ctxt {ctxt_regs: cregs'} {ctxt_states: cstates'} in\n Some adt {shadow_ctxts: (shadow_ctxts adt) # ctxtid == ctxt'} {slog: log'}\n end\n | _ => None\n end\n | _, _ => None\n end.\n\n Definition dev_store_spec (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n match gfn, icore adt with\n | VZ64 gfn, false =>\n rely is_smmu index; rely is_smmu_cfg cbndx;\n let adt := query_oracle adt in\n let log' := (SEVENT (curid adt) (OPT_GET (cur_vmid adt))) :: (slog adt) in\n let vmid := cur_vmid adt in\n let vcpuid := cur_vcpuid adt in\n let ctxtid := ctxt_id vmid vcpuid in\n let smmuid := smmu_id index cbndx in\n rely smmuid @ (smmu_vmid (shared adt)) =? vmid;\n let spt := (SMMU_TTBR index cbndx) @ (spt_pt (spts (shared adt))) in\n let ctxt := ctxtid @ (shadow_ctxts adt) in\n let val := get_shadow_ctxt_specx reg (ctxt_regs ctxt) (ctxt_states ctxt) in\n if vmid =? HOSTVISOR then\n match gfn @ spt with\n | (pfn, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? HOSTVISOR\n then Some adt {shared: (shared adt) {flatmem: (flatmem (shared adt)) # pfn == val}} {slog: log'}\n else Some adt {slog: log'}\n end\n else\n rely (vm_state (VS (cur_vmid adt) @ (vminfos (shared adt))) =? VERIFIED);\n match gfn @ spt with\n | (pfn, pte) =>\n if pfn =? 0 then None else\n if s2_owner (pfn @ (s2page (shared adt))) =? INVALID then None\n else\n if s2_count (pfn @ (s2page (shared adt))) =? 0\n then Some adt {shared: (shared adt) {flatmem: (flatmem (shared adt)) # pfn == val}} {slog: log'}\n else Some adt {slog: log'}\n end\n | _, _ => None\n end.\n\nEnd TrapHandlerSpec.\n\nSection TrapHandlerSpecLow.\n\n Context `{real_params: RealParams}.\n\n Notation LDATA := RData.\n\n Notation LDATAOps := (cdata (cdata_ops := TrapHandlerRaw_ops) LDATA).\n\n Definition host_hvc_handler_spec0 (adt: RData) : option RData :=\n host_hvc_handler_raw_spec adt.\n\n Definition host_npt_handler_spec0 (adt: RData) : option RData :=\n host_npt_handler_raw_spec adt.\n\n Definition host_vcpu_run_handler_spec0 (adt: RData) : option RData :=\n host_vcpu_run_handler_raw_spec adt.\n\n Definition vm_exit_handler_spec0 (adt: RData) : option RData :=\n vm_exit_handler_raw_spec adt.\n\n Definition mem_load_spec0 (gfn: Z64) (reg: Z) (adt: RData) : option RData :=\n mem_load_ref_spec gfn reg adt.\n\n Definition mem_store_spec0 (gfn: Z64) (reg: Z) (adt: RData) : option RData :=\n mem_store_ref_spec gfn reg adt.\n\n Definition dev_load_spec0 (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n dev_load_ref_spec gfn reg cbndx index adt.\n\n Definition dev_store_spec0 (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n dev_load_ref_spec gfn reg cbndx index adt.\n\n Inductive host_hvc_handler_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | host_hvc_handler_spec_low_intro s (WB: _ -> Prop) m'0 labd labd'\n (Hinv: high_level_invariant labd)\n (Hspec: host_hvc_handler_spec labd = Some labd'):\n host_hvc_handler_spec_low_step s WB nil (m'0, labd) Vundef (m'0, labd').\n\n Inductive host_npt_handler_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | host_npt_handler_spec_low_intro s (WB: _ -> Prop) m'0 labd labd'\n (Hinv: high_level_invariant labd)\n (Hspec: host_npt_handler_spec labd = Some labd'):\n host_npt_handler_spec_low_step s WB nil (m'0, labd) Vundef (m'0, labd').\n\n Inductive host_vcpu_run_handler_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | host_vcpu_run_handler_spec_low_intro s (WB: _ -> Prop) m'0 labd labd'\n (Hinv: high_level_invariant labd)\n (Hspec: host_vcpu_run_handler_spec labd = Some labd'):\n host_vcpu_run_handler_spec_low_step s WB nil (m'0, labd) Vundef (m'0, labd').\n\n Inductive vm_exit_handler_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | vm_exit_handler_spec_low_intro s (WB: _ -> Prop) m'0 labd labd'\n (Hinv: high_level_invariant labd)\n (Hspec: vm_exit_handler_spec labd = Some labd'):\n vm_exit_handler_spec_low_step s WB nil (m'0, labd) Vundef (m'0, labd').\n\n Inductive mem_load_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | mem_load_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' gfn reg\n (Hinv: high_level_invariant labd)\n (Hspec: mem_load_spec (VZ64 (Int64.unsigned gfn)) (Int.unsigned reg) labd = Some labd'):\n mem_load_spec_low_step s WB ((Vlong gfn)::(Vint reg)::nil) (m'0, labd) Vundef (m'0, labd').\n\n Inductive mem_store_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | mem_store_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' gfn reg\n (Hinv: high_level_invariant labd)\n (Hspec: mem_store_spec (VZ64 (Int64.unsigned gfn)) (Int.unsigned reg) labd = Some labd'):\n mem_store_spec_low_step s WB ((Vlong gfn)::(Vint reg)::nil) (m'0, labd) Vundef (m'0, labd').\n\n Inductive dev_load_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | dev_load_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' gfn reg cbndx index\n (Hinv: high_level_invariant labd)\n (Hspec: dev_load_spec (VZ64 (Int64.unsigned gfn)) (Int.unsigned reg) (Int.unsigned cbndx) (Int.unsigned index) labd = Some labd'):\n dev_load_spec_low_step s WB ((Vlong gfn)::(Vint reg)::(Vint cbndx)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n Inductive dev_store_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | dev_store_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' gfn reg cbndx index\n (Hinv: high_level_invariant labd)\n (Hspec: dev_store_spec (VZ64 (Int64.unsigned gfn)) (Int.unsigned reg) (Int.unsigned cbndx) (Int.unsigned index) labd = Some labd'):\n dev_store_spec_low_step s WB ((Vlong gfn)::(Vint reg)::(Vint cbndx)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModelX}.\n Context `{Hmwd: UseMemWithData mem}.\n\n Definition host_hvc_handler_spec_low: compatsem LDATAOps :=\n csem host_hvc_handler_spec_low_step (type_of_list_type nil) Tvoid.\n\n Definition host_npt_handler_spec_low: compatsem LDATAOps :=\n csem host_npt_handler_spec_low_step (type_of_list_type nil) Tvoid.\n\n Definition host_vcpu_run_handler_spec_low: compatsem LDATAOps :=\n csem host_vcpu_run_handler_spec_low_step (type_of_list_type nil) Tvoid.\n\n Definition vm_exit_handler_spec_low: compatsem LDATAOps :=\n csem vm_exit_handler_spec_low_step (type_of_list_type nil) Tvoid.\n\n Definition mem_load_spec_low: compatsem LDATAOps :=\n csem mem_load_spec_low_step (type_of_list_type (Tint64::Tint32::nil)) Tvoid.\n\n Definition mem_store_spec_low: compatsem LDATAOps :=\n csem mem_store_spec_low_step (type_of_list_type (Tint64::Tint32::nil)) Tvoid.\n\n Definition dev_load_spec_low: compatsem LDATAOps :=\n csem dev_load_spec_low_step (type_of_list_type (Tint64::Tint32::Tint32::Tint32::nil)) Tvoid.\n\n Definition dev_store_spec_low: compatsem LDATAOps :=\n csem dev_store_spec_low_step (type_of_list_type (Tint64::Tint32::Tint32::Tint32::nil)) Tvoid.\n\n End WITHMEM.\n\nEnd TrapHandlerSpecLow.\n\n", "meta": {"author": "VeriGu", "repo": "VRM-proof", "sha": "9e3c9751f31713a133a0a7e98f3d4c9600ca7bde", "save_path": "github-repos/coq/VeriGu-VRM-proof", "path": "github-repos/coq/VeriGu-VRM-proof/VRM-proof-9e3c9751f31713a133a0a7e98f3d4c9600ca7bde/sekvm/TrapHandler/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.18952109819626003, "lm_q1q2_score": 0.09772085267968895}} {"text": "(** * ImpParser: Lexing and Parsing in Coq *)\n\n(** The development of the Imp language in [Imp.v] completely ignores\n issues of concrete syntax -- how an ascii string that a programmer\n might write gets translated into abstract syntax trees defined by\n the datatypes [aexp], [bexp], and [com]. In this chapter, we\n illustrate how the rest of the story can be filled in by building\n a simple lexical analyzer and parser using Coq's functional\n programming facilities.\n\n It is not important to understand all the details here (and\n accordingly, the explanations are fairly terse and there are no\n exercises). The main point is simply to demonstrate that it can\n be done. You are invited to look through the code -- most of it\n is not very complicated, though the parser relies on some\n \"monadic\" programming idioms that may require a little work to\n make out -- but most readers will probably want to just skim down\n to the Examples section at the very end to get the punchline. *)\n\n(* ####################################################### *)\n(** * Internals *)\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Maps.\nRequire Import Imp.\n\n(* ####################################################### *)\n(** ** Lexical Analysis *)\n\nDefinition isWhite (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (orb (beq_nat n 32) (* space *)\n (beq_nat n 9)) (* tab *)\n (orb (beq_nat n 10) (* linefeed *)\n (beq_nat n 13)). (* Carriage return. *)\n\nNotation \"x '<=?' y\" := (leb x y)\n (at level 70, no associativity) : nat_scope.\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (97 <=? n) (n <=? 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (andb (65 <=? n) (n <=? 90))\n (andb (97 <=? n) (n <=? 122)).\n\nDefinition isDigit (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (48 <=? n) (n <=? 57).\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n if isWhite c then\n white\n else if isAlpha c then\n alpha\n else if isDigit c then\n digit\n else\n other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n match s with\n | EmptyString => []\n | String c s => c :: (list_of_string s)\n end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n fold_right String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii)\n : list (list ascii) :=\n let tk := match acc with [] => [] | _::_ => [rev acc] end in\n match xs with\n | [] => tk\n | (x::xs') =>\n match cls, classifyChar x, x with\n | _, _, \"(\" =>\n tk ++ [\"(\"]::(tokenize_helper other [] xs')\n | _, _, \")\" =>\n tk ++ [\")\"]::(tokenize_helper other [] xs')\n | _, white, _ =>\n tk ++ (tokenize_helper white [] xs')\n | alpha,alpha,x =>\n tokenize_helper alpha (x::acc) xs'\n | digit,digit,x =>\n tokenize_helper digit (x::acc) xs'\n | other,other,x =>\n tokenize_helper other (x::acc) xs'\n | _,tp,x =>\n tk ++ (tokenize_helper tp [x] xs')\n end\n end %char.\n\nDefinition tokenize (s : string) : list string :=\n map string_of_list (tokenize_helper white [] (list_of_string s)).\n\nExample tokenize_ex1 :\n tokenize \"abc12==3 223*(3+(a+c))\" %string\n = [\"abc\"; \"12\"; \"==\"; \"3\"; \"223\";\n \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n \"a\"; \"+\"; \"c\"; \")\"; \")\"]%string.\nProof. reflexivity. Qed.\n\n(* ####################################################### *)\n(** ** Parsing *)\n\n(** *** Options With Errors *)\n\n(** An [option] type with error messages: *)\n\nInductive optionE (X:Type) : Type :=\n | SomeE : X -> optionE X\n | NoneE : string -> optionE X.\n\nImplicit Arguments SomeE [[X]].\nImplicit Arguments NoneE [[X]].\n\n(** Some syntactic sugar to make writing nested match-expressions on\n optionE more convenient. *)\n\nNotation \"'DO' ( x , y ) <== e1 ; e2\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => NoneE err\n end)\n (right associativity, at level 60).\n\nNotation \"'DO' ( x , y ) <-- e1 ; e2 'OR' e3\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => e3\n end)\n (right associativity, at level 60, e2 at next level).\n\n(** *** Symbol Table *)\n\n(** Build a mapping from [tokens] to [nats]. A real parser would do\n this incrementally as it encountered new symbols, but passing\n around the symbol table inside the parsing functions is a bit\n inconvenient, so instead we do it as a first pass. *)\n\nFixpoint build_symtable (xs : list token) (n : nat)\n : (token -> nat) :=\n match xs with\n | [] => (fun s => n)\n | x::xs =>\n if (forallb isLowerAlpha (list_of_string x))\n then (fun s => if string_dec s x then n\n else (build_symtable xs (S n) s))\n else build_symtable xs n\n end.\n\n(** *** Generic Combinators for Building Parsers *)\n\nOpen Scope string_scope.\n\nDefinition parser (T : Type) :=\n list token -> optionE (T * list token).\n\nFixpoint many_helper {T} (p : parser T) acc steps xs :=\n match steps, p xs with\n | 0, _ =>\n NoneE \"Too many recursive calls\"\n | _, NoneE _ =>\n SomeE ((rev acc), xs)\n | S steps', SomeE (t, xs') =>\n many_helper p (t::acc) steps' xs'\n end.\n\n(** A (step-indexed) parser that expects zero or more [p]s: *)\n\nFixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=\n many_helper p [] steps.\n\n(** A parser that expects a given token, followed by [p]: *)\n\nDefinition firstExpect {T} (t : token) (p : parser T)\n : parser T :=\n fun xs => match xs with\n | x::xs' =>\n if string_dec x t\n then p xs'\n else NoneE (\"expected '\" ++ t ++ \"'.\")\n | [] =>\n NoneE (\"expected '\" ++ t ++ \"'.\")\n end.\n\n(** A parser that expects a particular token: *)\n\nDefinition expect (t : token) : parser unit :=\n firstExpect t (fun xs => SomeE(tt, xs)).\n\n(** *** A Recursive-Descent Parser for Imp *)\n\n(** Identifiers: *)\n\nDefinition parseIdentifier (symtable :string->nat)\n (xs : list token)\n : optionE (id * list token) :=\nmatch xs with\n| [] => NoneE \"Expected identifier\"\n| x::xs' =>\n if forallb isLowerAlpha (list_of_string x) then\n SomeE (Id (symtable x), xs')\n else\n NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\nend.\n\n(** Numbers: *)\n\nDefinition parseNumber (xs : list token)\n : optionE (nat * list token) :=\nmatch xs with\n| [] => NoneE \"Expected number\"\n| x::xs' =>\n if forallb isDigit (list_of_string x) then\n SomeE (fold_left\n (fun n d =>\n 10 * n + (nat_of_ascii d -\n nat_of_ascii \"0\"%char))\n (list_of_string x)\n 0,\n xs')\n else\n NoneE \"Expected number\"\nend.\n\n(** Parse arithmetic expressions *)\n\nFixpoint parsePrimaryExp (steps:nat) symtable\n (xs : list token)\n : optionE (aexp * list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (i, rest) <-- parseIdentifier symtable xs ;\n SomeE (AId i, rest)\n OR DO (n, rest) <-- parseNumber xs ;\n SomeE (ANum n, rest)\n OR (DO (e, rest) <== firstExpect \"(\"\n (parseSumExp steps' symtable) xs;\n DO (u, rest') <== expect \")\" rest ;\n SomeE(e,rest'))\n end\n\nwith parseProductExp (steps:nat) symtable\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parsePrimaryExp steps' symtable xs ;\n DO (es, rest') <==\n many (firstExpect \"*\" (parsePrimaryExp steps' symtable))\n steps' rest;\n SomeE (fold_left AMult es e, rest')\n end\n\nwith parseSumExp (steps:nat) symtable (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseProductExp steps' symtable xs ;\n DO (es, rest') <==\n many (fun xs =>\n DO (e,rest') <--\n firstExpect \"+\"\n (parseProductExp steps' symtable) xs;\n SomeE ( (true, e), rest')\n OR DO (e,rest') <==\n firstExpect \"-\"\n (parseProductExp steps' symtable) xs;\n SomeE ( (false, e), rest'))\n steps' rest;\n SomeE (fold_left (fun e0 term =>\n match term with\n (true, e) => APlus e0 e\n | (false, e) => AMinus e0 e\n end)\n es e,\n rest')\n end.\n\nDefinition parseAExp := parseSumExp.\n\n(** Parsing boolean expressions: *)\n\nFixpoint parseAtomicExp (steps:nat) (symtable : string->nat)\n (xs : list token) :=\nmatch steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u,rest) <-- expect \"true\" xs;\n SomeE (BTrue,rest)\n OR DO (u,rest) <-- expect \"false\" xs;\n SomeE (BFalse,rest)\n OR DO (e,rest) <-- \n firstExpect \"not\" \n (parseAtomicExp steps' symtable) \n xs;\n SomeE (BNot e, rest)\n OR DO (e,rest) <-- \n firstExpect \"(\" \n (parseConjunctionExp steps' symtable) xs;\n (DO (u,rest') <== expect \")\" rest; \n SomeE (e, rest'))\n OR DO (e, rest) <== parseProductExp steps' symtable xs;\n (DO (e', rest') <--\n firstExpect \"==\" \n (parseAExp steps' symtable) rest;\n SomeE (BEq e e', rest')\n OR DO (e', rest') <--\n firstExpect \"<=\" \n (parseAExp steps' symtable) rest;\n SomeE (BLe e e', rest')\n OR\n NoneE \n \"Expected '==' or '<=' after arithmetic expression\")\nend\n\nwith parseConjunctionExp (steps:nat)\n (symtable : string->nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseAtomicExp steps' symtable xs ;\n DO (es, rest') <==\n many (firstExpect \"&&\"\n (parseAtomicExp steps' symtable))\n steps' rest;\n SomeE (fold_left BAnd es e, rest')\n end.\n\nDefinition parseBExp := parseConjunctionExp.\n\nCheck parseConjunctionExp.\n\nDefinition testParsing {X : Type}\n (p : nat -> (string -> nat) ->\n list token ->\n optionE (X * list token))\n (s : string) :=\n let t := tokenize s in \n p 100 (build_symtable t 0) t.\n\n(*\nEval compute in \n testParsing parseProductExp \"x*y*(x*x)*x\".\n\nEval compute in \n testParsing parseConjunctionExp \"not((x==x||x*x<=(x*x)*x)&&x==x\". \n*)\n\n(** Parsing commands: *)\n\nFixpoint parseSimpleCommand (steps:nat) \n (symtable:string->nat) \n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u, rest) <-- expect \"SKIP\" xs;\n SomeE (SKIP, rest)\n OR DO (e,rest) <--\n firstExpect \"IF\" (parseBExp steps' symtable) xs;\n DO (c,rest') <==\n firstExpect \"THEN\" \n (parseSequencedCommand steps' symtable) rest;\n DO (c',rest'') <==\n firstExpect \"ELSE\" \n (parseSequencedCommand steps' symtable) rest';\n DO (u,rest''') <==\n expect \"END\" rest'';\n SomeE(IFB e THEN c ELSE c' FI, rest''')\n OR DO (e,rest) <--\n firstExpect \"WHILE\" \n (parseBExp steps' symtable) xs;\n DO (c,rest') <==\n firstExpect \"DO\" \n (parseSequencedCommand steps' symtable) rest;\n DO (u,rest'') <==\n expect \"END\" rest';\n SomeE(WHILE e DO c END, rest'')\n OR DO (i, rest) <==\n parseIdentifier symtable xs;\n DO (e, rest') <==\n firstExpect \":=\" (parseAExp steps' symtable) rest;\n SomeE(i ::= e, rest')\n end\n\nwith parseSequencedCommand (steps:nat)\n (symtable:string->nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (c, rest) <==\n parseSimpleCommand steps' symtable xs;\n DO (c', rest') <--\n firstExpect \";;\" \n (parseSequencedCommand steps' symtable) rest;\n SomeE(c ;; c', rest')\n OR\n SomeE(c, rest)\n end.\n\nDefinition bignumber := 1000.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n let tokens := tokenize str in\n parseSequencedCommand bignumber\n (build_symtable tokens 0) tokens.\n\n(* ####################################################### *)\n(** * Examples *)\n\n(*\nCompute parse \"\n IF x == y + 1 + 2 - y * 6 + 3 THEN\n x := x * 1;;\n y := 0\n ELSE\n SKIP\n END \".\n====>\n SomeE\n (IFB BEq (AId (Id 0))\n (APlus\n (AMinus (APlus (APlus (AId (Id 1)) (ANum 1)) (ANum 2))\n (AMult (AId (Id 1)) (ANum 6)))\n (ANum 3))\n THEN Id 0 ::= AMult (AId (Id 0)) (ANum 1);; Id 1 ::= ANum 0\n ELSE SKIP FI, [])\n*)\n\n(*\nCompute parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n====>\n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0)\n ELSE SKIP FI;;\n SKIP\n END;;\n Id 1 ::= AId (Id 0),\n [])\n*)\n\n(*\nCompute parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n=====>\n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);;\n Id 2 ::= AId (Id 0)\n ELSE SKIP\n FI;;\n SKIP\n END;;\n Id 1 ::= AId (Id 0),\n []).\n*)\n\n(** $Date: 2016-05-26 12:03:56 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "colinmccabe", "repo": "software-foundations", "sha": "d581e89d47978ed9acc9e2a64ba6209a614fd9f1", "save_path": "github-repos/coq/colinmccabe-software-foundations", "path": "github-repos/coq/colinmccabe-software-foundations/software-foundations-d581e89d47978ed9acc9e2a64ba6209a614fd9f1/ImpParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.2018132270610754, "lm_q1q2_score": 0.09618008033345508}} {"text": "(*|\n###############################################\nUnderstanding how pattern matching works in Coq\n###############################################\n\n:Link: https://stackoverflow.com/q/72930287\n|*)\n\n(*|\nQuestion\n********\n\nI'm currently following the `Software Foundations\n`__ book, I am currently\non the **Lists chapter**. However, I'm having a hard time wrapping my\nhead around a specific case of pattern matching and, due to being a\nbeginner in Coq, I'm not sure about how to find the answer of this\nquestion.\n\nSo, the exercise was to create a ``Fixpoint`` to calculate how many\nnat ``v`` we have in a list ``s`` (a bag, more specifically).\n\nI decided to use pattern matching for this, but if I tried to define a\nfunction like this:\n\n.. coq:: none\n|*)\n\nRequire Import List.\nImport ListNotations.\n\nDefinition bag := list nat.\n\n(*||*)\n\nFixpoint count' (v : nat) (s : bag) : nat :=\n match s with\n | nil => O\n | h :: t => match h with\n | v => S (count' v t)\n end\n end.\n\n(*| and tried to apply this function to, let's say, |*)\n\nExample test_count1 : count' 1 [1;2;3;1;4;1] = 3.\n\n(*|\nI would end up with ``6 = 3``. My understanding is that matching ``h``\nwith ``v`` is always \"true\", so it ends up counting every element of\nthe list.\n\nBut why does it happen? How could we compare, using pattern matching,\nthe values of both ``h`` and ``v``?\n\n**PS:** I have already solved this exercise using an auxiliary\nfunction that compares if ``h`` and ``v`` are equal, but I'm wondering\nif this can be achieved only using built-in pattern matching.\n|*)\n\n(*|\nAnswer (Li-yao Xia)\n*******************\n\nThe pattern\n\n.. code-block:: coq\n\n match h with\n | v => S (count' v t)\n end\n\nintroduces a new variable ``v`` bound to ``h``, shadowing the existing\n``v``. It is equivalent to a ``let`` expression:\n\n.. code-block:: coq\n\n let v := h in S (count' v t)\n (* or, without shadowing *)\n let v1 := h in S (count' v1 t)\n\nInstead, to compare ``h`` and ``v``, use a comparison function:\n\n.. code-block:: coq\n\n if h =? v then ... else ...\n|*)\n\n(*|\nAnswer (Ana Borges)\n*******************\n\nPattern matching is useful when you want to make case distinctions on\nconstructors. Perhaps the name is misleading in this sense, since\n\n.. code-block:: coq\n\n match h with\n | v => ...\n end\n\nwill not compare ``h`` and the specific ``v`` from above. Instead, the\n``match`` checks to see if the shape of ``h`` matches the shape\nexemplified by ``v``. Like Li-yao Xia mentioned, here ``v`` has no\nshape, it is a universal placeholder. On the other hand something like\n\n.. code-block:: coq\n\n match h with\n | O => ...\n | S k => ...\n end\n\nexposes two different shapes that a ``nat`` can have, namely being\n``O`` or the successor of some ``k``. The latter is the kind of\nsituation where we do want to use ``match``. Comparing values is best\ndone through ``_ =? _``.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/understanding-how-pattern-matching-works-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.20689404392565777, "lm_q1q2_score": 0.09538162885372847}} {"text": "(** # Tactics for Waterproof*)\nRequire Import Rbase.\nRequire Import Rfunctions.\nRequire Import SeqSeries.\nRequire Import Rtrigo.\nRequire Import Ranalysis.\nRequire Import Integration.\nRequire Import micromega.Lra.\nRequire Import Omega.\nRequire Import Max.\n(* Require Import Unicode.Utf8. *)\nRequire Import Sets.Ensembles.\nRequire Import Sets.Classical_sets.\n(** *)\n(** ## Custom notations*)\n(** Guarantee indentation and introduce custom notation for forall *)\nNotation \"'for' 'all' x .. y , P\" := (forall x, .. (forall y, P) ..)\n (at level 200, x binder, y binder, right associativity,\n format \"'[ ' '[ ' for all x .. y ']' , '//' P ']'\") : type_scope.\n\nNotation \"∀ x .. y , P\" := (forall x, .. (forall y, P) ..)\n (at level 200, x binder, y binder, right associativity,\n only parsing) : type_scope.\n\nNotation \"'there' 'exists' x .. y , P \" := (exists x, .. (exists y, P) ..)\n (at level 200, x binder, y binder, right associativity,\n format \"'[ ' '[ ' there exists x .. y ']' , '//' P ']'\") : type_scope.\n\nNotation \"∃ x .. y , P \" := (exists x, .. (exists y, P) ..)\n (at level 200, x binder, y binder, right associativity,\n only parsing) : type_scope.\n\nNotation \"'fun' x .. y '↦' t\" := (fun x => .. (fun y => t) ..)\n (at level 200, x binder, y binder, right associativity,\n format \"'[ ' '[ ' 'fun' x .. y ']' '↦' '/' t ']'\").\n\nNotation \"x ∨ y\" := (x \\/ y) (at level 85, right associativity) : type_scope.\nNotation \"x ∧ y\" := (x /\\ y) (at level 80, right associativity) : type_scope.\nNotation \"x → y\" := (x -> y)\n (at level 99, y at level 200, right associativity,\n only parsing): type_scope.\nNotation \"x ⇒ y\" := (x -> y)\n (at level 99, y at level 200, right associativity,\n only parsing): type_scope.\n(* the notation below is fun, but is no good for functions *)\n(* need to see if this can be adapted so it only uses \n this notation for propositions *)\n(*Notation \"'if' x 'then' y\" := (x -> y)\n (at level 99, y at level 200, right associativity): prop_scope.*)\nNotation \"x ⇨ y\" := (x -> y)\n (at level 99, y at level 200, right associativity): type_scope.\n\nNotation \"x ↔ y\" := (x <-> y) (at level 95, no associativity): type_scope.\nNotation \"x ⇔ y\" := (x <-> y) (at level 95, no associativity): type_scope.\nNotation \"¬ x\" := (~x) (at level 75, right associativity) : type_scope.\nNotation \"x ≠ y\" := (x <> y) (at level 70) : type_scope.\n\nNotation \"x ≤ y\" := (le x y) (at level 70, no associativity) : nat_scope.\nNotation \"x ≥ y\" := (ge x y) (at level 70, no associativity) : nat_scope.\n\nNotation \"x ≤ y\" := (x <= y)%R (at level 70, no associativity) : R_scope.\nNotation \"x ≥ y\" := (x >= y)%R (at level 70, no associativity) : R_scope.\n\nOpen Scope nat_scope.\nOpen Scope R_scope.\n\n(* TODO: the below definition doesn't work very nicely *)\nNotation \"x ↦ y\" := (fun x => y) (at level 0).\n\nNotation \"'ℕ'\" := (nat).\nNotation \"'ℝ'\" := (R).\n\n(** Add field and lra to tactics to try automatically *)\n\nHint Extern 3 ( _ = _ ) => field : real.\nHint Extern 3 ( _ <= _ ) => lra : real.\nHint Extern 3 ( _ >= _ ) => lra : real.\nHint Extern 3 ( _ < _ ) => lra : real.\nHint Extern 3 ( _ > _ ) => lra : real.\n\n\n(** ## A powertool*)\n(* TODO: in some cases, eauto has left some existentials.\n this may be undesired, but eauto can be very powerful...\n one option is to let waterproof check whether \n existentials are created and block this behavior. *)\n\nLtac wp_power :=\n timeout 60 (first [ solve [auto with *]\n | solve [eauto with *]\n | solve [firstorder (auto with *)]\n | solve [firstorder (eauto with *)]]).\n(** *)\n(** ## Introducing variables\n\nThe following is a strict version of `intro`, that checks the type of the variable to introduce.*)\nLtac intro_strict s t :=\n match goal with\n | [ |- forall _ : t, _ ] => intro s\n end.\n\n(** *)\n(** Take an arbitrary element of a certain type.*)\nTactic Notation \"Take\" ident(s) \":\" constr(t):=\n intro_strict s t.\n\n\n(** *)\n(** *)\n(** *)\n(** Taking two elements of the same type. (To be generalised?)*)\nLtac intros_strict x y t :=\n match goal with\n | [ |- forall _ _ : t, _] => intros x y\n end.\n\nTactic Notation \"Take\" ident(x) ident(y) \":\" constr(t):=\n intros_strict x y t. \n(** \nVariation of intro tactic that allows one to check that what you assume is really what you need to assume.*)\nLtac assume_strict s t :=\n match goal with\n | [ |- ?u -> _ ] => (change u with t; intro s)\n end.\n\n(** *)\n(** Assuming hypotheses.*)\nTactic Notation \"Assume\" ident(s) :=\n intro s.\n\nTactic Notation \"Assume\" ident(s) \":\" constr(t) :=\n assume_strict s t.\n(** ## Checking the context\n\nThe following tactics let the user record in the proof script various aspects of the current context.\n\nThe tactic call `goal_check t` checks if the current goal can equivalently be written as `t`, otherwise it fails.*)\nLtac goal_check t :=\n tryif (change t) \n then (idtac \"We indeed need to show that\" t)\n else fail \"This is not the current goal\".\n\n(** Make it possible to verify the goal t by writing\n \"We need to show that t\". *)\nTactic Notation \"We\" \"need\" \"to\" \"show\" \"that\" constr(t) :=\n goal_check t.\n\n(** Make it possible to verify the goal t by writing\n \"To show : t\". *)\nTactic Notation \"To\" \"show\" \":\" constr(t) :=\n goal_check t.\n\n(** The tactic (hypo_check s t) checks if t is one of the \n current hypothesis, and if so, it renames it into s *)\nLtac hypo_check s t:=\nmatch goal with \n| [H : t |- _] => rename H into s\n| _ => fail\nend.\n(** *)\n(** ## Choosing variables that exist*)\nTactic Notation \"Choose\" constr(t):=\n exists t.\n\nTactic Notation \"Choose\" ident(s) \":=\" constr(t) :=\n pose (s := t);\n exists s.\n\nTactic Notation \"Choose\" ident(s) \n \"such\" \"that\" ident(u)\n \"according\" \"to\" constr(v) (*\":\" constr(t)*):=\n destruct v as [s u].\n\n(*Tactic Notation \"Choose\" ident(s)\n \"such\" \"that\" ident(u)\n \"according\" \"to\" ident(v)\n \"with\" constr(t) :=\n destruct v with t as [s u]. *)\n\nTactic Notation \"Choose\" ident(s)\n \"such\" \"that\" ident(u)\n \"according\" \"to\" constr(v)\n \"with\" constr(t) :=\n destruct v with t as [s u].\n(** *)\n(** ## Forward reasoning*)\nTactic Notation \"Because\" ident(s) \n \"both\" ident(u) \"and\" ident(v) :=\n destruct s as [u v].\n\nTactic Notation \"Because\" ident(s) \n \"both\" ident(u) \":\" constr(t_u)\n \"and\" ident(v) \":\" constr(t_v):=\n destruct s as [u v].\n\nTactic Notation \"Because\" ident(s)\n \"either\" ident(u) \"or\" ident(v) :=\n destruct s as [u | v].\n\n\n(** *)\n(** ## Forward reasoning by automation*)\n(** Apply with goal check\n The next tactics verify whether certain steps have the desired effect. *)\nLtac new_goal_verified_apply s t :=\n apply s;\n match goal with \n | [|- t] => idtac \"Expected goal was produced\"\n | _ => fail \"Lemma did not produce expected outcome\"\n end.\n\n(*Tactic Notation \"By\" constr(s) \n \"it\" \"suffices\" \"to\" \"show\" \"that\"\n constr(t) :=\n new_goal_verified_apply s t.*)\n\n(** A powerful forward reasoning tactic. \n The sequential trying of auto and eauto \n is there because eauto can be much slower. \n TODO: is this what we want? *)\nLtac new_hyp_verified_pose_proof s t u:=\n assert (u : t) by timeout 60 (first [ solve [auto using s with *]\n | solve [eauto using s with *]\n | solve [firstorder using s]\n | solve [firstorder (eauto with *) using s]\n | idtac \"Waterproof could not find a proof. If you believe the statement should hold, try making a smaller step\"]).\n\nLtac new_hyp_verified_pose_proof_no_name s t:=\n assert t by timeout 60 (first [ solve [auto using s with *]\n | solve [eauto using s with *]\n | solve [firstorder using s]\n | solve [firstorder (eauto with *) using s]\n | idtac \"Waterproof could not find a proof. If you believe the statement should hold, try making a smaller step\"]).\n\nTactic Notation \"By\" constr(s)\n \"it\" \"holds\" \"that\" constr(t) \"(\"ident(u)\")\"\n := new_hyp_verified_pose_proof s t u.\n\nTactic Notation \"By\" constr(s)\n \"it\" \"holds\" \"that\" constr(t)\n := new_hyp_verified_pose_proof_no_name s t.\n\n(*Tactic Notation \"By\" constr(s0) \",\" constr(s1)\n \"it\" \"holds\" \"that\" constr(t) \"(\"ident(u)\")\"\n :=*)\n\n(* TODO: align syntax with \"By ... it holds that\" *)\nTactic Notation \"It\" \"holds\" \"that\"\n constr(t) \"(\" ident(u) \")\" :=\n assert (u : t) by first [ wp_power\n | idtac \"Waterproof could not find a proof. If you believe the statement should hold, try making a smaller step\"].\n\nLtac conclude_proof t :=\n match goal with\n | [|-t] => idtac\n | _ => (idtac \"Warning: The statement you provided does not exactly correspond to the current goal. This can make your proof less readable.\"; change t || fail \"The provided statement cannot be converted to the current goal. If you are trying to prove an intermediate step, add a name to your hypothesis between brackets at the end of the sentence.\")\n end; first [wp_power | fail \"Waterproof could not find a proof. Try making a smaller step.\"].\n\nTactic Notation \"It\" \"holds\" \"that\" constr(t) :=\n conclude_proof t.\n\nTactic Notation \"It\" \"follows\" \"that\" constr(t) :=\n conclude_proof t.\n(** *)\n(** Now a somewhat experimental and non-standard notation to resolve a goal using another assumption/lemma. The usual `By ... it holds that ...` does not do this, even without adding a name.*)\nTactic Notation \"By\" constr(u) \"it\" \"holds\" \"that\" constr(t) \"which\" \"concludes\" ident(the) \"proof\":= \n By u it holds that t (the); \n apply the. \n(** TODO: preferably deprecate this notation.*)\nTactic Notation \"This\" \"follows\" \"immediately\" :=\n wp_power.\n\nTactic Notation \"follows\" \"immediately\" := \n wp_power.\nTactic Notation \"It\" \"suffices\" \"to\" \"show\" \"that\"\n constr(t) :=\n enough t by ( wp_power || fail \"Waterproof could not confirm that proving the statement would be enough.\").\nTactic Notation \"It\" \"suffices\" \"to\" \"show\" \"that\"\n constr(t) \"by\" tactic(tac) :=\n enough t by tac.\nTactic Notation \"Write\" \"goal\" \"using\" constr(t) \"as\" \n constr(s) :=\n let u := fresh in\n assert (u : t) by wp_power;\n rewrite u;\n enough s by wp_power;\n clear u.\nTactic Notation \"Write\" ident(H) \"using\" constr(t) \"as\"\n constr(s) :=\n let u := fresh in\n assert (u : t) by wp_power;\n rewrite u in H;\n clear u.\n\n\n\n\n(** *)\n(** ## Applying one of the assumptions*)\nTactic Notation \"This\" \"follows\" \"by\" \"assumption\" := \n assumption.\n(** *)\n(** ## Claims*)\nTactic Notation \"We\" \"claim\" \"that\" \n constr(t) \"(\" ident(u) \")\" :=\n assert (u : t).\n(** ## Rewriting\n\nTODO: add rewrite with at\nTODO: add support for rewriting in and at multiple places at once*)\n(** *)\nTactic Notation \"Rewrite\" \"using\" constr(t) :=\n let u := fresh in\n assert (u : t) by wp_power;\n rewrite u;\n clear u.\n\nTactic Notation \"rewrite\" \"using\" constr(t) :=\n let u := fresh in\n assert (u : t) by wp_power;\n rewrite u;\n clear u.\n\nTactic Notation \"Rewrite\" \"using\" constr(t) \"in\" ident(s):=\n let u := fresh in\n assert (u : t) by wp_power;\n rewrite u in s;\n clear u.\n\nTactic Notation \"rewrite\" \"using\" constr(t) \"in\" ident(s):=\n let u := fresh in\n assert (u : t) by wp_power;\n rewrite u in s;\n clear u.\n\nTactic Notation \"Rewrite\" \"<-\" \"using\" constr(t) :=\n let u := fresh in \n assert (u : t) by wp_power;\n rewrite<-u;\n clear u.\n(** *)\nTactic Notation \"replacing\" constr(s) \"with\" constr(t) :=\n replace s with t by wp_power.\n(** ## Applying lemmas and theorems*)\nTactic Notation \"Apply\" uconstr(t) :=\n apply t.\n(** *)\n(** Note: when using `constr(t)` instead of `uconstr(t)`, the use of wildcareds is no longer possible.\n\nTODO: add option to do an 'apply with'.*)\n(** ## Expanding definitions\n\nTODO: add more options for these tactics.*)\nTactic Notation \"Unfold\" constr(t) :=\n unfold t.\n\nTactic Notation \"Unfold\" constr(t) \"in\" ident(s):=\n unfold t in s.\n\nTactic Notation \"Expand\" \"the\" \"definition\" \"of\" reference(t) :=\n unfold t.\n\nTactic Notation \"Expand\" \"the\" \"definition\" \"of\" \n reference(t) \"in\" ident(s) :=\n unfold t in s.\n\nTactic Notation \"Write\" ident(s) \"as\" constr(t) :=\n change t in s.\n\n(** *)\n(** ## Strings of (in)equalities\n\nThe following tactics should help in situations where in a pen-and-paper proof we would write a string equalities and inequalites.\n\n**Note:** As of now, forward reasoning by \"it holds that\" seems to be a better option.\n\nThe tactic `trans_ineq eq_or_ineq` reduces the inequality in the goal to a new one by using `eq_or_ineq`.*)\nLtac trans_ineq eq_or_ineq := \n match goal with \n | [|-?x <= ?z] => \n match (type of eq_or_ineq) with \n | (x <= ?y) => apply (Rle_trans x y z eq_or_ineq)\n | _ => idtac \"not a less-than-or-equal-to inequality\"\n end\n | _ => idtac \"Goal is not a less-than-or-equal-to inequality.\"\n end.\n(** *)\n(** ## Defining new variables*)\nTactic Notation \"Define\" ident(u) \":=\" constr(t) :=\n set (u := t).\n(** *)\n(** ## Reflexivity*)\nTactic Notation \"This\" \"follows\" \"by\" \"reflexivity\" :=\n reflexivity.\n(** ## Simplification\n\nTODO: the following tactic notation may need to be improved.*)\nTactic Notation \"Simplify\" \"what\" \"we\" \"need\" \"to\" \"show\" :=\n simpl.\n(** ## Proving by induction\n\nVery basic notation, room for improvement. Also not the nicest formulation, but `Proof` is already used. *)\nTactic Notation \"We\" \"prove\" \"by\" \"induction\" \"on\" ident(x) := \n induction x. \n(** ## A tool for set equalities and inclusions*)\n(** TODO This tool works well in separate lemmas, but not always in larger contexts. Also, no error message is built in yet.*)\nLtac set_power :=\n timeout 1 (first [ solve [auto with sets]\n | solve [eauto with sets]\n | solve [firstorder (auto with sets)]\n | solve [firstorder (eauto with sets)]]).\n\nLtac destruct_sets :=\n match goal with \n | [H : In _ (Intersection _ _ _) _ |- _] => destruct H\n | [H : In _ (Union _ _ _) _ |- _] => destruct H; try set_power\n end.\n\nLtac trivial_set_inclusion := \n try intro x;\n try intro H;\n try destruct_sets;\n try contradiction;\n try set_power.\n\nLtac trivial_set_equality := \n try intros A;\n try intros B;\n try apply Extensionality_Ensembles;\n try unfold Same_set;\n try unfold Included;\n split;\n trivial_set_inclusion;\n trivial_set_inclusion.\n\n\nTactic Notation \"This\" \"equality\" \"is\" \"trivial\" := \n trivial_set_equality.\n(** \n\n## Hints*)\nHint Resolve Rmult_gt_0_compat : real.\nHint Resolve Rmult_lt_0_compat : real.\nHint Resolve R_dist_eq : real.\nHint Constructors Union Intersection Disjoint Full_set : sets. \n\n(*Would like to add the following hint, but this undesirably interferes with workings of e.g. wp_power. Also, what weight to use?\nHint Extern 5 (_ = _) => try trivial_set_equality : sets. \n*)\n(** *)\n", "meta": {"author": "jmoraal", "repo": "BachelorFinalProject_MeasureTheory_WP", "sha": "81c2fc5b692c8a2dec7b6e0b1a9bf18df36caada", "save_path": "github-repos/coq/jmoraal-BachelorFinalProject_MeasureTheory_WP", "path": "github-repos/coq/jmoraal-BachelorFinalProject_MeasureTheory_WP/BachelorFinalProject_MeasureTheory_WP-81c2fc5b692c8a2dec7b6e0b1a9bf18df36caada/WP exports/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444286, "lm_q2_score": 0.2068940439256578, "lm_q1q2_score": 0.09377717363709699}} {"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import strings gmap.\nFrom melocoton Require Import named_props.\nFrom transfinite.base_logic.lib Require Import ghost_map ghost_var.\nFrom iris.algebra Require Import gset.\nFrom iris.proofmode Require Import proofmode.\nFrom melocoton.c_interface Require Export defs resources.\nFrom melocoton.ml_lang Require Import lang_instantiation.\nFrom melocoton.ml_lang Require Export lang primitive_laws.\nFrom melocoton.interop Require Import basics_resources.\n\n(* The [GC θ] resource.\n\n [GC θ] represents the collection of authoritative resources related to the ML\n runtime while running or interoperating with external C-like code. It is used\n e.g. in the points-to update laws that translate between ML and block-level\n pointsto.\n\n Its definition is best understood side-by-side with the wrapper state\n interpretation (in weakestpre.v), but is in its own separate file to make it\n possible to only import [GC θ] and relevant SL resources without depending on\n the wrapper WP and state interp.\n *)\n\nClass wrapperGCtokGpre `{SI: indexT} Σ := WrapperGCtokGpre {\n wrapperG_locsetG :> ghost_varG Σ (gsetUR loc);\n wrapperG_addrmapG :> ghost_varG Σ (leibnizO addr_map);\n wrapperG_var_lstoreG :> ghost_varG Σ lstore;\n wrapperG_var_lloc_mapG :> ghost_varG Σ lloc_map;\n wrapperG_var_bool :> ghost_varG Σ (leibnizO bool);\n}.\n\nClass wrapperGCtokG `{SI: indexT} Σ := WrapperGCtokG {\n wrapperG_basics :> wrapperBasicsG Σ;\n wrapperG_inG :> wrapperGCtokGpre Σ;\n wrapperG_γζ : gname;\n wrapperG_γθ : gname;\n wrapperG_γχ : gname;\n wrapperG_γroots_set : gname;\n wrapperG_γat_init : gname;\n}.\n\nDefinition wrapperGCtokΣ {SI: indexT} : gFunctors :=\n #[ghost_varΣ (gsetUR loc); ghost_varΣ (leibnizO addr_map);\n ghost_varΣ lstore; ghost_varΣ lloc_map; ghost_varΣ (leibnizO bool)].\n\nGlobal Instance subG_wrapperGCtokGpre `{SI: indexT} Σ :\n subG wrapperGCtokΣ Σ → wrapperGCtokGpre Σ.\nProof. solve_inG. Qed.\n\nSection GCtoken.\nContext `{SI: indexT}.\nContext {Σ : gFunctors}.\nContext `{!heapG_ML Σ, !heapG_C Σ}.\nContext `{!wrapperGCtokG Σ}.\n\nDefinition GC (θ : addr_map) : iProp Σ :=\n ∃ (ζ ζfreeze ζσ ζvirt : lstore) (χ χvirt : lloc_map) (σMLvirt : store)\n (roots_s : gset addr) (roots_m : gmap addr lval),\n \"GCζ\" ∷ ghost_var wrapperG_γζ (1/2) ζ\n ∗ \"GCχ\" ∷ ghost_var wrapperG_γχ (1/2) χ\n ∗ \"GCθ\" ∷ ghost_var wrapperG_γθ (1/2) θ\n ∗ \"GCroots\" ∷ ghost_var wrapperG_γroots_set (1/2) roots_s\n ∗ \"GCinit\" ∷ ghost_var wrapperG_γat_init (1/2) false\n ∗ \"GCζvirt\" ∷ lstore_own_auth ζvirt\n ∗ \"GCσMLv\" ∷ state_interp (σMLvirt : language.language.state ML_lang)\n ∗ \"GCχvirt\" ∷ lloc_own_auth χvirt\n ∗ \"GCχNone\" ∷ ([∗ map] _↦ℓ ∈ pub_locs_in_lstore χvirt ζvirt, ℓ ↦M/)\n ∗ \"GCrootsm\" ∷ ghost_map_auth wrapperG_γroots_map 1 roots_m\n ∗ \"GCrootspto\" ∷ ([∗ map] a ↦ v ∈ roots_m, ∃ w, a ↦C w ∗ ⌜repr_lval θ v w⌝)\n ∗ \"%Hrootsdom\" ∷ ⌜dom roots_m = roots_s⌝\n ∗ \"%Hrootslive\" ∷ ⌜roots_are_live θ roots_m⌝\n ∗ \"%Hfreezeρ\" ∷ ⌜freeze_lstore ζ ζfreeze⌝\n ∗ \"%Hfreezeeq\" ∷ ⌜ζfreeze = ζσ ∪ ζvirt⌝\n ∗ \"%Hfreezedj\" ∷ ⌜ζσ ##ₘ ζvirt⌝\n ∗ \"%Hstore_blocks\" ∷ ⌜is_store_blocks χvirt σMLvirt ζσ⌝\n ∗ \"%Hother_blocks\" ∷ ⌜dom ζvirt ⊆ dom χvirt⌝\n ∗ \"%Hstore\" ∷ ⌜is_store χvirt ζfreeze σMLvirt⌝\n ∗ \"%Hχvirt\" ∷ ⌜expose_llocs χ χvirt⌝\n ∗ \"%Hχinj\" ∷ ⌜lloc_map_inj χ⌝ (* TODO redundant? *)\n ∗ \"%HGCOK\" ∷ ⌜GC_correct ζfreeze θ⌝.\n\nDefinition at_init := ghost_var wrapperG_γat_init (1/2) true.\n\nEnd GCtoken.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/interop/gctoken.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.17553807362342935, "lm_q1q2_score": 0.09324747269826822}} {"text": "(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n definitions from the previous chapter: *)\n\nRequire Export Basics.\n\n(** For the [Require Export] to work, you first need to use\n [coqc] to compile [Basics.v] into [Basics.vo]. This is like\n making a [.class] file from a [.java] file, or a [.o] file from a\n [.c] file. There are two ways to do it:\n\n - In CoqIDE:\n\n Open [Basics.v]. In the \"Compile\" menu, click on \"Compile\n Buffer\".\n\n - From the command line: Either\n\n [make Basics.vo]\n\n (assuming you've downloaded the whole LF directory and have a\n working [make] command) or\n\n [coqc Basics.v]\n\n (which should work from any terminal window).\n\n If you have trouble (e.g., if you get complaints about missing\n identifiers later in the file), it may be because the \"load path\"\n for Coq is not set up correctly. The [Print LoadPath.] command may\n be helpful in sorting out such issues.\n\n In particular, if you see a message like\n\n [Compiled library Foo makes inconsistent assumptions over\n library Coq.Init.Bar]\n\n you should check whether you have multiple installations of Coq on\n your machine. If so, it may be that commands (like [coqc]) that\n you execute in a terminal window are getting a different version of\n Coq than commands executed by Proof General or CoqIDE.\n\n One more tip for CoqIDE users: If you see messages like [Error:\n Unable to locate library Basics], a likely reason is\n inconsistencies between compiling things _within CoqIDE_ vs _using\n coqc_ from the command line. This typically happens when there are\n two incompatible versions of [coqc] installed on your system (one\n associated with CoqIDE, and one associated with [coqc] from the\n terminal). The workaround for this situation is compiling using\n CoqIDE only (i.e. choosing \"make\" from the menu), and avoiding\n using [coqc] directly at all. *)\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left, using an easy argument based on\n simplification. We also observed that proving the fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n n = n + 0.\n\n(** ... can't be done in the same simple way. Just applying\n [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through fine, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n n = n + 0.\nProof.\n intros n. destruct n as [| n'].\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** We could use [destruct n'] to get one step further, but,\n since [n] can be arbitrarily large, if we just go on like this\n we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n inductively defined sets, we usually need a more powerful\n reasoning principle: _induction_.\n\n Recall (from high school, a discrete math course, etc.) the\n _principle of induction over natural numbers_: If [P(n)] is some\n proposition involving a natural number [n] and we want to show\n that [P] holds for all numbers [n], we can reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same: we begin with the goal of proving\n [P(n)] for all [n] and break it down (by applying the [induction]\n tactic) into two separate subgoals: one where we must show [P(O)]\n and another where we must show [P(n') -> P(S n')]. Here's how\n this works for the theorem at hand: *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. Since there are two subgoals, the [as...] clause\n has two parts, separated by [|]. (Strictly speaking, we can omit\n the [as...] clause and Coq will choose names for us. In practice,\n this is a bad idea, as Coq's automatic choices tend to be\n confusing.)\n\n In the first subgoal, [n] is replaced by [0]. No new variables\n are introduced (so the first part of the [as...] is empty), and\n the goal becomes [0 = 0 + 0], which follows by simplification.\n\n In the second subgoal, [n] is replaced by [S n'], and the\n assumption [n' + 0 = n'] is added to the context with the name\n [IHn'] (i.e., the Induction Hypothesis for [n']). These two names\n are specified in the second part of the [as...] clause. The goal\n in this case becomes [S n' = (S n') + 0], which simplifies to\n [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\n\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** (The use of the [intros] tactic in these proofs is actually\n redundant. When applied to a goal that contains quantified\n variables, the [induction] tactic will automatically move them\n into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction) *)\n(** Prove the following using induction. You might need previously\n proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: mult_0_r *)\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m. induction n as[| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity. Qed.\n (* GRADE_THEOREM 0.5: plus_n_Sm *)\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. induction n as [|n' IHn'].\n - simpl. rewrite <- plus_n_O. reflexivity.\n - simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n(* GRADE_THEOREM 0.5: plus_comm *)\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [|n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n(* GRADE_THEOREM 0.5: plus_assoc *)\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus) *)\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n as [|n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_S) *)\n(** One inconvenient aspect of our definition of [evenb n] is the\n recursive call on [n - 2]. This makes proofs about [evenb n]\n harder when done by induction on [n], since we may need an\n induction hypothesis about [n - 2]. The following lemma gives an\n alternative characterization of [evenb (S n)] that works better\n with induction: *)\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n intros n. induction n as [|n' IHn'].\n - simpl. reflexivity.\n - rewrite -> IHn'. simpl. rewrite -> negb_involutive. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics [destruct]\n and [induction].\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n broken into a sequence of theorems, with later proofs referring to\n earlier theorems. But sometimes a proof will require some\n miscellaneous fact that is too trivial and of too little general\n interest to bother giving it its own top-level name. In such\n cases, it is convenient to be able to simply state and prove the\n needed \"sub-theorem\" right at the point where it is used. The\n [assert] tactic allows us to do this. For example, our earlier\n proof of the [mult_0_plus] theorem referred to a previous theorem\n named [plus_O_n]. We could instead use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (We can also name the assertion with [as] just as\n we did above with [destruct] and [induction], i.e., [assert (0 + n\n = n) as H].) Note that we surround the proof of this assertion\n with curly braces [{ ... }], both for readability and so that,\n when using Coq interactively, we can see more easily when we have\n finished this sub-proof. The second goal is the same as the one\n at the point where we invoke [assert] except that, in the context,\n we now have the assumption [H] that [0 + n = n]. That is,\n [assert] generates one subgoal where we must prove the asserted\n fact and a second subgoal where we can use the asserted fact to\n make progress on whatever we were trying to prove in the first\n place. *)\n\n(** Another example of [assert]... *)\n\n(** For example, suppose we want to prove that [(n + m) + (p + q)\n = (m + n) + (p + q)]. The only difference between the two sides of\n the [=] is that the arguments [m] and [n] to the first inner [+]\n are swapped, so it seems we should be able to use the\n commutativity of addition ([plus_comm]) to rewrite one into the\n other. However, the [rewrite] tactic is not very smart about\n _where_ it applies the rewrite. There are three uses of [+] here,\n and it turns out that doing [rewrite -> plus_comm] will affect\n only the _outer_ one... *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)... seems\n like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To use [plus_comm] at the point where we need it, we can introduce\n a local lemma stating that [n + m = m + n] (for the particular [m]\n and [n] that we are talking about here), prove this lemma using\n [plus_comm], and then use it to do the desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n { rewrite -> plus_comm. reflexivity. }\n rewrite -> H. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** What constitutes a successful proof of a mathematical claim?\n The question has challenged philosophers for millennia, but a\n rough and ready definition could be this: A proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true --\n an unassailable argument for the truth of [P]. That is, a proof\n is an act of communication.\n\n Acts of communication may involve different sorts of readers. On\n one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is that [P] can be mechanically\n derived from a certain set of formal logical rules, and the proof\n is a recipe that guides the program in checking this fact. Such\n recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n and will thus necessarily be _informal_. Here, the criteria for\n success are less clearly specified. A \"valid\" proof is one that\n makes the reader believe [P]. But the same proof may be read by\n many different readers, some of whom may be convinced by a\n particular way of phrasing the argument, while others may not be.\n Some readers may be particularly pedantic, inexperienced, or just\n plain thick-headed; the only way to convince them will be to make\n the argument in painstaking detail. But other readers, more\n familiar in the area, may find all this detail so overwhelming\n that they lose the overall thread; all they want is to be told the\n main ideas, since it is easier for them to fill in the details for\n themselves than to wade through a written presentation of them.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader.\n\n In practice, however, mathematicians have developed a rich set of\n conventions and idioms for writing about complex mathematical\n objects that -- at least within a certain community -- make\n communication fairly reliable. The conventions of this stylized\n form of communication give a fairly clear standard for judging\n proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can\n completely forget about informal ones! Formal proofs are useful\n in many ways, but they are _not_ very efficient ways of\n communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this. For a human, however, it\n is difficult to make much sense of it. We can use comments and\n bullets to show the structure a little more clearly... *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** ... and if you're used to Coq you may be able to step\n through the tactics one after the other in your mind and imagine\n the state of the context and goal stack at each point, but if the\n proof were even a little bit more complicated this would be next\n to impossible.\n\n A (pedantic) mathematician might write the proof something like\n this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n n + (m + p) = (n + m) + p.\n\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n\n 0 + (m + p) = (0 + m) + p.\n\n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n\n n' + (m + p) = (n' + m) + p.\n\n We must show\n\n (S n') + (m + p) = ((S n') + m) + p.\n\n By the definition of [+], this follows from\n\n S (n' + (m + p)) = S ((n' + m) + p),\n\n which is immediate from the induction hypothesis. _Qed_. *)\n\n(** The overall form of the proof is basically similar, and of\n course this is no accident: Coq has been designed so that its\n [induction] tactic generates the same sub-goals, in the same\n order, as the bullet points that a mathematician would write. But\n there are significant differences of detail: the formal proof is\n much more explicit in some ways (e.g., the use of [reflexivity])\n but much less explicit in others (in particular, the \"proof state\"\n at any given point in the Coq proof is completely implicit,\n whereas the informal proof reminds the reader several times where\n things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof:\n\n Theorem: Addition is commutative.\n\n Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n\n Theorem: [true = beq_nat n n] for any [n].\n\n Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction on [plus_swap]. *)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_comm. \n assert (H: n + p = p + n).\n {rewrite -> plus_comm. reflexivity. }\n rewrite -> H.\n rewrite -> plus_assoc.\n reflexivity.\nQed.\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one. You may find that [plus_swap] comes in\n handy.) *)\n\nTheorem mult_n_SO : forall n:nat,\n n = n * 1.\nProof.\n intros n. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed. \n\nTheorem mult_n_Sm : forall n m : nat,\n n * S m = n * m + n.\n (* n * S m = n + (n * m). *)\nProof.\n intros n m. induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. rewrite -> plus_n_Sm. rewrite -> plus_assoc. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros n m. induction n as [|n' IHn'].\n - rewrite -> mult_0_r. reflexivity.\n - simpl. rewrite -> mult_n_Sm. rewrite -> plus_comm. rewrite -> IHn'. reflexivity.\nQed. \n \n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n true = leb n n.\nProof.\n intros n. induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity. \nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n intros n. induction n as [|n' IHn'].\n - reflexivity.\n - simpl. reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n intros b. destruct b.\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n leb n m = true -> leb (p + n) (p + m) = true.\nProof.\n intros n m p H.\n induction p as [|p' IHp'].\n - simpl. rewrite -> H. reflexivity.\n - simpl. rewrite -> IHp'. reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n intros n. induction n as [|n' IHn'].\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros n. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite <- plus_n_O. reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros [] [].\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* intros n m p. induction p as [|p' IHp']. *)\n (* - rewrite -> mult_0_r. rewrite -> mult_0_r. rewrite -> mult_0_r. reflexivity. *)\n intros n m p. induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite -> IHn'. rewrite -> plus_assoc. reflexivity.\nQed. \n\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p.\n induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite -> mult_plus_distr_r. rewrite->IHn'. reflexivity.\nQed. \n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\n(** Prove the following theorem. (Putting the [true] on the left-hand\n side of the equality may look odd, but this is how the theorem is\n stated in the Coq standard library, so we follow suit. Rewriting\n works equally well in either direction, so we will have no problem\n using the theorem no matter which way we state it.) *)\n\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\nProof.\n intros n. induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed. \n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to: [replace (t) with (u)]\n replaces (all copies of) expression [t] in the goal by expression\n [u], and generates [t = u] as an additional subgoal. This is often\n useful when a plain [rewrite] acts on the wrong part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p. induction m as [|n' IHm'].\n - simpl. reflexivity.\n - simpl. rewrite <- plus_n_Sm. rewrite -> IHm'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (binary_commute) *)\n(** Recall the [incr] and [bin_to_nat] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that the following diagram commutes:\n\n incr\n bin ----------------------> bin\n | |\n bin_to_nat | | bin_to_nat\n | |\n v v\n nat ----------------------> nat\n S\n\n That is, incrementing a binary number and then converting it to\n a (unary) natural number yields the same result as first converting\n it to a natural number and then incrementing.\n Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n Before you start working on this exercise, copy the definitions\n from your solution to the [binary] exercise here so that this file\n can be graded on its own. If you want to change your original\n definitions to make the property easier to prove, feel free to\n do so! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n there to complete this one; please copy them to this file to make\n it self contained for grading.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, this is not true!\n Explain what the problem is.\n\n (c) Define a \"direct\" normalization function -- i.e., a function\n [normalize] from binary numbers to binary numbers such that,\n for any binary number b, converting to a natural and then back\n to binary yields [(normalize b)]. Prove it. (Warning: This\n part is tricky!)\n\n Again, feel free to change your earlier definitions if this helps\n here. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n", "meta": {"author": "luckyuro", "repo": "sf_exercise", "sha": "4dcdb4bfc24338064698de6af0fa6c67604bb7d1", "save_path": "github-repos/coq/luckyuro-sf_exercise", "path": "github-repos/coq/luckyuro-sf_exercise/sf_exercise-4dcdb4bfc24338064698de6af0fa6c67604bb7d1/lf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.1943678016853152, "lm_q1q2_score": 0.09111780643304604}} {"text": "(* this preamble takes some time to load, you may want to\n run while the teacher does his welcome bla bla... *)\nFrom elpi Require Import elpi.\nFrom HB Require Import structures.\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n-----------------------------------------------------\n#
#\n** Objective of this school\n\n Give you access to the \n #Mathematical Components library#\n\n - formalization techniques\n - proof language\n - familiarize with some theories\n\n\n#
#\n\n----------------------------------------------------------\n#
#\n** Why another library? Why another language?\n\n - large, consistent, library organized as a programming language\n library (interfaces, overload, naming conventions, ...)\n - maintainable in the long term (compact, stable, ...)\n - validated on large formalization projects\n\n** Captatio benevolentiae: this is not standard Coq\n\n - things are done differently, very differently, than usual\n - it is not easy to appreciate the benefits on small examples,\n but we will try hard ;-)\n - not enough time to explain eveything, we may focus on\n intuition rather than technical details (aka handwaving)\n\n#
(notes)
#\nThe mathematical components library was used to formalize the\n#\nOdd Order Theorem (Feit Thompson)\n#, literally a 250 pages book. Such proof amounts to 40k lines\nof Coq scripts, on top of 120k lines of mathematical components.\nThe library has been maintained for more than 10 years now.\n#
#\n\n#
#\n\n----------------------------------------------------------\n#
#\n** Roadmap of the first lesson\n\n - formalization technique: boolean reflection (aka small scale reflection)\n - proof language: basic SSReflect (part 1)\n - libraries: conventions, notations, ad-hoc polymorphism\n\n#
#\n\n----------------------------------------------------------\n----------------------------------------------------------\n#
#\n** Boolean reflection\n\n - when a concept is \"computable\" we represent it as a\n computable function (a program), not as an inductive relation\n - Coq knows how to compute, even symbolically, and computation is\n a very stable form of automation\n - expressions in bool are a \"simple\" concept in type theory\n - Excluded Middle (EM) just holds\n - Uniqueness of Identity Proofs holds uniformly\n\n#
#\n*)\n\nModule BooleanReflectionSanbox.\n(**\n#
#\n\n#
(notes)
#\nDecideable predicates are quite common in both computer\nscience and mathematics. On this class or predicates the\nexcluded middle principle needs not to be an axiom; in particular\nits computational content can be expressed inside Coq as a program.\nWriting this program in Coq may be non trivial (e.g. being a prime\nnumber requires some effort) but once the program is written it\nprovides notable benefits. First, one can use the program as a\ndecision procedure for closed terms. Second, the proofs of such\npredicate are small. E.g. a proof of [prime 17 = true] is just\n[erefl true].\n\nLast, the proofs of these predicates are irrelevant (i.e. unique).\nThis means that we can form subtypes without problems. E.g. the\nin habitants of the subtype of prime numbers [{ x | prime x = true }]\nare pairs, the number (relevant) and the proof (always [erefl true]).\nHence when we compare these pairs we can ignore the proof part, that is,\nprime numbers behave exactly as numbers.\n\nA way to see this is that we are using Coq as a logical framework\nand that we are setting up an environment where one can\nreason classically (as in set theory, EM, subsets..) but also take\nadvantage of computations as valid reasoning steps (unlike set theory TT\nmanipulates effective programs)\n#
#\n\n#
#\n----------------------------------------------------------\n#
#\n\n** The first predicate: leq\n - order relation on [nat] is a program\n - [if-is-then] syntax (simply a 2-way match-with-end)\n - [.+1] syntax (postfix notations [.something] are recurrent)\n\n#
#\n*)\nFixpoint leq (n m : nat) : bool :=\n if n is p.+1 then\n if m is q.+1 then leq p q\n else false\n else true.\n\n(* Coq prints it \"raw\" *) \nPrint leq.\n\nArguments leq !n !m.\nInfix \"<=\" := leq.\n\n(** \n#
#\n\n#
(notes)
#\nWe give a taste of boolean reflection by examples\n - these examples, to stay simple, are a bit artificial\n - in the library the same concepts are defeined in a slightly\n different way, but following the same ideas\n#
#\n\n#
#\n------------------------------------------------------\n#
#\n ** The first proof about leq\n - [... = true] to \"state\" something\n - proof by computation\n - [by []] to say, provable by trivial means (no mean is inside []).\n - [by tac] to say: tac must solve the goal (up to trivial leftovers)\n\n#
#\n*)\nLemma leq0n n : (0 <= n) = true.\nProof. (* compute. *) by []. Qed.\n\n(**\n#
#\n\n#
(notes)
#\nNote that [0 <= n] is a symbolic expression, [n] is\nunknown, but Coq can still compute its value\n#
#\n\n#
#\n------------------------------------------------------\n#
#\n** Another lemma about leq\n - equality as a double implication\n - naming convention\n\n#
#\n*)\nLemma leqSS n m : (n.+1 <= m.+1) = (n <= m).\nProof. (* simpl. *) by []. Qed.\n\n(**\n#
#\n\n#
(notes)
#\nAgain, Coq can compute on symbolic expressions\n#
#\n\n#
#\n------------------------------------------------------\n#
#\n** It is nice to have a lemma, it is even better to don't need it\n - [elim] with naming and automatic clear of [n]\n - indentation for subgoals\n - no need to mention lemmas proved by computation\n - [apply], [rewrite]\n#
#\n*)\nLemma leqnn n : (n <= n) = true.\nProof.\n(*#\nelim: n => [|m IHm].\n by apply: leq0n. (* the first lemma we proved by computation *)\nrewrite leqSS. (* the second lemma we proved by computation *)\nrewrite IHm.\n#*)\nby elim: n. Qed. (* computation is for free *)\n\n(** \n#
#\n\n#
#\n------------------------------------------------------\n#
#\n*** Connectives for booleans\n - since we want statements be in bool, we need to\n be able to form longer sentences with our basic \n predicates (like [leq]) and stay in bool\n - notations [&&], [||] and [~~]\n\n#
#\n*)\nDefinition andb (b1 b2 : bool) : bool :=\n if b1 then b2 else false.\nInfix \"&&\" := andb.\n\nDefinition orb (b1 b2 : bool) : bool :=\n if b1 then true else b2.\nInfix \"||\" := orb.\n\nDefinition negb b : bool :=\n if b then false else true.\nNotation \"~~ b\" := (negb b).\n\n(** \n#
#\n\n#
#\n------------------------------------------------------\n#
#\n*** Proofs by truth tables\n - we can use EM to reason about boolean predicates\n and connectives\n - [move=> name]\n - [case:]\n - [move=> /=]\n - naming convention: [C] suffix\n#
#\n*)\nLemma andbC : forall b1 b2, (b1 && b2) = (b2 && b1).\nProof.\n(*\nmove=> b1 b2. (* name hyps *)\ncase: b1. (* reason on b1 by cases *)\n move=> /=. (* simplify the goal *)\n by case: b2. (* reason on b2 by cases *)\nby case: b2. (* reason on b2 by cases *)\n*)\nby move=> b1 b2; case: b1; case: b2. Qed.\n\nEnd BooleanReflectionSanbox.\n\n(** \n#
#\n\n#
(notes)
#\nNaming convention is key to find lemmas in a large library.\nIt is worth mentioning here\n- [C] for commutativity\n- [A] for associativity\n- [K] for cancellation\n\nWhen doing \"truth table\" proofs, it is handy to\ncombine calls to [case] with [;], as we do in the last line.\n#
#\n\n#
#\n------------------------------------------------------\n#
#\n** Recap: formalization approach and basic tactics\n - boolean predicates and connectives\n - think \"up to\" computation\n - [case], [elim], [move], [rewrite]\n - [if-is-then-else], [.+1], [&&], [||], [~~]\n - naming convetions [C], [foo0n], [foon0], [fooSS]\n\n#
#\n------------------------------------------------------\n------------------------------------------------------\n#
#\n** The real MathComp library\n \n Things to know:\n - [Search] something inside library\n - patterns, eg [ _ <= _]\n - names, eg [\"SS\"]\n - constants, eg [leq]\n - [a < b] is a notation for [a.+1 <= b]\n - [_ == _] stands for computable equality (overloaded)\n - [_ != _] is [~~ (_ == _)]\n - [is_true] coercion\n - [rewrite /concept] to unfold\n\n#
#\n*)\nSearch (_ <= _) inside ssrnat.\nSearch \"SS\" inside ssrnat.\nLocate \"_ < _\".\nCheck (forall x, x.+1 <= x).\nSearch \"orb\" \"C\".\nPrint commutative. (* for consistency *)\nCheck (3 == 4) || (3 <= 4).\nEval compute in (3 == 4) || (3 <= 4).\nCheck (true == false). (* overloaded *)\nCheck (3 != 4). (* with negation ~~ *)\n\nLemma test_is_true_coercion : true.\nProof. rewrite /is_true. by []. Qed.\n\n(**\n#
#\n\n#
(notes)
#\nUnfortunately [Search] does not work \"up to\" definitions\nlike [commutative]. The pattern [(_ + _ = _ + _)] won't work.\nIt's sad, it may be fidex one day, but now you know it.\nSearch for \"C\" if you need a commutativity law.\n#
#\n\n\n#
#\n-------------------------------------------------------------\n#
#\n** Equality\n - privileged role (many lemmas are stated with [=] or [is_true])\n - the [eqP] view: \"is_true (a == b) <-> a = b\"\n - [move=> /eqP] (both directions, on hyps)\n - [apply/eqP] (both directions, on goal)\n - [move=> /view name] to name after applying the view\n - notation [.*2]\n - [rewrite lem1 lem2] to chain rules\n\n#
#\n*)\nLemma test_eqP (n m : nat) :\n n == m -> n.+1 + m.+1 = m.+1.*2.\nProof.\n(*#\nCheck eqP. (* reflect is, for now, like [<->] *)\nmove=> /eqP. move=> /eqP. move=> /eqP. move=> Enm. (* back and forth *) \napply/eqP. apply/eqP. (* back and forth *)\nrewrite Enm.\nSearch (_ + _) _.*2 inside ssrnat. (* look for lemmas linking + and .*2 *)\nby apply: addnn.\n#*)\n(* clean script *)\nby move=> /eqP Enm; rewrite Enm -addnn. Qed.\n\n\n(**\n#
#\n\n#
#\n-------------------------------------------------------------\n#
#\n ** A little bit of gimmicks\n - connectives like [&&] have a view as well\n - [andP] and [[]]\n - [move:] to move back down to the goal\n#
#\n*)\nLemma test_andP (b1 b2 : bool) :\n b1 && (b1 == b2) -> b2.\nProof.\n(*\nmove=> /andP Hb1b2. (* process [&&] *)\ncase: Hb1b2. (* separate hyps *)\nmove=> Hb1 Hb2. (* name both *)\n(* too boring *)\n*)\nmove=> /andP[Hb1 Hb12]. (* process [&&] and separate*)\n\nmove: Hb12. (* move down *)\nmove=> /eqP Hb2. (* process with view *)\nby rewrite -Hb2 Hb1. (* conclude, remmark hidden [.. = true] *)\nQed.\n\n(**\n#
#\n\n#
#\n-------------------------------------------------------------\n#
#\n ** Forward steps:\n - [have]\n - [move: (f x)]\n - [move=> {}H]\n#
#\n*)\nLemma test_have (b1 b2 b3 : bool) :\n b1 -> b2 -> (b1 && b2 -> b3) -> b3 && b1.\nProof.\nmove=> Hb1 Hb2 Hb3.\nhave Hb1b2 : b1 && b2. (* like Lemma, but inside a proof *)\n by rewrite Hb1 Hb2.\nmove: (Hb3 Hb1b2). (* move down a specialized Hb3 *)\nmove=> {}Hb3. (* replace Hb3 *)\nby rewrite Hb3 Hb1.\nQed.\n\n(**\n#
#\n\n#
(notes)
#\nUnlike with [_ /\\ _] we rarely use [split] to prove\na conjunction. It is typically simpler to rewrite\n[_ && _] to true.\n#
#\n\n\n#
#\n--------------------------------------------------------\n--------------------------------------------------------\n#
#\n** Sequences\n - many notations\n\n#
#\n*)\nCheck [::].\nCheck [:: 3 ; 4].\nCheck [::] ++ [:: true ; false].\nEval compute in [seq x.+1 | x <- [:: 1; 2; 3]]. (* map *)\nEval compute in [seq x <- [::3; 4; 5] | odd x ]. (* filter *)\nEval compute in rcons [:: 4; 5] 3.\nEval compute in all odd [:: 3; 5].\n\nModule polylist.\n\n(**\n#
#\n\n#
(notes)
#\nNotations for sequentes are documented the header of the \n#seq.v# file.\n[rcons] is like [cons] but the new element is placed in the last position.\nIndeed it is not a real constructor, but rather a function that appends the singleton list.\nThis special case of append has its own name and collection of theorems.\n#
#\n\n#
#\n--------------------------------------------------------\n#
#\n** Polymorphic lists\n - no assumptions on T\n - we can use [=> ... //] to kill a goal\n - we can use [=> ... /=] to simplify a goal\n\n#
#\n*)\nLemma size_cat T (s1 s2 : seq T) : size (s1 ++ s2) = size s1 + size s2.\nProof.\nelim: s1 => [//|x s1 IH /=].\n (*by [].*)\n(*move=> /=.*)\nby rewrite IH.\nQed.\n\nEnd polylist.\n\n(** \n#
#\n\n#
#\n--------------------------------------------------------\n#
#\n** Ad-hoc polymorphic lists\n - [T : Type |- l : list T] v.s. [T : eqType |- l : list T]\n - [eqType] means: a type with a decidable equality [_ == _]\n - if [T] is an [eqType] then [list T] also is an [eqType]\n - [x \\in l] requires the type of [x] to be an [eqType]\n - overloaded as [(_ == _)]\n#
#\n*)\n\nFail Check forall T : Type, forall x : T, x == x .\nFail Check forall T : Type, forall x : T, x \\in [:: x ].\n\n Check forall T : eqType, forall x : T, x == x.\n Check forall T : eqType, forall x : T, x \\in [:: x ].\n\n(* overloaded and computable *)\nEval compute in 3 \\in [:: 7; 4; 3].\nEval compute in true \\in [:: false; true; true].\n\n(**\n#
#\n\n#
(notes)
#\nAd-hoc polymorphism is a well established concept in object\noriented programming languages and as well in functional\nlanguages equipped with type classes like Haskell.\nWhenever [T] is an [eqType], we have a comparison\nfunction for all terms of type [T] ([x] in the example above).\n#
#\n\n#
#\n--------------------------------------------------------\n#
#\n** Working with the [\\in] notation\n - pushing [\\in] with [inE]\n - rewrite flag [!]\n - [rewrite !inE] idiom\n - [\\notin] notation\n#
#\n*)\nLemma test_in l : 3 \\in [:: 4; 5] ++ l -> l != [::].\nProof.\nrewrite inE.\nrewrite inE.\n(*rewrite !inE*)\nmove=> /=.\napply: contraL. (* l = [::] is in conflict with 3 \\in l *)\nmove=> /eqP El.\nrewrite El.\n(*compute*)\nby [].\nQed.\n\n(**\n#
#\n\n#
#\n\n----\n#
#\n** References for this lesson\n - SSReflect #manual#\n - documentation of the\n #library#\n - in particular #ssrbool#\n - in particular #ssrnat#\n - #Book# (draft) on the Mathematical Components library\n ##\n#
# \n*)\n", "meta": {"author": "gares", "repo": "math-comp-school-2022", "sha": "d7f18a5c9afd2659426be21ef54bec119451446c", "save_path": "github-repos/coq/gares-math-comp-school-2022", "path": "github-repos/coq/gares-math-comp-school-2022/math-comp-school-2022-d7f18a5c9afd2659426be21ef54bec119451446c/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1801066596856071, "lm_q1q2_score": 0.09005332984280355}} {"text": "(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n definitions from the previous chapter: *)\n\nFrom LF Require Export Basics_done.\n\n(** For the [Require Export] to work, you first need to use\n [coqc] to compile [Basics.v] into [Basics.vo]. This is like\n making a [.class] file from a [.java] file, or a [.o] file from a\n [.c] file. There are two ways to do it:\n\n - In CoqIDE:\n\n Open [Basics.v]. In the \"Compile\" menu, click on \"Compile\n Buffer\".\n\n - From the command line: Either\n\n [make Basics.vo]\n\n (assuming you've downloaded the whole LF directory and have a\n working [make] command) or\n\n [coqc Basics.v]\n\n (which should work regardless).\n\n If you have trouble (e.g., if you get complaints about missing\n identifiers later in the file), it may be because the \"load path\"\n for Coq is not set up correctly. The [Print LoadPath.] command may\n be helpful in sorting out such issues.\n\n In particular, if you see a message like\n\n [Compiled library Foo makes inconsistent assumptions over\n library Coq.Init.Bar]\n\n you should check whether you have multiple installations of Coq on\n your machine. If so, it may be that commands (like [coqc]) that\n you execute in a terminal window are getting a different version of\n Coq than commands executed by Proof General or CoqIDE.\n\n One more tip for CoqIDE users: If you see messages like [Error:\n Unable to locate library Basics], a likely reason is\n inconsistencies between compiling things _within CoqIDE_ vs _using\n coqc_ from the command line. This typically happens when there are\n two incompatible versions of [coqc] installed on your system (one\n associated with CoqIDE, and one associated with [coqc] from the\n terminal). The workaround for this situation is compiling using\n CoqIDE only (i.e. choosing \"make\" from the menu), and avoiding\n using [coqc] directly at all. *)\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left, using an easy argument based on\n simplification. We also observed that proving the fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n n = n + 0.\n\n(** ... can't be done in the same simple way. Just applying\n [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through fine, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n n = n + 0.\nProof.\n intros n. destruct n as [| n'].\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** We could use [destruct n'] to get one step further, but,\n since [n] can be arbitrarily large, if we just go on like this\n we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n inductively defined sets, we usually need a more powerful\n reasoning principle: _induction_.\n\n Recall (from high school, a discrete math course, etc.) the\n _principle of induction over natural numbers_: If [P(n)] is some\n proposition involving a natural number [n] and we want to show\n that [P] holds for all numbers [n], we can reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same: we begin with the goal of proving\n [P(n)] for all [n] and break it down (by applying the [induction]\n tactic) into two separate subgoals: one where we must show [P(O)]\n and another where we must show [P(n') -> P(S n')]. Here's how\n this works for the theorem at hand: *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. Since there are two subgoals, the [as...] clause\n has two parts, separated by [|]. (Strictly speaking, we can omit\n the [as...] clause and Coq will choose names for us. In practice,\n this is a bad idea, as Coq's automatic choices tend to be\n confusing.)\n\n In the first subgoal, [n] is replaced by [0]. No new variables\n are introduced (so the first part of the [as...] is empty), and\n the goal becomes [0 = 0 + 0], which follows by simplification.\n\n In the second subgoal, [n] is replaced by [S n'], and the\n assumption [n' + 0 = n'] is added to the context with the name\n [IHn'] (i.e., the Induction Hypothesis for [n']). These two names\n are specified in the second part of the [as...] clause. The goal\n in this case becomes [S n' = (S n') + 0], which simplifies to\n [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\n\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** (The use of the [intros] tactic in these proofs is actually\n redundant. When applied to a goal that contains quantified\n variables, the [induction] tactic will automatically move them\n into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction) *)\n(** Prove the following using induction. You might need previously\n proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. induction n as [| n' IHn'].\n - (* n = 0 *)\n rewrite -> plus_O_n. rewrite <- plus_n_O. reflexivity.\n - (* n = S n' *)\n simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p.\n induction n as [| n' IHn'].\n - rewrite -> plus_O_n. rewrite -> plus_O_n.\n reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus) *)\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_S) *)\n(** One inconvenient aspect of our definition of [evenb n] is the\n recursive call on [n - 2]. This makes proofs about [evenb n]\n harder when done by induction on [n], since we may need an\n induction hypothesis about [n - 2]. The following lemma gives an\n alternative characterization of [evenb (S n)] that works better\n with induction: *)\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n induction n as [| n' IHn'].\n - reflexivity.\n - rewrite -> IHn'. rewrite -> negb_involutive. simpl. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics [destruct]\n and [induction].\n\n(* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_destruct_induction : option (prod nat string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n broken into a sequence of theorems, with later proofs referring to\n earlier theorems. But sometimes a proof will require some\n miscellaneous fact that is too trivial and of too little general\n interest to bother giving it its own top-level name. In such\n cases, it is convenient to be able to simply state and prove the\n needed \"sub-theorem\" right at the point where it is used. The\n [assert] tactic allows us to do this. For example, our earlier\n proof of the [mult_0_plus] theorem referred to a previous theorem\n named [plus_O_n]. We could instead use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (We can also name the assertion with [as] just as\n we did above with [destruct] and [induction], i.e., [assert (0 + n\n = n) as H].) Note that we surround the proof of this assertion\n with curly braces [{ ... }], both for readability and so that,\n when using Coq interactively, we can see more easily when we have\n finished this sub-proof. The second goal is the same as the one\n at the point where we invoke [assert] except that, in the context,\n we now have the assumption [H] that [0 + n = n]. That is,\n [assert] generates one subgoal where we must prove the asserted\n fact and a second subgoal where we can use the asserted fact to\n make progress on whatever we were trying to prove in the first\n place. *)\n\n(** Another example of [assert]... *)\n\n(** For example, suppose we want to prove that [(n + m) + (p + q)\n = (m + n) + (p + q)]. The only difference between the two sides of\n the [=] is that the arguments [m] and [n] to the first inner [+]\n are swapped, so it seems we should be able to use the\n commutativity of addition ([plus_comm]) to rewrite one into the\n other. However, the [rewrite] tactic is not very smart about\n _where_ it applies the rewrite. There are three uses of [+] here,\n and it turns out that doing [rewrite -> plus_comm] will affect\n only the _outer_ one... *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)... seems\n like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To use [plus_comm] at the point where we need it, we can introduce\n a local lemma stating that [n + m = m + n] (for the particular [m]\n and [n] that we are talking about here), prove this lemma using\n [plus_comm], and then use it to do the desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n { rewrite -> plus_comm. reflexivity. }\n rewrite -> H. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** What constitutes a successful proof of a mathematical claim?\n The question has challenged philosophers for millennia, but a\n rough and ready definition could be this: A proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true --\n an unassailable argument for the truth of [P]. That is, a proof\n is an act of communication.\n\n Acts of communication may involve different sorts of readers. On\n one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is that [P] can be mechanically\n derived from a certain set of formal logical rules, and the proof\n is a recipe that guides the program in checking this fact. Such\n recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n and will thus necessarily be _informal_. Here, the criteria for\n success are less clearly specified. A \"valid\" proof is one that\n makes the reader believe [P]. But the same proof may be read by\n many different readers, some of whom may be convinced by a\n particular way of phrasing the argument, while others may not be.\n Some readers may be particularly pedantic, inexperienced, or just\n plain thick-headed; the only way to convince them will be to make\n the argument in painstaking detail. But other readers, more\n familiar in the area, may find all this detail so overwhelming\n that they lose the overall thread; all they want is to be told the\n main ideas, since it is easier for them to fill in the details for\n themselves than to wade through a written presentation of them.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader.\n\n In practice, however, mathematicians have developed a rich set of\n conventions and idioms for writing about complex mathematical\n objects that -- at least within a certain community -- make\n communication fairly reliable. The conventions of this stylized\n form of communication give a fairly clear standard for judging\n proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can\n completely forget about informal ones! Formal proofs are useful\n in many ways, but they are _not_ very efficient ways of\n communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this. For a human, however, it\n is difficult to make much sense of it. We can use comments and\n bullets to show the structure a little more clearly... *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** ... and if you're used to Coq you may be able to step\n through the tactics one after the other in your mind and imagine\n the state of the context and goal stack at each point, but if the\n proof were even a little bit more complicated this would be next\n to impossible.\n\n A (pedantic) mathematician might write the proof something like\n this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n n + (m + p) = (n + m) + p.\n\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n\n 0 + (m + p) = (0 + m) + p.\n\n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n\n n' + (m + p) = (n' + m) + p.\n\n We must show\n\n (S n') + (m + p) = ((S n') + m) + p.\n\n By the definition of [+], this follows from\n\n S (n' + (m + p)) = S ((n' + m) + p),\n\n which is immediate from the induction hypothesis. _Qed_. *)\n\n(** The overall form of the proof is basically similar, and of\n course this is no accident: Coq has been designed so that its\n [induction] tactic generates the same sub-goals, in the same\n order, as the bullet points that a mathematician would write. But\n there are significant differences of detail: the formal proof is\n much more explicit in some ways (e.g., the use of [reflexivity])\n but much less explicit in others (in particular, the \"proof state\"\n at any given point in the Coq proof is completely implicit,\n whereas the informal proof reminds the reader several times where\n things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof:\n\n Theorem: Addition is commutative.\n\n Proof: (* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_plus_comm_informal : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n\n Theorem: [true = beq_nat n n] for any [n].\n\n Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction on [plus_swap]. *)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (H: n + m = m + n). { rewrite -> plus_comm. reflexivity. }\n rewrite -> H.\n reflexivity.\nQed.\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one. You may find that [plus_swap] comes in\n handy.) *)\n\nTheorem mult_n_1 : forall n : nat,\n n * 1 = n.\nProof.\n intros n.\n induction n as [| n' IHn'].\n - rewrite -> mult_0_l. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mult_expand : forall m n : nat,\n n + n * m = n * S m.\nProof.\n intros m n.\n induction n as [| n' IHn'].\n - rewrite -> mult_0_l. rewrite -> mult_0_l. rewrite plus_O_n. reflexivity.\n - simpl.\n rewrite -> plus_assoc.\n assert (H: n' + m = m + n').\n { rewrite -> plus_comm. reflexivity. }\n rewrite -> H.\n rewrite <- plus_assoc.\n rewrite -> IHn'.\n reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros m n.\n induction m as [| m' IHm'].\n - rewrite -> mult_0_l. rewrite -> mult_0_r. reflexivity.\n - simpl.\n rewrite <- mult_expand.\n rewrite -> IHm'.\n reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n true = leb n n.\nProof.\n induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n intros n.\n simpl.\n reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n intros b.\n destruct b.\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n leb n m = true -> leb (p + n) (p + m) = true.\nProof.\n intros n m p H.\n induction p as [| p' IHp'].\n - simpl. rewrite -> H. reflexivity.\n - simpl. rewrite -> IHp'. reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n intros n.\n simpl. reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros n. simpl. rewrite plus_n_O. reflexivity. Qed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros [] [].\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros n m p.\n induction p as [| p' IHp'].\n - rewrite -> mult_0_r. rewrite -> mult_0_r. rewrite -> mult_0_r. rewrite -> plus_O_n. reflexivity.\n - rewrite <- mult_expand. rewrite <- mult_expand. rewrite <- mult_expand.\n rewrite -> IHp'.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (H: n + n * p' + m = n + m + n * p').\n {\n rewrite -> plus_comm.\n rewrite -> plus_assoc.\n assert (H1 : m + n = n + m). { rewrite -> plus_comm. reflexivity. }\n rewrite -> H1.\n reflexivity.\n }\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p.\n induction n as [| n' IHn'].\n - rewrite -> mult_0_l. rewrite -> mult_0_l. reflexivity.\n - simpl.\n rewrite -> mult_plus_distr_r.\n rewrite -> IHn'.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\n(** Prove the following theorem. (Putting the [true] on the left-hand\n side of the equality may look odd, but this is how the theorem is\n stated in the Coq standard library, so we follow suit. Rewriting\n works equally well in either direction, so we will have no problem\n using the theorem no matter which way we state it.) *)\n\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\nProof.\n intros n.\n induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to: [replace (t) with (u)]\n replaces (all copies of) expression [t] in the goal by expression\n [u], and generates [t = u] as an additional subgoal. This is often\n useful when a plain [rewrite] acts on the wrong part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n induction n as [|n' IHn'].\n - rewrite -> plus_O_n. rewrite -> plus_O_n. reflexivity.\n - rewrite -> plus_assoc. rewrite -> plus_assoc.\n replace (S n' + m) with (m + S n').\n reflexivity.\n rewrite -> plus_comm.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (binary_commute) *)\n(** Recall the [incr] and [bin_to_nat] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that the following diagram commutes:\n\n incr\n bin ----------------------> bin\n | |\n bin_to_nat | | bin_to_nat\n | |\n v v\n nat ----------------------> nat\n S\n\n That is, incrementing a binary number and then converting it to\n a (unary) natural number yields the same result as first converting\n it to a natural number and then incrementing.\n Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n Before you start working on this exercise, copy the definitions\n from your solution to the [binary] exercise here so that this file\n can be graded on its own. If you want to change your original\n definitions to make the property easier to prove, feel free to\n do so! *)\n\nTheorem bin_to_nat_pres_incr : forall n : bin,\n S (bin_to_nat n) = bin_to_nat (incr n).\nProof.\n intros n.\n induction n as [|n' | n'' IHn''].\n - simpl. reflexivity.\n - simpl.\n rewrite -> plus_comm.\n reflexivity.\n - simpl.\n rewrite <- IHn''.\n rewrite -> plus_comm.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_commute : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n there to complete this one; please copy them to this file to make\n it self contained for grading.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, this is not true!\n Explain what the problem is.\n\n (c) Define a \"direct\" normalization function -- i.e., a function\n [normalize] from binary numbers to binary numbers such that,\n for any binary number b, converting to a natural and then back\n to binary yields [(normalize b)]. Prove it. (Warning: This\n part is tricky!)\n\n Again, feel free to change your earlier definitions if this helps\n here. *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse : option (prod nat string) := None.\n(** [] *)\n\n\n", "meta": {"author": "maximsmol", "repo": "sf-lf", "sha": "94ea1bb7663d913a2e69201e7a32111b08c75e92", "save_path": "github-repos/coq/maximsmol-sf-lf", "path": "github-repos/coq/maximsmol-sf-lf/sf-lf-94ea1bb7663d913a2e69201e7a32111b08c75e92/Induction_done.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.19682619657611938, "lm_q1q2_score": 0.08997648128845032}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(* DROP *)\n\n(* ################################################################# *)\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward.\n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (mostly works), and Scheme (a bit\n out of date). *)\n\nRequire Coq.extraction.Extraction.\nExtraction Language OCaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ################################################################# *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ################################################################# *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we need a few\n magic declarations to set up the right correspondence between Coq\n strings and lists of OCaml characters. *)\n\nRequire Import Ascii String.\nExtract Inductive ascii => char\n[\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))\"\n]\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))\".\nExtract Constant zero => \"'\\000'\".\nExtract Constant one => \"'\\001'\".\nExtract Constant shift =>\n \"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)\".\nExtract Inlined Constant ascii_dec => \"(=)\".\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nRequire Import Imp.\nRequire Import ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ################################################################# *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(* ################################################################# *)\n(** * Going Further *)\n\n(** Further details about extraction can be found in the Extract\n chapter in _Verified Functional Algorithms_ (_Software\n Foundations_ volume 3). *)\n\n(* /DROP *)\n\n(** $Date: 2017-05-22 11:43:34 -0400 (Mon, 22 May 2017) $ *)\n", "meta": {"author": "kazimuth", "repo": "6.826", "sha": "74e9eb7dbe352394fae68e988fe338195969ede9", "save_path": "github-repos/coq/kazimuth-6.826", "path": "github-repos/coq/kazimuth-6.826/6.826-74e9eb7dbe352394fae68e988fe338195969ede9/lf/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.17328821019878957, "lm_q1q2_score": 0.08664410509939478}} {"text": "(** * Preface *)\n\n(* ################################################################# *)\n(** * Welcome *)\n\n(** Here's a good way to build formally verified correct software:\n - Write your program in an expressive language with a good proof theory\n (the Gallina language embedded in Coq's logic).\n - Prove it correct in Coq.\n - Compile it with an optimizing ML compiler.\n\n Since you want your programs to be _efficient_, you'll want to\n implement sophisticated data structures and algorithms. Since\n Gallina is a _purely functional_ language, it helps to have\n purely functional algorithms.\n\n In this volume you will learn how to specify and verify (prove the\n correctness of) sorting algorithms, binary search trees, balanced\n binary search trees, and priority queues. Before using this book,\n you should have some understanding of these algorithms and data\n structures, available in any standard undergraduate algorithms\n textbook.\n\n This electronic book is Volume 3 of the _Software Foundations_\n series, which presents the mathematical underpinnings of reliable\n software. It builds on _Software Foundations Volume 1_\n (Logical Foundations), but does not depend on Volume 2.\n The exposition here is intended for a broad range of readers, from\n advanced undergraduates to PhD students and researchers.\n\n The principal novelty of _Software Foundations_ is that it is one\n hundred percent formalized and machine-checked: the entire text is\n literally a script for Coq. It is intended to be read alongside an\n interactive session with Coq. All the details in the text are fully\n formalized in Coq, and the exercises are designed to be worked using\n Coq.\n*)\n\n(* ################################################################# *)\n(** * Practicalities *)\n\n(* ================================================================= *)\n(** ** Chapter Dependencies *)\n\n(** Before using _Verified Functional Algorithms_, read\n (and do the exercises in) these chapters of\n _Software Foundations Volume I_:\n Preface, Basics, Induction, Lists, Poly, Tactics, Logic,\n IndProp, Maps, and perhaps (ProofObjects), (IndPrinciples).\n\n In this volume, the core path is:\n\n [Preface] -> [Perm] -> [Sort] -> [SearchTree] -> [Extract] -> [Redblack]\n\n with many optional chapters whose dependencies are,\n\n - [Sort] -> [Multiset] or [Selection] or [Decide]\n - [SearchTree] -> [ADT]\n - [Perm] -> [Trie]\n - [Sort] -> [Selection] -> [SearchTree] -> [ADT] -> [Priqueue] -> [Binom]\n\n The [Color] chapter is advanced material that should not be\n attempted until the student has had experience with most\n of the earlier chapters, or other experience using Coq.\n*)\n\n(* ================================================================= *)\n(** ** System Requirements *)\n\n(** Coq runs on Windows, Linux, and OS X. The Preface of Volume 1\n describes the Coq installation you will need. This edition was\n built with Coq 8.9.1 or later.\n\n In addition, two of the chapters ask you to compile and run an\n OCaml program; having OCaml installed on your computer is helpful,\n but not essential. *)\n\n(* ================================================================= *)\n(** ** Exercises *)\n\n(** Each chapter includes numerous exercises. Each is marked with a\n \"star rating,\" which can be interpreted as follows:\n\n - One star: easy exercises that underscore points in the text\n and that, for most readers, should take only a minute or two.\n Get in the habit of working these as you reach them.\n\n - Two stars: straightforward exercises (five or ten minutes).\n\n - Three stars: exercises requiring a bit of thought (ten\n minutes to half an hour).\n\n - Four and five stars: more difficult exercises (half an hour\n and up).\n\n Also, some exercises are marked \"advanced\", and some are marked\n \"optional.\" Doing just the non-optional, non-advanced exercises\n should provide good coverage of the core material. Optional\n exercises provide a bit of extra practice with key concepts and\n introduce secondary themes that may be of interest to some\n readers. Advanced exercises are for readers who want an extra\n challenge (and, in return, a deeper contact with the material).\n\n _Please do not post solutions to the exercises in any public place_: \n Software Foundations is widely used both for self-study and for\n university courses. Having solutions easily available makes it\n much less useful for courses, which typically have graded homework\n assignments. The authors especially request that readers not post\n solutions to the exercises anyplace where they can be found by\n search engines.\n*)\n\n(* ================================================================= *)\n(** ** Downloading the Coq Files *)\n\n(** A tar file containing the full sources for the \"release version\"\n of this book (as a collection of Coq scripts and HTML files) is\n available at https://softwarefoundations.cis.upenn.edu.\n\n (If you are using the book as part of a class, your professor may\n give you access to a locally modified version of the files, which\n you should use instead of the release version.) *)\n\n(* ================================================================= *)\n(** ** Lecture Videos *)\n\n(** Lectures on for an intensive summer course based on some chapters\n of this book at the DeepSpec summer school in 2017 can be\n found at https://deepspec.org/event/dsss17/lecture_appel.html. *)\n\n(* ================================================================= *)\n(** ** For Instructors and Contributors *)\n\n(** If you plan to use these materials in your own course, you will\n undoubtedly find things you'd like to change, improve, or add.\n Your contributions are welcome! Please see the [Preface]\n to _Logical Foundations_ for instructions. *)\n\n(* ================================================================= *)\n(** ** Recommended Citation Format *)\n\n(** If you want to refer to this volume in your own writing, please\n do so as follows:\n\n @book {$FIRSTAUTHOR:SF$VOLUMENUMBER,\n author = {$AUTHORS},\n title = \"$VOLUMENAME\",\n series = \"Software Foundations\",\n volume = \"$VOLUMENUMBER\",\n year = \"$VOLUMEYEAR\",\n publisher = \"Electronic textbook\",\n note = {Version $VERSION, \\URLhttp://softwarefoundations.cis.upenn.edu },\n }\n*)\n\n(* ################################################################# *)\n(** * Thanks *)\n\n(** Development of the _Software Foundations_ series has been\n supported, in part, by the National Science Foundation under the\n NSF Expeditions grant 1521523, _The Science of Deep\n Specification_. *)\n\n(* 2020-08-07 17:08 *)\n", "meta": {"author": "Edwardzcn", "repo": "ocaml-exercise", "sha": "6df431973ce13f24c6d4ff739f6e6d83fae48656", "save_path": "github-repos/coq/Edwardzcn-ocaml-exercise", "path": "github-repos/coq/Edwardzcn-ocaml-exercise/ocaml-exercise-6df431973ce13f24c6d4ff739f6e6d83fae48656/SoftwareFoundation/vfa/Preface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.08561092745338114}} {"text": "(** * Preface *)\n\n(* ################################################################# *)\n(** * Welcome *)\n\n(** This is the entry point to a series of electronic textbooks on\n various aspects of _Software Foundations_, the mathematical\n underpinnings of reliable software. Topics in the series include\n basic concepts of logic, computer-assisted theorem proving, the\n Coq proof assistant, functional programming, operational\n semantics, logics and techniques for reasoning about programs,\n static type systems, property-based random testing, and\n verification of practical C code. The exposition is intended for\n a broad range of readers, from advanced undergraduates to PhD\n students and researchers. No specific background in logic or\n programming languages is assumed, though a degree of mathematical\n maturity will be helpful.\n\n The principal novelty of the series is that it is one hundred\n percent formalized and machine-checked: each text is literally a\n script for Coq. The books are intended to be read alongside (or\n inside) an interactive session with Coq. All the details in the\n text are fully formalized in Coq, and most of the exercises are\n designed to be worked using Coq.\n\n The files in each book are organized into a sequence of core\n chapters, covering about one semester's worth of material and\n organized into a coherent linear narrative, plus a number of\n \"offshoot\" chapters covering additional topics. All the core\n chapters are suitable for both upper-level undergraduate and\n graduate students.\n\n This book, _Logical Foundations_, lays groundwork for the others,\n introducing the reader to the basic ideas of functional\n programming, constructive logic, and the Coq proof assistant. *)\n\n(* ################################################################# *)\n(** * Overview *)\n\n(** Building reliable software is really hard -- really hard. The\n scale and complexity of modern systems, the number of people\n involved, and the range of demands placed on them make it\n challenging to build software that is even more-or-less correct,\n much less 100%% correct. At the same time, the increasing degree\n to which information processing is woven into every aspect of\n society greatly amplifies the cost of bugs and insecurities.\n\n Computer scientists and software engineers have responded to these\n challenges by developing a host of techniques for improving\n software reliability, ranging from recommendations about managing\n software projects teams (e.g., extreme programming) to design\n philosophies for libraries (e.g., model-view-controller,\n publish-subscribe, etc.) and programming languages (e.g.,\n object-oriented programming, aspect-oriented programming,\n functional programming, ...) to mathematical techniques for\n specifying and reasoning about properties of software and tools\n for helping validate these properties. The _Software Foundations_\n series is focused on this last set of tools.\n\n This volume weaves together three conceptual threads:\n\n (1) basic tools from _logic_ for making and justifying precise\n claims about programs;\n\n (2) the use of _proof assistants_ to construct rigorous logical\n arguments;\n\n (3) _functional programming_, both as a method of programming that\n simplifies reasoning about programs and as a bridge between\n programming and logic. *)\n\n(* ================================================================= *)\n(** ** Logic *)\n\n(** Logic is the field of study whose subject matter is _proofs_ --\n unassailable arguments for the truth of particular propositions.\n Volumes have been written about the central role of logic in\n computer science. Manna and Waldinger called it \"the calculus of\n computer science,\" while Halpern et al.'s paper _On the Unusual\n Effectiveness of Logic in Computer Science_ catalogs scores of\n ways in which logic offers critical tools and insights. Indeed,\n they observe that, \"As a matter of fact, logic has turned out to\n be significantly more effective in computer science than it has\n been in mathematics. This is quite remarkable, especially since\n much of the impetus for the development of logic during the past\n one hundred years came from mathematics.\"\n\n In particular, the fundamental tools of _inductive proof_ are\n ubiquitous in all of computer science. You have surely seen them\n before, perhaps in a course on discrete math or analysis of\n algorithms, but in this course we will examine them more deeply\n than you have probably done so far. *)\n\n(* ================================================================= *)\n(** ** Proof Assistants *)\n\n(** The flow of ideas between logic and computer science has not been\n unidirectional: CS has also made important contributions to logic.\n One of these has been the development of software tools for\n helping construct proofs of logical propositions. These tools\n fall into two broad categories:\n\n - _Automated theorem provers_ provide \"push-button\" operation:\n you give them a proposition and they return either _true_ or\n _false_ (or, sometimes, _don't know: ran out of time_).\n Although their capabilities are still limited to specific\n domains, they have matured tremendously in recent years and\n are used now in a multitude of settings. Examples of such\n tools include SAT solvers, SMT solvers, and model checkers.\n\n - _Proof assistants_ are hybrid tools that automate the more\n routine aspects of building proofs while depending on human\n guidance for more difficult aspects. Widely used proof\n assistants include Isabelle, Agda, Twelf, ACL2, PVS, and Coq,\n among many others.\n\n This course is based around Coq, a proof assistant that has been\n under development since 1983 and that in recent years has\n attracted a large community of users in both research and\n industry. Coq provides a rich environment for interactive\n development of machine-checked formal reasoning. The kernel of\n the Coq system is a simple proof-checker, which guarantees that\n only correct deduction steps are ever performed. On top of this\n kernel, the Coq environment provides high-level facilities for\n proof development, including a large library of common definitions\n and lemmas, powerful tactics for constructing complex proofs\n semi-automatically, and a special-purpose programming language for\n defining new proof-automation tactics for specific situations.\n\n Coq has been a critical enabler for a huge variety of work across\n computer science and mathematics:\n\n - As a _platform for modeling programming languages_, it has\n become a standard tool for researchers who need to describe and\n reason about complex language definitions. It has been used,\n for example, to check the security of the JavaCard platform,\n obtaining the highest level of common criteria certification,\n and for formal specifications of the x86 and LLVM instruction\n sets and programming languages such as C.\n\n - As an _environment for developing formally certified software\n and hardware_, Coq has been used, for example, to build\n CompCert, a fully-verified optimizing compiler for C, and\n CertiKOS, a fully verified hypervisor, for proving the\n correctness of subtle algorithms involving floating point\n numbers, and as the basis for CertiCrypt, an environment for\n reasoning about the security of cryptographic algorithms. It is\n also being used to build verified implementations of the\n open-source RISC-V processor architecture.\n\n - As a _realistic environment for functional programming with\n dependent types_, it has inspired numerous innovations. For\n example, the Ynot system embeds \"relational Hoare reasoning\" (an\n extension of the _Hoare Logic_ we will see later in this course)\n in Coq.\n\n - As a _proof assistant for higher-order logic_, it has been used\n to validate a number of important results in mathematics. For\n example, its ability to include complex computations inside\n proofs made it possible to develop the first formally verified\n proof of the 4-color theorem. This proof had previously been\n controversial among mathematicians because it required checking\n a large number of configurations using a program. In the Coq\n formalization, everything is checked, including the correctness\n of the computational part. More recently, an even more massive\n effort led to a Coq formalization of the Feit-Thompson Theorem,\n the first major step in the classification of finite simple\n groups.\n\n By the way, in case you're wondering about the name, here's what\n the official Coq web site at INRIA (the French national research\n lab where Coq has mostly been developed) says about it: \"Some\n French computer scientists have a tradition of naming their\n software as animal species: Caml, Elan, Foc or Phox are examples of\n this tacit convention. In French, 'coq' means rooster, and it\n sounds like the initials of the Calculus of Constructions (CoC) on\n which it is based.\" The rooster is also the national symbol of\n France, and C-o-q are the first three letters of the name of\n Thierry Coquand, one of Coq's early developers. *)\n\n(* ================================================================= *)\n(** ** Functional Programming *)\n\n(** The term _functional programming_ refers both to a collection of\n programming idioms that can be used in almost any programming\n language and to a family of programming languages designed to\n emphasize these idioms, including Haskell, OCaml, Standard ML,\n F##, Scala, Scheme, Racket, Common Lisp, Clojure, Erlang, and Coq.\n\n Functional programming has been developed over many decades --\n indeed, its roots go back to Church's lambda-calculus, which was\n invented in the 1930s, well _before_ the first electronic\n computers! But since the early '90s it has enjoyed a surge of\n interest among industrial engineers and language designers,\n playing a key role in high-value systems at companies like Jane\n Street Capital, Microsoft, Facebook, Twitter, and Ericsson.\n\n The most basic tenet of functional programming is that, as much as\n possible, computation should be _pure_, in the sense that the only\n effect of execution should be to produce a result: it should be\n free from _side effects_ such as I/O, assignments to mutable\n variables, redirecting pointers, etc. For example, whereas an\n _imperative_ sorting function might take a list of numbers and\n rearrange its pointers to put the list in order, a pure sorting\n function would take the original list and return a _new_ list\n containing the same numbers in sorted order.\n\n A significant benefit of this style of programming is that it\n makes programs easier to understand and reason about. If every\n operation on a data structure yields a new data structure, leaving\n the old one intact, then there is no need to worry about how that\n structure is being shared and whether a change by one part of the\n program might break an invariant relied on by another part of the\n program. These considerations are particularly critical in\n concurrent systems, where every piece of mutable state that is\n shared between threads is a potential source of pernicious bugs.\n Indeed, a large part of the recent interest in functional\n programming in industry is due to its simpler behavior in the\n presence of concurrency.\n\n Another reason for the current excitement about functional\n programming is related to the first: functional programs are often\n much easier to parallelize and physically distribute than their\n imperative counterparts. If running a computation has no effect\n other than producing a result, then it does not matter _where_ it\n is run. Similarly, if a data structure is never modified\n destructively, then it can be copied freely, across cores or\n across the network. Indeed, the \"Map-Reduce\" idiom, which lies at\n the heart of massively distributed query processors like Hadoop\n and is used by Google to index the entire web is a classic example\n of functional programming.\n\n For purposes of this course, functional programming has yet\n another significant attraction: it serves as a bridge between\n logic and computer science. Indeed, Coq itself can be viewed as a\n combination of a small but extremely expressive functional\n programming language plus a set of tools for stating and proving\n logical assertions. Moreover, when we come to look more closely,\n we find that these two sides of Coq are actually aspects of the\n very same underlying machinery -- i.e., _proofs are programs_. *)\n\n(* ================================================================= *)\n(** ** Further Reading *)\n\n(** This text is intended to be self contained, but readers looking\n for a deeper treatment of particular topics will find some\n suggestions for further reading in the [Postscript] chapter.\n Bibliographic information for all cited works can be found in the\n file [Bib].*)\n\n(* ################################################################# *)\n(** * Practicalities *)\n\n(* ================================================================= *)\n(** ** System Requirements *)\n\n(** Coq runs on Windows, Linux, and macOS. You will need:\n\n - A current installation of Coq, available from the Coq home page.\n These files have been tested with Coq 8.12.\n\n - An IDE for interacting with Coq. Currently, there are two\n choices:\n\n - Proof General is an Emacs-based IDE. It tends to be\n preferred by users who are already comfortable with Emacs.\n It requires a separate installation (google \"Proof\n General\").\n\n Adventurous users of Coq within Emacs may want to check\n out extensions such as [company-coq] and [control-lock].\n\n - CoqIDE is a simpler stand-alone IDE. It is distributed with\n Coq, so it should be available once you have Coq installed.\n It can also be compiled from scratch, but on some platforms\n this may involve installing additional packages for GUI\n libraries and such.\n\n Users who like CoqIDE should consider running it with the\n \"asynchronous\" and \"error resilience\" modes disabled:\n\n coqide -async-proofs off \\\n -async-proofs-command-error-resilience off Foo.v &\n*)\n\n(* ================================================================= *)\n(** ** Exercises *)\n\n(** Each chapter includes numerous exercises. Each is marked with a\n \"star rating,\" which can be interpreted as follows:\n\n - One star: easy exercises that underscore points in the text\n and that, for most readers, should take only a minute or two.\n Get in the habit of working these as you reach them.\n\n - Two stars: straightforward exercises (five or ten minutes).\n\n - Three stars: exercises requiring a bit of thought (ten\n minutes to half an hour).\n\n - Four and five stars: more difficult exercises (half an hour\n and up).\n\n Those using SF in a classroom setting should note that the autograder\n assigns extra points to harder exercises:\n\n 1 star = 1 point\n 2 stars = 2 points\n 3 stars = 3 points\n 4 stars = 6 points\n 5 stars = 10 points\n\n Some exercises are marked \"advanced,\" and some are marked\n \"optional.\" Doing just the non-optional, non-advanced exercises\n should provide good coverage of the core material. Optional\n exercises provide a bit of extra practice with key concepts and\n introduce secondary themes that may be of interest to some\n readers. Advanced exercises are for readers who want an extra\n challenge and a deeper cut at the material.\n\n _Please do not post solutions to the exercises in a public place_. \n Software Foundations is widely used both for self-study and for\n university courses. Having solutions easily available makes it\n much less useful for courses, which typically have graded homework\n assignments. We especially request that readers not post\n solutions to the exercises anyplace where they can be found by\n search engines. *)\n\n(* ================================================================= *)\n(** ** Downloading the Coq Files *)\n\n(** A tar file containing the full sources for the \"release version\"\n of this book (as a collection of Coq scripts and HTML files) is\n available at https://softwarefoundations.cis.upenn.edu.\n\n If you are using the book as part of a class, your professor may\n give you access to a locally modified version of the files; you\n should use that one instead of the public release version, so that\n you get any local updates during the semester. *)\n\n(* ================================================================= *)\n(** ** Chapter Dependencies *)\n\n(** A diagram of the dependencies between chapters and some suggested\n paths through the material can be found in the file [deps.html]. *)\n\n(* ================================================================= *)\n(** ** Recommended Citation Format *)\n\n(** If you want to refer to this volume in your own writing, please\n do so as follows:\n\n @book {$FIRSTAUTHOR:SF$VOLUMENUMBER,\n author = {$AUTHORS},\n title = \"$VOLUMENAME\",\n series = \"Software Foundations\",\n volume = \"$VOLUMENUMBER\",\n year = \"$VOLUMEYEAR\",\n publisher = \"Electronic textbook\",\n note = {Version $VERSION, \\URLhttp://softwarefoundations.cis.upenn.edu },\n }\n*)\n\n(* ################################################################# *)\n(** * Resources *)\n\n(* ================================================================= *)\n(** ** Sample Exams *)\n\n(** A large compendium of exams from many offerings of\n CIS500 (\"Software Foundations\") at the University of Pennsylvania\n can be found at\n https://www.seas.upenn.edu/~cis500/current/exams/index.html.\n There has been some drift of notations over the years, but most of\n the problems are still relevant to the current text. *)\n\n(* ================================================================= *)\n(** ** Lecture Videos *)\n\n(** Lectures for two intensive summer courses based on _Logical\n Foundations_ (part of the DeepSpec summer school series) can be\n found at https://deepspec.org/event/dsss17 and\n https://deepspec.org/event/dsss18/. The video quality in the\n 2017 lectures is poor at the beginning but gets better in the\n later lectures. *)\n\n(* ################################################################# *)\n(** * Note for Instructors *)\n\n(** If you plan to use these materials in your own course, you will\n undoubtedly find things you'd like to change, improve, or add.\n Your contributions are welcome!\n\n In order to keep the legalities simple and to have a single point\n of responsibility in case the need should ever arise to adjust the\n license terms, sublicense, etc., we ask all contributors (i.e.,\n everyone with access to the developers' repository) to assign\n copyright in their contributions to the appropriate \"author of\n record,\" as follows:\n\n - I hereby assign copyright in my past and future contributions\n to the Software Foundations project to the Author of Record of\n each volume or component, to be licensed under the same terms\n as the rest of Software Foundations. I understand that, at\n present, the Authors of Record are as follows: For Volumes 1\n and 2, known until 2016 as \"Software Foundations\" and from\n 2016 as (respectively) \"Logical Foundations\" and \"Programming\n Foundations,\" and for Volume 4, \"QuickChick: Property-Based\n Testing in Coq,\" the Author of Record is Benjamin C. Pierce.\n For Volume 3, \"Verified Functional Algorithms\", the Author of\n Record is Andrew W. Appel. For components outside of\n designated volumes (e.g., typesetting and grading tools and\n other software infrastructure), the Author of Record is\n Benjamin Pierce.\n\n To get started, please send an email to Benjamin Pierce,\n describing yourself and how you plan to use the materials and\n including (1) the above copyright transfer text and (2) your\n github username.\n\n We'll set you up with access to the git repository and developers'\n mailing lists. In the repository you'll find a file [INSTRUCTORS]\n with further instructions. *)\n\n(* ################################################################# *)\n(** * Translations *)\n\n(** Thanks to the efforts of a team of volunteer translators,\n _Software Foundations_ can be enjoyed in Japanese at\n http://proofcafe.org/sf. A Chinese translation is also underway;\n you can preview it at https://coq-zh.github.io/SF-zh/. *)\n\n(* ################################################################# *)\n(** * Thanks *)\n\n(** Development of the _Software Foundations_ series has been\n supported, in part, by the National Science Foundation under the\n NSF Expeditions grant 1521523, _The Science of Deep\n Specification_. *)\n\n(* 2020-09-09 20:51 *)\n", "meta": {"author": "shouya", "repo": "thinking-dumps", "sha": "bfe50272459ddfca95de74a1857e2e649218584e", "save_path": "github-repos/coq/shouya-thinking-dumps", "path": "github-repos/coq/shouya-thinking-dumps/thinking-dumps-bfe50272459ddfca95de74a1857e2e649218584e/software-foundations-2/lf/Preface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.18952109590739918, "lm_q1q2_score": 0.08516938457647451}} {"text": "(* [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- you can just skip\n over the definition to the example that follows. It uses some\n facilities of Coq that we have not discussed -- the string\n library (just for the concrete syntax of quoted strings) and the\n [Ltac] command, which allows us to declare custom tactics. Kudos\n to Aaron Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\nRequire Export Induction.\n\n(*\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n*)\n\n(** * Lists: Working with Structured Data *)\nModule NatList.\n\nInductive natprod : Type :=\n | pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nExample test_fst_1: (fst (pair 3 5)) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_snd_1: (snd (pair 2 4)) = 4.\nProof. simpl. reflexivity. Qed.\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3, 4)).\n\nDefinition fst' (p: natprod) : nat :=\n match p with\n | (x, y) => x\n end.\n\nDefinition snd' (p: natprod) : nat :=\n match p with\n | (x, y) => y\n end.\n\nDefinition swap_pair (p: natprod) : natprod :=\n match p with\n | (x, y) => (y, x)\n end.\n\nCompute (swap_pair (3, 5)).\n\nTheorem surjective_pairing' : forall (n m:nat),\n (n,m) = (fst (n, m), snd (n, m)).\nProof.\n reflexivity. Qed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl.\nAbort.\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed.\n\n\nTheorem snd_fst_is_swap : forall(p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity. Qed.\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\n\nNotation \"[ ]\" := nil.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\nCompute (repeat 2 3).\n\nFixpoint length (n : natlist) : nat :=\n match n with\n | nil => 0\n | h :: t => plus 1 (length t)\n end.\n\nCompute (length [1;2;3]).\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app_1: [1;2;3] ++ [4;5;6] = [1;2;3;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_app_2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\n\nExample test_app_3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nFixpoint tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\n\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\n\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint nonzeroes (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: t => nonzeroes t\n | h :: t => h :: (nonzeroes t)\n end.\n\nExample test_nonzeroes: nonzeroes [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint evenb (n:nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => \n match (evenb h) with\n | true => oddmembers t\n | false => h :: (oddmembers t)\n end\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n length (oddmembers l).\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h1 :: t1 =>\n match l2 with\n | nil => l1\n | h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n end\n end.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4: alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | nil => 0\n | h :: t =>\n match (beq_nat h v) with\n | true => plus 1 (count v t)\n | false => (count v t)\n end\n end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n\nDefinition sum : bag -> bag -> bag :=\n alternate.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n cons v s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint leb (n m : nat) : bool :=\n match n with\n | O => true\n | S n' =>\n match m with\n | O => false\n | S m' => leb n' m'\n end\n end.\n\nDefinition member (v:nat) (s:bag) : bool :=\n negb (beq_nat 0 (count v s)).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => \n match (beq_nat h v) with\n | true => t\n | false => h :: remove_one v t\n end\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t =>\n match (beq_nat h v) with\n | true => remove_all v t\n | false => h :: (remove_all v t)\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h1 :: t1 =>\n match leb (count h1 s1) (count h1 s2) with\n | false => false\n | true => (subset t1 s2)\n end\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n'].\n - reflexivity.\n - reflexivity.\nQed.\n\n(** Induction on Lists **)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n simpl. reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\n\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n simpl. reflexivity.\n - (* l = const n l' *)\n simpl. rewrite <- IHl'.\nAbort.\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = length l1 + length l2.\nProof.\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n simpl. reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem plus_n_O_firsttry : forall n:nat,\n n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) intros m. induction m as [| m' IHm'] \n + (* m = 0 *) simpl. reflexivity.\n + (* m = S m' *) simpl. rewrite <- IHm'. simpl. reflexivity.\n - (* n = S n *) intros m. simpl. induction m as [| m' IHm'].\n + (* m = 0 *) simpl. rewrite <- plus_n_O_firsttry. reflexivity.\n + (* m = S m' *) simpl. rewrite <- IHm'. rewrite -> IHn'. simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n simpl. rewrite -> app_length, plus_comm. \n simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(* List Exercises, Part 1 *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *) simpl. rewrite -> plus_comm. reflexivity.\n - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n rewrite -> app_nil_r. reflexivity. \n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n simpl. reflexivity.\n - (* l = cons n l' *)\n simpl. rewrite -> rev_app_distr. simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4. rewrite? app_assoc. reflexivity.\nQed. \n\nLemma nonzeros_app: forall l1 l2 : natlist,\n nonzeroes (l1 ++ l2) = (nonzeroes l1) ++ (nonzeroes l2).\nProof.\n intros l1 l2. induction l1.\n Case \"l1 = []\". reflexivity.\n Case \"l1 = n :: l1'\".\n destruct n.\n - simpl. rewrite -> IHl1. reflexivity.\n - simpl. rewrite -> IHl1. reflexivity.\nQed.\n\n(* Exercise: 2 stars (beq_natlist) *)\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1 with\n | nil => match l2 with\n | nil => true\n | _ => false\n end\n | n1 :: t1 => match l2 with\n | nil => false\n | n2 :: t2 => \n andb (beq_nat n1 n2) (beq_natlist t1 t2)\n end\n end.\n\nExample test_beq_natlist1: \n (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2:\n (beq_natlist [1;2;3] [1;2;3] = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3:\n (beq_natlist [1;2;3] [1;2;4] = false).\nProof. reflexivity. Qed.\n\n\nTheorem beq_nat_refl : forall n:nat,\n true = beq_nat n n.\nProof.\n intros n. induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros l. induction l.\n Case \"l = []\". reflexivity.\n Case \"l = n :: l'\". \n simpl. rewrite <- IHl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nProof.\n intros s. induction s.\n Case \"s = []\". reflexivity.\n Case \"s = n :: s'\". simpl. reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nProof.\n intros n. induction n.\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem remove_decrease_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros s. induction s.\n Case \"s = []\". reflexivity.\n Case \"s = n :: s'\".\n destruct n.\n - simpl. rewrite -> ble_n_Sn. reflexivity.\n - simpl. rewrite -> IHs. reflexivity.\nQed.\n\nTheorem rev_injective: forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2. intros H. induction l1 as [| n1 l1' IHl1].\n - rewrite <- rev_involutive. rewrite <- H. reflexivity.\n - rewrite <- rev_involutive. rewrite <- H. rewrite -> rev_involutive. reflexivity.\nQed.\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nCompute nth_bad [1;2;3] 1.\nCompute nth_bad [1;3;4] 10.\nCompute nth_error [1;2;3;4] 3.\nCompute nth_error [1;2;3;4] 10.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\n\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\n\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\n end.\n\nExample test_hd_error1: hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2: hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3: hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros l default. destruct l.\n Case \"l = []\". reflexivity.\n Case \"l = n :: l'\". reflexivity.\nQed.\n\nEnd NatList.\n\nExport NatList.\n\n(* Partial Maps *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\nTheorem beq_id_refl : forall x, \n true = beq_id x x.\nProof.\n intros x. destruct x.\n simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d: partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\nFixpoint find (x: id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if beq_id x y\n then Some v\n else find x d'\n end.\n\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v : nat),\n find x (update d x v) = Some v.\nProof.\n intros d x v. induction d.\n - simpl. rewrite <- beq_id_refl. reflexivity.\n - simpl. rewrite <- beq_id_refl. reflexivity.\nQed.\n\nTheorem update_neq :\n forall (d : partial_map) (x : id) (v : nat),\n find x (update d x v) = Some v.\nProof.\n intros d x v. induction d.\n - simpl. rewrite <- beq_id_refl. reflexivity.\n - simpl. rewrite <- beq_id_refl. reflexivity.\nQed.\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n\nCheck baz.\n\nEnd PartialMap.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "prashantpawar", "repo": "logical-foundations", "sha": "8c2126869f2104e2fe38249e3b86de080ea12d2f", "save_path": "github-repos/coq/prashantpawar-logical-foundations", "path": "github-repos/coq/prashantpawar-logical-foundations/logical-foundations-8c2126869f2104e2fe38249e3b86de080ea12d2f/Lists_psp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.20181322946142372, "lm_q1q2_score": 0.08449857544258811}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(* ################################################################# *)\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward.\n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (mostly works), and Scheme (a bit\n out of date). *)\n\nRequire Coq.extraction.Extraction.\nExtraction Language OCaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nFrom LF Require Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ################################################################# *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ################################################################# *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we first need\n to set up the right correspondence between Coq strings and lists\n of OCaml characters. *)\n\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlString.\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nFrom LF Require Import Imp.\nFrom LF Require Import ImpParser.\n\nFrom LF Require Import Maps.\nDefinition empty_state := { --> 0 }.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ################################################################# *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(* ################################################################# *)\n(** * Going Further *)\n\n(** Further details about extraction can be found in the Extract\n chapter in _Verified Functional Algorithms_ (_Software\n Foundations_ volume 3). *)\n\n", "meta": {"author": "neshkeev", "repo": "Logical-Foundations", "sha": "f529036b8e483f1beb737386c02fc5d18e6deae2", "save_path": "github-repos/coq/neshkeev-Logical-Foundations", "path": "github-repos/coq/neshkeev-Logical-Foundations/Logical-Foundations-f529036b8e483f1beb737386c02fc5d18e6deae2/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1666754067576692, "lm_q1q2_score": 0.08268664081703529}} {"text": "(** * ImpParser: Lexing and Parsing in Coq *)\n\n(** The development of the Imp language in [Imp.v] completely ignores\n issues of concrete syntax -- how an ascii string that a programmer\n might write gets translated into abstract syntax trees defined by\n the datatypes [aexp], [bexp], and [com]. In this chapter, we\n illustrate how the rest of the story can be filled in by building\n a simple lexical analyzer and parser using Coq's functional\n programming facilities. *)\n\n(** It is not important to understand all the details here (and\n accordingly, the explanations are fairly terse and there are no\n exercises). The main point is simply to demonstrate that it can\n be done. You are invited to look through the code -- most of it\n is not very complicated, though the parser relies on some\n \"monadic\" programming idioms that may require a little work to\n make out -- but most readers will probably want to just skim down\n to the Examples section at the very end to get the punchline. *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-implicit-arguments\".\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Maps Imp.\n\n(* ################################################################# *)\n(** * Internals *)\n\n(* ================================================================= *)\n(** ** Lexical Analysis *)\n\nDefinition isWhite (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (orb (beq_nat n 32) (* space *)\n (beq_nat n 9)) (* tab *)\n (orb (beq_nat n 10) (* linefeed *)\n (beq_nat n 13)). (* Carriage return. *)\n\nNotation \"x '<=?' y\" := (leb x y)\n (at level 70, no associativity) : nat_scope.\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (97 <=? n) (n <=? 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (andb (65 <=? n) (n <=? 90))\n (andb (97 <=? n) (n <=? 122)).\n\nDefinition isDigit (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (48 <=? n) (n <=? 57).\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n if isWhite c then\n white\n else if isAlpha c then\n alpha\n else if isDigit c then\n digit\n else\n other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n match s with\n | EmptyString => []\n | String c s => c :: (list_of_string s)\n end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n fold_right String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii)\n : list (list ascii) :=\n let tk := match acc with [] => [] | _::_ => [rev acc] end in\n match xs with\n | [] => tk\n | (x::xs') =>\n match cls, classifyChar x, x with\n | _, _, \"(\" =>\n tk ++ [\"(\"]::(tokenize_helper other [] xs')\n | _, _, \")\" =>\n tk ++ [\")\"]::(tokenize_helper other [] xs')\n | _, white, _ =>\n tk ++ (tokenize_helper white [] xs')\n | alpha,alpha,x =>\n tokenize_helper alpha (x::acc) xs'\n | digit,digit,x =>\n tokenize_helper digit (x::acc) xs'\n | other,other,x =>\n tokenize_helper other (x::acc) xs'\n | _,tp,x =>\n tk ++ (tokenize_helper tp [x] xs')\n end\n end %char.\n\nDefinition tokenize (s : string) : list string :=\n map string_of_list (tokenize_helper white [] (list_of_string s)).\n\nExample tokenize_ex1 :\n tokenize \"abc12=3 223*(3+(a+c))\" %string\n = [\"abc\"; \"12\"; \"=\"; \"3\"; \"223\";\n \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n \"a\"; \"+\"; \"c\"; \")\"; \")\"]%string.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Parsing *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Options With Errors *)\n\n(** An [option] type with error messages: *)\n\nInductive optionE (X:Type) : Type :=\n | SomeE : X -> optionE X\n | NoneE : string -> optionE X.\n\nImplicit Arguments SomeE [[X]].\nImplicit Arguments NoneE [[X]].\n\n(** Some syntactic sugar to make writing nested match-expressions on\n optionE more convenient. *)\n\nNotation \"'DO' ( x , y ) <== e1 ; e2\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => NoneE err\n end)\n (right associativity, at level 60).\n\nNotation \"'DO' ( x , y ) <-- e1 ; e2 'OR' e3\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => e3\n end)\n (right associativity, at level 60, e2 at next level).\n\n(* ----------------------------------------------------------------- *)\n(** *** Generic Combinators for Building Parsers *)\n\nOpen Scope string_scope.\n\nDefinition parser (T : Type) :=\n list token -> optionE (T * list token).\n\nFixpoint many_helper {T} (p : parser T) acc steps xs :=\n match steps, p xs with\n | 0, _ =>\n NoneE \"Too many recursive calls\"\n | _, NoneE _ =>\n SomeE ((rev acc), xs)\n | S steps', SomeE (t, xs') =>\n many_helper p (t::acc) steps' xs'\n end.\n\n(** A (step-indexed) parser that expects zero or more [p]s: *)\n\nFixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=\n many_helper p [] steps.\n\n(** A parser that expects a given token, followed by [p]: *)\n\nDefinition firstExpect {T} (t : token) (p : parser T)\n : parser T :=\n fun xs => match xs with\n | x::xs' =>\n if string_dec x t\n then p xs'\n else NoneE (\"expected '\" ++ t ++ \"'.\")\n | [] =>\n NoneE (\"expected '\" ++ t ++ \"'.\")\n end.\n\n(** A parser that expects a particular token: *)\n\nDefinition expect (t : token) : parser unit :=\n firstExpect t (fun xs => SomeE(tt, xs)).\n\n(* ----------------------------------------------------------------- *)\n(** *** A Recursive-Descent Parser for Imp *)\n\n(** Identifiers: *)\n\nDefinition parseIdentifier (xs : list token)\n : optionE (string * list token) :=\nmatch xs with\n| [] => NoneE \"Expected identifier\"\n| x::xs' =>\n if forallb isLowerAlpha (list_of_string x) then\n SomeE (x, xs')\n else\n NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\nend.\n\n(** Numbers: *)\n\nDefinition parseNumber (xs : list token)\n : optionE (nat * list token) :=\nmatch xs with\n| [] => NoneE \"Expected number\"\n| x::xs' =>\n if forallb isDigit (list_of_string x) then\n SomeE (fold_left\n (fun n d =>\n 10 * n + (nat_of_ascii d -\n nat_of_ascii \"0\"%char))\n (list_of_string x)\n 0,\n xs')\n else\n NoneE \"Expected number\"\nend.\n\n(** Parse arithmetic expressions *)\n\nFixpoint parsePrimaryExp (steps:nat) \n (xs : list token)\n : optionE (aexp * list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (i, rest) <-- parseIdentifier xs ;\n SomeE (AId i, rest)\n OR DO (n, rest) <-- parseNumber xs ;\n SomeE (ANum n, rest)\n OR (DO (e, rest) <== firstExpect \"(\"\n (parseSumExp steps') xs;\n DO (u, rest') <== expect \")\" rest ;\n SomeE(e,rest'))\n end\n\nwith parseProductExp (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parsePrimaryExp steps' xs ;\n DO (es, rest') <==\n many (firstExpect \"*\" (parsePrimaryExp steps'))\n steps' rest;\n SomeE (fold_left AMult es e, rest')\n end\n\nwith parseSumExp (steps:nat) (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseProductExp steps' xs ;\n DO (es, rest') <==\n many (fun xs =>\n DO (e,rest') <--\n firstExpect \"+\"\n (parseProductExp steps') xs;\n SomeE ( (true, e), rest')\n OR DO (e,rest') <==\n firstExpect \"-\"\n (parseProductExp steps') xs;\n SomeE ( (false, e), rest'))\n steps' rest;\n SomeE (fold_left (fun e0 term =>\n match term with\n (true, e) => APlus e0 e\n | (false, e) => AMinus e0 e\n end)\n es e,\n rest')\n end.\n\nDefinition parseAExp := parseSumExp.\n\n(** Parsing boolean expressions: *)\n\nFixpoint parseAtomicExp (steps:nat)\n (xs : list token) :=\nmatch steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u,rest) <-- expect \"true\" xs;\n SomeE (BTrue,rest)\n OR DO (u,rest) <-- expect \"false\" xs;\n SomeE (BFalse,rest)\n OR DO (e,rest) <-- \n firstExpect \"!\" \n (parseAtomicExp steps') \n xs;\n SomeE (BNot e, rest)\n OR DO (e,rest) <-- \n firstExpect \"(\" \n (parseConjunctionExp steps') xs;\n (DO (u,rest') <== expect \")\" rest; \n SomeE (e, rest'))\n OR DO (e, rest) <== parseProductExp steps' xs;\n (DO (e', rest') <--\n firstExpect \"=\" \n (parseAExp steps') rest;\n SomeE (BEq e e', rest')\n OR DO (e', rest') <--\n firstExpect \"<=\" \n (parseAExp steps') rest;\n SomeE (BLe e e', rest')\n OR\n NoneE \n \"Expected '=' or '<=' after arithmetic expression\")\nend\n\nwith parseConjunctionExp (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseAtomicExp steps' xs ;\n DO (es, rest') <==\n many (firstExpect \"&&\"\n (parseAtomicExp steps'))\n steps' rest;\n SomeE (fold_left BAnd es e, rest')\n end.\n\nDefinition parseBExp := parseConjunctionExp.\n\nCheck parseConjunctionExp.\n\nDefinition testParsing {X : Type}\n (p : nat -> \n list token ->\n optionE (X * list token))\n (s : string) :=\n let t := tokenize s in \n p 100 t.\n\n(*\nEval compute in \n testParsing parseProductExp \"x*y*(x*x)*x\".\n\nEval compute in \n testParsing parseConjunctionExp \"not((x=x||x*x<=(x*x)*x)&&x=x\". \n*)\n\n(** Parsing commands: *)\n\nFixpoint parseSimpleCommand (steps:nat) \n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u, rest) <-- expect \"SKIP\" xs;\n SomeE (SKIP, rest)\n OR DO (e,rest) <--\n firstExpect \"IFB\" (parseBExp steps') xs;\n DO (c,rest') <==\n firstExpect \"THEN\" \n (parseSequencedCommand steps') rest;\n DO (c',rest'') <==\n firstExpect \"ELSE\" \n (parseSequencedCommand steps') rest';\n DO (u,rest''') <==\n expect \"END\" rest'';\n SomeE(IFB e THEN c ELSE c' FI, rest''')\n OR DO (e,rest) <--\n firstExpect \"WHILE\" \n (parseBExp steps') xs;\n DO (c,rest') <==\n firstExpect \"DO\" \n (parseSequencedCommand steps') rest;\n DO (u,rest'') <==\n expect \"END\" rest';\n SomeE(WHILE e DO c END, rest'')\n OR DO (i, rest) <==\n parseIdentifier xs;\n DO (e, rest') <==\n firstExpect \":=\" (parseAExp steps') rest;\n SomeE(i ::= e, rest')\n end\n\nwith parseSequencedCommand (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (c, rest) <==\n parseSimpleCommand steps' xs;\n DO (c', rest') <--\n firstExpect \";;\" \n (parseSequencedCommand steps') rest;\n SomeE(c ;; c', rest')\n OR\n SomeE(c, rest)\n end.\n\nDefinition bignumber := 1000.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n let tokens := tokenize str in\n parseSequencedCommand bignumber tokens.\n\n(* ################################################################# *)\n(** * Examples *)\n\nExample eg1 : parse \"\n IFB x = y + 1 + 2 - y * 6 + 3 THEN\n x := x * 1;;\n y := 0\n ELSE\n SKIP\n END \"\n= \n SomeE (\n IFB \"x\" = \"y\" + 1 + 2 - \"y\" * 6 + 3 THEN\n \"x\" ::= \"x\" * 1;;\n \"y\" ::= 0\n ELSE\n SKIP\n FI,\n []). \nProof. reflexivity. Qed.\n\n(** $Date: 2017-11-28 15:16:24 -0600 (Tue, 28 Nov 2017) $ *)\n", "meta": {"author": "fsq", "repo": "CS386L-Programming-Language", "sha": "2a4e01bba8dbee34d5ccc60b104ce831ff69ace1", "save_path": "github-repos/coq/fsq-CS386L-Programming-Language", "path": "github-repos/coq/fsq-CS386L-Programming-Language/CS386L-Programming-Language-2a4e01bba8dbee34d5ccc60b104ce831ff69ace1/full/ImpParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.16885695214168314, "lm_q1q2_score": 0.08113216514423462}} {"text": "(** * B3: Reszta logiki konstruktywnej [TODO] *)\n\nFrom Typonomikon Require Export B2.\n\n(** * Kombinatory taktyk *)\n\n(** Przyjrzyjmy się jeszcze raz twierdzeniu [iff_intro] (lekko\n zmodernizowanemu przy pomocy kwantyfikacji uniwersalnej). *)\n\nLemma iff_intro' :\n forall P Q : Prop,\n (P -> Q) -> (Q -> P) -> (P <-> Q).\nProof.\n intros. split.\n - intro. apply H. assumption.\n - intro. apply H0. assumption.\nQed.\n\n(** Jego dowód wygląda dość schematycznie. Taktyka [split] generuje\n nam dwa podcele będące implikacjami — na każdym z osobna używamy\n następnie [intro], a kończymy [assumption]. Jedyne, czym różnią\n się dowody podcelów, to nazwa aplikowanej hipotezy.\n\n A co, gdyby jakaś taktyka wygenerowała nam 100 takich schematycznych\n podcelów? Czy musielibyśmy przechodzić przez mękę ręcznego dowodzenia\n tych niezbyt ciekawych przypadków? Czy da się powyższy dowód jakoś\n skrócić lub zautomatyzować?\n\n Odpowiedź na szczęście brzmi \"tak\". Z pomocą przychodzą nam kombinatory\n taktyk (ang. tacticals), czyli taktyki, które mogą przyjmować jako\n argumenty inne\n taktyki. Dzięki temu możemy łączyć proste taktyki w nieco bardziej\n skomplikowane lub jedynie zmieniać niektóre aspekty ich zachowań. *)\n\n(** ** [;] (średnik) *)\n\nLemma iff_intro'' :\n forall P Q : Prop,\n (P -> Q) -> (Q -> P) -> (P <-> Q).\nProof.\n split; intros; [apply H | apply H0]; assumption.\nQed.\n\n(** Najbardziej podstawowym kombinatorem jest [;] (średnik). Zapis\n [t1; t2] oznacza \"użyj na obecnym celu taktyki [t1], a następnie\n na wszystkich podcelach wygenerowanych przez [t1] użyj taktyki\n [t2]\".\n\n Zauważmy, że taktyka [split] działa nie tylko na koniunkcjach i\n równoważnościach, ale także wtedy, gdy są one konkluzją pewnej\n implikacji. W takich przypadkach taktyka [split] przed rozbiciem\n ich wprowadzi do kontekstu przesłanki implikacji (a także zmienne\n związane kwantyfikacją uniwersalną), zaoszczędzając nam użycia\n wcześniej taktyki [intros].\n\n Wobec tego, zamiast wprowadzać zmienne do kontekstu przy pomocy\n [intros], rozbijać cel [split]em, a potem jeszcze w każdym\n podcelu z osobna wprowadzać do kontekstu przesłankę implikacji,\n możemy to zrobić szybciej pisząc [split; intros].\n\n Drugie użycie średnika jest uogólnieniem pierwszego. Zapis\n [t; [t1 | t2 | ... | tn]] oznacza \"użyj na obecnym podcelu\n taktyki [t]; następnie na pierwszym wygenerowanym przez nią\n podcelu użyj taktyki [t1], na drugim [t2], etc., a na n-tym\n użyj taktyki [tn]\". Wobec tego zapis [t1; t2] jest jedynie\n skróconą formą [t1; [t2 | t2 | ... | t2]].\n\n Użycie tej formy kombinatora [;] jest uzasadnione tym, że\n w pierwszym z naszych podcelów musimy zaaplikować hipotezę\n [H], a w drugim [H0] — w przeciwnym wypadku nasza taktyka\n zawiodłaby (sprawdź to). Ostatnie użycie tego kombinatora\n jest identyczne jak pierwsze — każdy z podcelów kończymy\n taktyką [assumption].\n\n Dzięki średnikowi dowód naszego twierdzenia skurczył się z\n trzech linijek do jednej, co jest wyśmienitym wynikiem —\n trzy razy mniej linii kodu to trzy razy mniejszy problem\n z jego utrzymaniem. Fakt ten ma jednak również i swoją\n ciemną stronę. Jest nią utrata interaktywności — wykonanie\n taktyki przeprowadza dowód od początku do końca.\n\n Znalezienie odpowiedniego balansu między automatyzacją i\n interaktywnością nie jest sprawą łatwą. Dowodząc twierdzenia\n twoim pierwszym i podstawowym celem powinno być zawsze jego\n zrozumienie, co oznacza dowód mniej lub bardziej interaktywny,\n nieautomatyczny. Gdy uda ci się już udowodnić i zrozumieć dane\n twierdzenie, możesz przejść do automatyzacji. Proces ten jest\n analogiczny jak w przypadku inżynierii oprogramowania — najpierw\n tworzy się działający prototyp, a potem się go usprawnia.\n\n Praktyka pokazuje jednak, że naszym ostatecznym\n celem powinna być pełna automatyzacja, tzn. sytuacja, w\n której dowód każdego twierdzenia (poza zupełnie banalnymi)\n będzie się sprowadzał, jak w powyższym przykładzie, do\n użycia jednej, specjalnie dla niego stworzonej taktyki.\n Ma to swoje uzasadnienie:\n - zrozumienie cudzych dowodów jest zazwyczaj dość trudne,\n co ma spore znaczenie w większych projektach, w których\n uczestniczy wiele osób, z których część odchodzi, a na\n ich miejsce przychodzą nowe\n - przebrnięcie przez dowód interaktywny, nawet jeżeli\n ma walory edukacyjne i jest oświecające, jest zazwyczaj\n czasochłonne, a czas to pieniądz\n - skoro zrozumienie dowodu jest trudne i czasochłonne,\n to będziemy chcieli unikać jego zmieniania, co może\n nastąpić np. gdy będziemy chcieli dodać do systemu\n jakąś funkcjonalność i udowodnić, że po jej dodaniu\n system wciąż działa poprawnie *)\n\n(** **** Ćwiczenie (średnik) *)\n\n(** Poniższe twierdzenia udowodnij najpierw z jak największym zrozumieniem,\n a następnie zautomatyzuj tak, aby całość była rozwiązywana w jednym\n kroku przez pojedynczą taktykę. *)\n\nLemma or_comm_ex :\n forall P Q : Prop, P \\/ Q -> Q \\/ P.\n(* begin hide *)\nProof.\n intros; destruct H; [right | left]; assumption.\nQed.\n(* end hide *)\n\nLemma diamond :\n forall P Q R S : Prop,\n (P -> Q) \\/ (P -> R) -> (Q -> S) -> (R -> S) -> P -> S.\n(* begin hide *)\nProof.\n intros. destruct H.\n apply H0. apply H. assumption.\n apply H1. apply H. assumption.\nRestart.\n intros; destruct H; [apply H0 | apply H1]; apply H; assumption.\nQed.\n(* end hide *)\n\n(** ** [||] (alternatywa) *)\n\nLemma iff_intro''' :\n forall P Q : Prop,\n (P -> Q) -> (Q -> P) -> (P <-> Q).\nProof.\n split; intros; apply H0 || apply H; assumption.\nQed.\n\n(** Innym przydatnym kombinatorem jest [||], który będziemy nazywać\n alternatywą. Żeby wyjaśnić jego działanie, posłużymy się pojęciem\n postępu. Taktyka dokonuje postępu, jeżeli wygenerowany przez nią\n cel różni się od poprzedniego celu. Innymi słowy, taktyka nie\n dokonuje postępu, jeżeli nie zmienia obecnego celu. Za pomocą\n [progress t] możemy sprawdzić, czy taktyka [t] dokona postępu\n na obecnym celu.\n\n Taktyka [t1 || t2] używa na obecnym celu [t1]. Jeżeli [t1] dokona\n postępu, to [t1 || t2] będzie miało taki efekt jak [t1] i skończy\n się sukcesem. Jeżeli [t1] nie dokona postępu, to na obecnym celu\n zostanie użyte [t2]. Jeżeli [t2] dokona postępu, to [t1 || t2]\n będzie miało taki efekt jak [t2] i skończy się sukcesem. Jeżeli\n [t2] nie dokona postępu, to [t1 || t2] zawiedzie i cel się nie\n zmieni.\n\n W naszym przypadku w każdym z podcelów wygenerowanych przez\n [split; intros] próbujemy zaaplikować najpierw [H0], a potem\n [H]. Na pierwszym podcelu [apply H0] zawiedzie (a więc nie\n dokona postępu), więc zostanie użyte [apply H], które zmieni\n cel. Wobec tego [apply H0 || apply H] na pierwszym podcelu\n będzie miało taki sam efekt, jak użycie [apply H]. W drugim\n podcelu [apply H0] skończy się sukcesem, więc tu [apply H0 ||\n apply H] będzie miało taki sam efekt, jak [apply H0]. *)\n\n(** ** [idtac], [do] oraz [repeat] *)\n\nLemma idtac_do_example :\n forall P Q R S : Prop,\n P -> S \\/ R \\/ Q \\/ P.\nProof.\n idtac. intros. do 3 right. assumption.\nQed.\n\n(** [idtac] to taktyka identycznościowa, czyli taka, która nic\n nic robi. Sama w sobie nie jest zbyt użyteczna, ale przydaje\n się do czasem do tworzenia bardziej skomplikowanych taktyk.\n\n Kombinator [do] pozwala nam użyć danej taktyki określoną ilość\n razy. [do n t] na obecnym celu używa [t]. Jeżeli [t] zawiedzie,\n to [do n t] również zawiedzie. Jeżeli [t] skończy się sukcesem,\n to na każdym podcelu wygenerowanym przez [t] użyte zostanie\n [do (n - 1) t]. W szczególności [do 0 t] działa jak [idtac],\n czyli kończy się sukcesem nic nie robiąc.\n\n W naszym przypadku użycie taktyki [do 3 right] sprawi, że\n przy wyborze członu dysjunkcji, którego chcemy dowodzić,\n trzykrotnie pójdziemy w prawo. Zauważmy, że taktyka [do 4 right]\n zawiodłaby, gdyż po 3 użyciach [right] cel nie byłby już\n dysjunkcją, więc kolejne użycie [right] zawiodłoby, a wtedy\n cała taktyka [do 4 right] również zawiodłaby. *)\n\nLemma repeat_example :\n forall P A B C D E F : Prop,\n P -> A \\/ B \\/ C \\/ D \\/ E \\/ F \\/ P.\nProof.\n intros. repeat right. assumption.\nQed.\n\n(** Kombinator [repeat] powtarza daną taktykę, aż ta rozwiąże cel,\n zawiedzie, lub nie zrobi postępu. Formalnie: [repeat t] używa\n na obecnym celu taktyki [t]. Jeżeli [t] rozwiąże cel, to\n [repeat t] kończy się sukcesem. Jeżeli [t] zawiedzie lub nie\n zrobi postępu, to [repeat t] również kończy się sukcesem.\n Jeżeli [t] zrobi jakiś postęp, to na każdym wygenerowaym przez\n nią celu zostanie użyte [repeat t].\n\n W naszym przypadku [repeat right] ma taki efekt, że przy wyborze\n członu dysjunkcji wybieramy człon będący najbardziej na prawo,\n tzn. dopóki cel jest dysjunkcją, aplikowana jest taktyka [right],\n która wybiera prawy człon. Kiedy nasz cel przestaje być dysjunkcją,\n taktyka [right] zawodzi i wtedy taktyka [repeat right] kończy swoje\n działanie sukcesem. *)\n\n(** ** [try] i [fail] *)\n\nLemma iff_intro4 :\n forall P Q : Prop,\n (P -> Q) -> (Q -> P) -> (P <-> Q).\nProof.\n split; intros; try (apply H0; assumption; fail);\n try (apply H; assumption; fail).\nQed.\n\n(** [try] jest kombinatorem, który zmienia zachowanie przekazanej mu\n taktyki. Jeżeli [t] zawiedzie, to [try t] zadziała jak [idtac],\n czyli nic nie zrobi i skończy się sukcesem. Jeżeli [t] skończy się\n sukcesem, to [try t] również skończy się sukcesem i będzie miało\n taki sam efekt, jak [t]. Tak więc, podobnie jak [repeat], [try]\n nigdy nie zawodzi.\n\n [fail] jest przeciwieństwem [idtac] — jest to taktyka, która zawsze\n zawodzi. Sama w sobie jest bezużyteczna, ale w tandemie z [try]\n oraz średnikiem daje nam pełną kontrolę nad tym, czy taktyka\n zakończy się sukcesem, czy zawiedzie, a także czy dokona postępu.\n\n Częstym sposobem użycia [try] i [fail] jest [try (t; fail)]. Taktyka\n ta na obecnym celu używa [t]. Jeżeli [t]\n rozwiąże cel, to [fail] nie zostanie wywołane i całe [try (t; fail)]\n zadziała tak jak [t], czyli rozwiąże cel. Jeżeli [t] nie rozwiąże celu,\n to na wygenerowanych podcelach wywoływane zostanie [fail], które\n zawiedzie — dzięki temu [t; fail] również zawiedzie, nie dokonując\n żadnych zmian w celu (nie dokona postępu), a całe [try (t; fail)]\n zakończy się sukcesem, również nie dokonując w celu żadnych zmian.\n Wobec tego działanie [try (t; fail)] można podsumować tak: \"jeżeli [t]\n rozwiąże cel to użyj jej, a jeżeli nie, to nic nie rób\".\n\n Postaraj się dokładnie zrozumieć, jak opis ten ma się do powyższego\n przykładu — spróbuj usunąć jakieś [try], [fail] lub średnik i zobacz,\n co się stanie.\n\n Oczywiście przykład ten jest bardzo sztuczny — najlepszym pomysłem\n udowodnienia tego twierdzenia jest użycie ogólnej postaci średnika\n [t; t1 | ... | tn], tak jak w przykładzie [iff_intro'']. Idiom\n [try (t; fail)] najlepiej sprawdza się, gdy użycie średnika w ten\n sposób jest niepraktyczne, czyli gdy celów jest dużo, a rozwiązać\n automatycznie potrafimy tylko część z nich. Możemy użyć go wtedy,\n żeby pozbyć się prostszych przypadków nie zaśmiecając sobie jednak\n kontekstu w pozostałych przypadkach. Idiom ten jest też dużo\n bardziej odporny na przyszłe zmiany w programie, gdyż użycie go\n nie wymaga wiedzy o tym, ile podcelów zostanie wygenerowanych.\n\n Przedstawione kombinatory są najbardziej użyteczne i stąd\n najpowszechniej używane. Nie są to jednak wszystkie kombinatory\n — jest ich znacznie więcej. Opisy taktyk i kombinatorów\n z biblioteki standardowej znajdziesz w\n #\n manualu#. *)\n\n(** * Inne spójniki? (TODO) *)\n\n(** ** Różnica między \"lub\" i \"albo\" *)\n\nDefinition xor (A B : Prop) : Prop :=\n (A /\\ ~ B) \\/ (~ A /\\ B).\n\nLemma xor_irrefl :\n forall P : Prop, ~ xor P P.\n(* begin hide *)\nProof.\n unfold xor. intros A H.\n destruct H as [[p np] | [np p]].\n apply np. assumption.\n apply np. assumption.\nQed.\n(* end hide *)\n\nLemma xor_comm :\n forall P Q : Prop, xor P Q -> xor Q P.\n(* begin hide *)\nProof.\n unfold xor. intros P Q H.\n destruct H as [[p nq] | [q np]].\n right. split; assumption.\n left. split; assumption.\nQed.\n(* end hide *)\n\nLemma xor_comm' :\n forall P Q : Prop, xor P Q <-> xor Q P.\n(* begin hide *)\nProof.\n split; apply xor_comm.\nQed.\n(* end hide *)\n\nLemma xor_cotrans :\n (forall P : Prop, P \\/ ~ P) ->\n (forall P Q R : Prop, xor P Q -> xor P R \\/ xor Q R).\n(* begin hide *)\nProof.\n unfold xor. intros LEM P Q R H.\n destruct H as [[p nq] | [q np]].\n destruct (LEM R) as [r | nr].\n right. right. split; assumption.\n left. left. split; assumption.\n destruct (LEM R) as [r | nr].\n left. right. split; assumption.\n right. left. split; assumption.\nQed.\n(* end hide *)\n\nLemma Irrefutable_xor_cotrans :\n forall P Q R : Prop, ~ ~ (xor P Q -> xor P R \\/ xor Q R).\n(* begin hide *)\nProof. unfold xor; firstorder. Qed.\n(* end hide *)\n\nLemma not_iff_xor :\n forall P Q : Prop, xor P Q -> ~ (P <-> Q).\n(* begin hide *)\nProof.\n unfold xor, iff.\n intros P Q H1 H2.\n destruct H2 as [pq qp], H1 as [[p nq] | [np q]].\n apply nq, pq. assumption.\n apply np, qp. assumption.\nQed.\n(* end hide *)\n\nLemma Irrefutable_xor_not_iff :\n forall P Q : Prop, ~ ~ (~ (P <-> Q) -> xor P Q).\n(* begin hide *)\nProof. unfold xor; firstorder. Qed.\n(* end hide *)\n\nLemma xor_spec :\n forall P Q : Prop, xor P Q <-> (P \\/ Q) /\\ (~ P \\/ ~ Q).\n(* begin hide *)\nProof.\n unfold xor, iff. split.\n intros [[p nq] | [np q]].\n split.\n left. assumption.\n right. assumption.\n split.\n right. assumption.\n left. assumption.\n intros [[p | q] [np | nq]].\n contradiction.\n left. split; assumption.\n right. split; assumption.\n contradiction.\nQed.\n(* end hide *)\n\nLemma xor_False_r :\n forall P : Prop, xor P False <-> P.\n(* begin hide *)\nProof.\n unfold xor, iff. split.\n intro H. destruct H as [[p _] | [_ f]].\n assumption.\n contradiction.\n intro p. left. split.\n assumption.\n intro f. contradiction.\nQed.\n(* end hide *)\n\nLemma xor_False_l :\n forall P : Prop, xor False P <-> P.\n(* begin hide *)\nProof.\n split.\n intro x. apply xor_comm in x. apply xor_False_r. assumption.\n intro p. unfold xor. right. split.\n intro f. contradiction.\n assumption.\nQed.\n(* end hide *)\n\nLemma xor_True_l :\n forall P : Prop, xor True P <-> ~ P.\n(* begin hide *)\nProof.\n unfold xor, iff. split.\n intros [[_ np] | [f _]].\n assumption.\n contradiction.\n intro np. left. split.\n trivial.\n assumption.\nQed.\n(* end hide *)\n\nLemma xor_True_r :\n forall P : Prop, xor P True <-> ~ P.\n(* begin hide *)\nProof.\n split.\n destruct 1 as [[p nt] | [np t]].\n contradiction.\n assumption.\n intro. right. split.\n assumption.\n trivial.\nQed.\n(* end hide *)\n\nModule xor_new.\n\nInfix \"`xor`\" := xor (at level 85, right associativity).\n\nParameters P Q R : Prop.\n\n(** ** [xor] *)\n\nLemma xor_True_l :\n True `xor` P <-> ~ P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_True_r :\n P `xor` True <-> ~ P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_False_l :\n False `xor` P <-> P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_False_r :\n P `xor` False <-> P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_True_l' :\n P -> P `xor` Q <-> ~ Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_True_r' :\n Q -> P `xor` Q <-> ~ P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_False_l' :\n ~ P -> P `xor` Q <-> Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_False_r' :\n ~ Q -> P `xor` Q <-> P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_irrefl :\n P `xor` P <-> False.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_comm :\n P `xor` Q <-> Q `xor` P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_xor_assoc :\n ~ ~ (P `xor` (Q `xor` R) <-> (P `xor` Q) `xor` R).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma or_xor :\n P `xor` Q -> P \\/ Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma and_xor_l :\n (P `xor` Q) /\\ R <-> (P /\\ R) `xor` (Q /\\ R).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma and_xor_r :\n P /\\ (Q `xor` R) <-> (P /\\ Q) `xor` (P /\\ R).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_not_xor_l :\n ~ ~ (~ (P `xor` Q) <-> ~ P `xor` Q).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_not_xor_r :\n ~ ~ (~ (P `xor` Q) <-> P `xor` ~ Q).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_xor_not :\n ~ ~ ((~ P) `xor` ~ Q -> P `xor` Q).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_not_conv :\n P `xor` Q -> ~ P `xor` ~ Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma xor_isolation :\n (P /\\ ~ Q) `xor` (P /\\ Q) -> P.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_xor_isolation_conv :\n ~ ~ (P -> (P /\\ ~ Q) `xor` (P /\\ Q)).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_dd_and_xor :\n ~ ~ (P /\\ (~ P `xor` Q) -> P /\\ Q).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma dd_and_xor_conv :\n P /\\ Q -> P /\\ (~ P `xor` Q).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma dd_or_xor_r :\n P \\/ (P `xor` Q) -> P \\/ Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma Irrefutable_dd_or_xor_r_conv :\n ~ ~ (P \\/ Q -> P \\/ (P `xor` Q)).\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma dd_impl_xor_r :\n P -> (~ P `xor` Q) <-> P -> Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nLemma dd_impl_xor_l :\n (P `xor` Q) -> Q <-> P -> Q.\n(* begin hide *)\nProof. unfold xor; tauto. Qed.\n(* end hide *)\n\nEnd xor_new.\n\n(** ** i/lub *)\n\nDefinition andor (P Q : Prop) : Prop := P \\/ Q \\/ (P /\\ Q).\n\nLemma and_or_l :\n forall P Q : Prop, P /\\ Q -> P \\/ Q.\n(* begin hide *)\nProof.\n destruct 1 as [p q]. left. assumption.\nQed.\n(* end hide *)\n\nLemma and_or_r :\n forall P Q : Prop, P /\\ Q -> P \\/ Q.\n(* begin hide *)\nProof.\n destruct 1 as [p q]. right. assumption.\nQed.\n(* end hide *)\n\nLemma andor_or :\n forall P Q : Prop, andor P Q <-> P \\/ Q.\n(* begin hide *)\nProof.\n unfold andor. intros P Q. split.\n - intros [p | [q | [p q]]].\n + left. assumption.\n + right. assumption.\n + left. assumption.\n - intros [p | q].\n + left. assumption.\n + right. left. assumption.\nQed.\n(* end hide *)\n\n(** *** i/lub po raz drugi *)\n\nDefinition andxor (P Q : Prop) : Prop := xor P (xor Q (P /\\ Q)).\n\nLemma andxor_or :\n (forall P : Prop, P \\/ ~ P) ->\n forall P Q : Prop, andxor P Q <-> P \\/ Q.\n(* begin hide *)\nProof.\n unfold andxor. intros lem P Q. split.\n - intros [[p _] | [_ [[q _] | H]]].\n + left. assumption.\n + right. assumption.\n + destruct H as (nq & _ & q). contradiction.\n - intros [p | q].\n + left. split.\n * assumption.\n * unfold xor. intros [[q npq] | (nq & _ & q)].\n -- apply npq. split; assumption.\n -- contradiction.\n + destruct (lem P) as [p | np].\n * left. split; [assumption |]. unfold xor. tauto.\n * right. split; [assumption |]. unfold xor. tauto.\nQed.\n(* end hide *)\n\nLemma Irrefutable_andxor_or :\n forall P Q : Prop, ~ ~ (andxor P Q <-> P \\/ Q).\n(* begin hide *)\nProof. unfold andxor; firstorder. Qed.\n(* end hide *)\n\n(** ** Ani [P] ani [Q], czyli negacja dysjunkcji *)\n\nDefinition nor (P Q : Prop) : Prop := ~ (P \\/ Q).\n\nLemma nor_comm :\n forall P Q : Prop,\n nor P Q <-> nor Q P.\n(* begin hide *)\nProof.\n unfold nor. intros P Q. split.\n - intros f [q | p]; apply f; [right | left]; assumption.\n - intros f [p | q]; apply f; [right | left]; assumption.\nQed.\n(* end hide *)\n\nLemma not_nor_assoc :\n exists P Q R : Prop,\n nor (nor P Q) R /\\ ~ nor P (nor Q R).\n(* begin hide *)\nProof.\n unfold nor. exists True, True, False. tauto.\nQed.\n(* end hide *)\n\nLemma nor_True_l :\n forall P : Prop,\n nor True P <-> False.\n(* begin hide *)\nProof.\n unfold nor.\n intros P. split.\n - intros f. apply f. left. trivial.\n - contradiction.\nQed.\n(* end hide *)\n\nLemma nor_True_r :\n forall P : Prop,\n nor P True <-> False.\n(* begin hide *)\nProof.\n unfold nor. intros P; split.\n - intros f. apply f. right. trivial.\n - contradiction.\nQed.\n(* end hide *)\n\nLemma nor_False_l :\n forall P : Prop,\n nor False P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nor.\n split.\n - intros f p. apply f. right. assumption.\n - intros np [f | p]; contradiction.\nQed.\n(* end hide *)\n\nLemma nor_False_r :\n forall P : Prop,\n nor P False <-> ~ P.\n(* begin hide *)\nProof.\n unfold nor. intros P; split.\n - intros f p. apply f. left. assumption.\n - intros np [p | f]; contradiction.\nQed.\n(* end hide *)\n\nLemma nor_antiidempotent :\n forall P : Prop,\n nor P P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nor. split.\n - intros f p. apply f. left. assumption.\n - intros f [p | p]; contradiction.\nQed.\n(* end hide *)\n\n(** W nieco innej wersji. *)\n\nDefinition nor' (P Q : Prop) : Prop := ~ P /\\ ~ Q.\n\nLemma nor'_comm :\n forall P Q : Prop,\n nor' P Q <-> nor' Q P.\n(* begin hide *)\nProof.\n unfold nor'.\n intros P Q. split.\n - intros [np nq]. split; assumption.\n - intros [nq np]. split; assumption.\nQed.\n(* end hide *)\n\nLemma not_nor'_assoc :\n exists P Q R : Prop,\n nor' (nor' P Q) R /\\ ~ nor' P (nor' Q R).\n(* begin hide *)\nProof.\n unfold nor'. exists True, True, False. tauto.\nQed.\n(* end hide *)\n\nLemma nor'_True_l :\n forall P : Prop,\n nor' True P <-> False.\n(* begin hide *)\nProof.\n unfold nor'.\n intros P. split.\n - intros [? _]. contradiction.\n - contradiction.\nQed.\n(* end hide *)\n\nLemma nor'_True_r :\n forall P : Prop,\n nor' P True <-> False.\n(* begin hide *)\nProof.\n unfold nor'. intros P; split.\n - intros [_ ?]. contradiction.\n - contradiction.\nQed.\n(* end hide *)\n\nLemma nor'_False_l :\n forall P : Prop,\n nor' False P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nor'. intros P. split.\n - intros [_ np]. assumption.\n - intros np. split.\n + intros e. contradiction.\n + assumption.\nQed.\n(* end hide *)\n\nLemma nor'_False_r :\n forall P : Prop,\n nor' P False <-> ~ P.\n(* begin hide *)\nProof.\n unfold nor'. intros P; split.\n - intros [np _]. assumption.\n - intros np. split.\n + assumption.\n + intros e. contradiction.\nQed.\n(* end hide *)\n\nLemma nor'_antiidempotent :\n forall P : Prop,\n nor' P P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nor'. split.\n - intros [np _]. assumption.\n - intros np. split; assumption.\nQed.\n(* end hide *)\n\n(** Równoważność *)\n\nLemma nor_nor' :\n forall P Q : Prop, nor P Q <-> nor' P Q.\n(* begin hide *)\nProof.\n unfold nor, nor'; split.\n - intros f. split.\n + intros p. apply f. left. assumption.\n + intros q. apply f. right. assumption.\n - intros [np nq] [p | q]; contradiction.\nQed.\n(* end hide *)\n\n(** ** [nand], czyli negacja koniunkcji *)\n\nDefinition nand (P Q : Prop) : Prop := ~ (P /\\ Q).\n\nLemma nand_comm :\n forall P Q : Prop,\n nand P Q <-> nand Q P.\n(* begin hide *)\nProof.\n unfold nand.\n intros P. split.\n - intros f [q p]. apply f; split; assumption.\n - intros f [p q]. apply f; split; assumption.\nQed.\n(* end hide *)\n\nLemma not_nand_assoc :\n exists P Q R : Prop,\n nand (nand P Q) R /\\ ~ nand P (nand Q R).\n(* begin hide *)\nProof.\n unfold nand. exists True, True, False. tauto.\nQed.\n(* end hide *)\n\nLemma nand_True_l :\n forall P : Prop,\n nand True P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nand.\n intros P. split.\n - intros f p. apply f. split; trivial.\n - intros np [_ p]. contradiction.\nQed.\n(* end hide *)\n\nLemma nand_True_r :\n forall P : Prop,\n nand P True <-> ~ P.\n(* begin hide *)\nProof.\n unfold nand; intros P; split.\n - intros f p. apply f. split; trivial.\n - intros np [p _]. contradiction.\nQed.\n(* end hide *)\n\nLemma nand_False_l' :\n forall P : Prop,\n nand False P.\n(* begin hide *)\nProof.\n unfold nand. intros P [[] _].\nQed.\n(* end hide *)\n\nLemma nand_False_l :\n forall P : Prop,\n nand False P <-> True.\n(* begin hide *)\nProof.\n split; intros.\n - trivial.\n - apply nand_False_l'.\nQed.\n(* end hide *)\n\nLemma nand_False_r :\n forall P : Prop,\n nand P False <-> True.\n(* begin hide *)\nProof.\n unfold nand; intros P; split.\n - intros _. trivial.\n - intros _ [p f]. contradiction.\nQed.\n(* end hide *)\n\nLemma nand_antiidempotent :\n forall P : Prop,\n nand P P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nand. split.\n - intros f p. apply f. split; assumption.\n - intros np [p _]. contradiction.\nQed.\n(* end hide *)\n\n(** ** Antyimplikacja, czyli negacja implikacji *)\n\nDefinition nimpl (P Q : Prop) : Prop := ~ (P -> Q).\n\nLemma nimpl_False_l :\n forall P : Prop,\n ~ nimpl False P.\n(* begin hide *)\nProof.\n unfold nimpl.\n intros P f. apply f. intros c. contradiction.\nQed.\n(* end hide *)\n\nLemma nimpl_False_r:\n forall P : Prop,\n nimpl P False <-> ~ ~ P.\n(* begin hide *)\nProof.\n unfold nimpl.\n intros P; split; intros; assumption.\nQed.\n(* end hide *)\n\nLemma nimpl_True_l :\n forall P : Prop,\n nimpl True P <-> ~ P.\n(* begin hide *)\nProof.\n unfold nimpl.\n intros P; split.\n - intros f p. apply f. intros _. assumption.\n - intros f p. apply f, p. trivial.\nQed.\n(* end hide *)\n\nLemma nimpl_True_r :\n forall P : Prop,\n ~ nimpl P True.\n(* begin hide *)\nProof.\n unfold nimpl.\n intros P f. apply f. intros _. trivial.\nQed.\n(* end hide *)\n\nLemma nimpl_conv :\n forall P Q : Prop,\n nimpl (~ P) (~ Q) -> nimpl P Q.\n(* begin hide *)\nProof.\n unfold nimpl.\n intros P Q f g.\n apply f. intros np q.\nAbort.\n(* end hide *)\n\nLemma nimpl_conv :\n forall P Q : Prop,\n nimpl P Q -> nimpl (~ Q) (~ P).\n(* begin hide *)\nProof.\n unfold nimpl.\n intros P Q f g.\n apply f. intros p.\nAbort.\n(* end hide *)\n\n(** **** Ćwiczenie (conditioned disjunction) *)\n\n(** #\n Wikipedia# podaje poniższą definicję pewnego dziwnego spójnika: *)\n\nDefinition conditioned_disjunction (P Q R : Prop) : Prop :=\n (Q -> P) /\\ (~ Q -> R).\n\n(** Wyraź za jego pomocą wszystkie podstawowe spójniki, tj. implikację, dysjunkcję,\n koniunkcje i negację.\n\n Udowodnij też garść twierdzeń mówiących, co się stanie, gdy za [P], [Q] lub [R]\n wstawić [True] lub [False]. *)\n\n(* begin hide *)\n(* TODO: tu rozwiązania zadań o [conditioned_disjunction] *)\n(* end hide *)\n\n(** * Inne kwantyfikatory? (TODO) *)\n\n(** Poznaliśmy jak dotąd trzy kwantyfikatory: uniwersalny ([forall]), egzystencjalny\n ([exists]) oraz unikalny, który był zdefiniowany za pomocą dwóch poprzednich\n oraz relacji równości ([=]).\n\n Skoro mogliśmy zdefiniować nowy kwantyfikator ze starych, to należy zadać\n sobie pytanie: czy istnieją jeszcze jakieś inne kwantyfikatory? I czy są\n one ciekawe?\n\n Odpowiedź na pierwsze pytanie brzmi: tak, i to nieskończenie wiele. Na drugie\n zaś: większość z nich nie jest zbyt ciekawa. Nie na tyle, żeby o nich tutaj\n wspominać. *)\n\n(** ** Kwantyfikator unikatowy *)\n\nDefinition unique {A : Type} (P : A -> Prop) : Prop :=\n exists x : A, P x /\\ forall y : A, P y -> x = y.\n\n(** Poznawszy relację równości oraz kwantyfikatory uniwersalny i\n egzystencjalny, możemy zdefiniować inny bardzo ważny \"kwantyfikator\",\n a mianowicie kwantyfikator unikatowy, który głosi, że istnieje\n dokładnie jeden obiekt spełniający daną właściwość. *)\n\n(** ** Kwantyfikator [xor]owy *)\n\n(** Zauważmy, że kwantyfikator egzystencjalny jest podobny do \"nieskończonej\"\n dysjunkcji: [exists x : A, P x] znaczyłoby to samo, co [P x_0 \\/ P x_1 \\/ ...],\n gdyby rzecz jasna dało się takie nieskończenie długaśne zdanie zapisać. Ale\n się nie da - i dlatego właśnie mamy kwantyfikator egzystencjalny.\n\n W poprzednim podrozdziale poznaliśmy spójnik [xor], który możemy interpretować\n jako polskie \"albo\". [xor P Q] znaczy \"albo zachodzi P (i nie zachodzi Q, albo\n zachodzi Q (i nie zachodzi P)\", a zatem [xor] to wariant zwykłej dysjunkcji [\\/],\n który jednak wyklucza możliwość zajścia więcej niż jednego ze swoich członów.\n\n Nieco sztucznym, acz potencjalnie ciekawym, kwantyfikatorem może być\n \"kwantyfikator xorowy\", który działa jak nieskończony [xor] - ma się\n on do [xor]a tak, jak kwantyfikator egzystencjalny do dysjunkcji. Zdefiniuj\n ten kwantyfikator, a następnie sprawdź, czy ma jakieś ciekawe właściwości. *)\n\n(* begin hide *)\nDefinition qxor {A : Type} (P : A -> Prop) : Prop :=\n exists x : A, P x /\\ forall y : A, x <> y -> ~ P y.\n(* end hide *)\n\nLemma ex_qxor :\n forall {A : Type} (P : A -> Prop),\n qxor P -> ex P.\n(* begin hide *)\nProof.\n intros A P (x & p & _).\n exists x. assumption.\nQed.\n(* end hide *)\n\nLemma qxor_True_two_elems :\n forall {A : Type} {x y : A},\n x <> y -> ~ qxor (fun _ : A => True).\n(* begin hide *)\nProof.\n intros A x y Hneq (z & _ & H).\n apply (H x).\n - intros ->. apply (H y); trivial.\n - trivial.\nQed.\n(* end hide *)\n\nLemma qxor_False :\n forall A : Type,\n ~ qxor (fun _ : A => False).\n(* begin hide *)\nProof.\n intros A (z & e & _).\n assumption.\nQed.\n(* end hide *)\n\n(** * Logika pierwszego rzędu a logika wyższego rzędu (TODO) *)\n\n(** ** Logika pierwszego rzędu *)\n\n(** ** Logika drugiego rzędu *)\n\n(** ** Logika wyższego rzędu *)\n\n(** * Paradoksy autoreferencji *)\n\n(** ** Paradoks Curry'ego *)\n\nLemma Curry's_paradox :\n forall P Q : Prop,\n (P <-> (P -> Q)) -> Q.\nProof.\n destruct 1.\n apply H.\n apply H0. intro. apply H; assumption.\n apply H0. intro. apply H; assumption.\nQed.\n\n(** **** Ćwiczenie *)\n\n(** TODO: napisać polecenie *)\n\n(* begin hide *)\nLemma mutual_reference :\n forall P Q : Prop,\n (P <-> (Q <-> True)) ->\n (Q <-> (P <-> False)) ->\n False.\nProof.\n firstorder.\nQed.\n(* end hide *)\n\n(** ** Paradoks golibrody *)\n\n(** Języki naturalne, jakimi ludzie posługują się w życiu codziennym\n (polski, angielski suahili, język indian Navajo) zawierają spory\n zestaw spójników oraz kwantyfikatorów (\"i\", \"a\", \"oraz\", \"lub\",\n \"albo\", \"jeżeli ... to\", \"pod warunkiem, że \", \"wtedy\", i wiele\n innych).\n\n Należy z całą stanowczością zaznaczyć, że te spójniki i kwantyfikatory,\n a w szczególności ich intuicyjna interpretacja, znacznie różnią się\n od analogicznych spójników i kwantyfikatorów logicznych, które mieliśmy\n okazję poznać w tym rozdziale. Żeby to sobie uświadomić, zapoznamy się\n z pewnego rodzaju \"paradoksem\". *)\n\nLemma barbers_paradox :\n forall (man : Type) (barber : man)\n (shaves : man -> man -> Prop),\n (forall x : man, shaves barber x <-> ~ shaves x x) -> False.\n(* begin hide *)\nProof.\n intros. destruct (H barber). apply H0.\n apply H1. intro. apply H0; assumption.\n apply H1. intro. apply H0; assumption.\nQed.\n(* end hide *)\n\n(** Twierdzenie to formułowane jest zazwyczaj tak: nie istnieje człowiek,\n który goli wszystkich tych (i tylko tych), którzy sami siebie nie golą.\n\n Ale cóż takiego znaczy to przedziwne zdanie? Czy matematyka dają nam\n magiczną, aprioryczną wiedzę o fryzjerach?\n\n Odczytajmy je poetycko. Wyobraźmy sobie pewne miasteczko. Typ [man]\n będzie reprezentował jego mieszkańców. Niech term [barber] typu [man]\n oznacza hipotetycznego golibrodę. Hipotetycznego, gdyż samo użycie\n jakiejś nazwy nie powoduje automatycznie, że nazywany obiekt istnieje\n (przykładów jest masa, np. jednorożce, sprawiedliwość społeczna).\n\n Mamy też relację [shaves]. Będziemy ją interpretować w ten sposób, że\n [shaves a b] zachodzi, gdy [a] goli brodę [b]. Nasza hipoteza\n [forall x : man, shaves barber x <-> ~ shaves x x] jest zawoalowanym\n sposobem podania następującej definicji: golibrodą nazwiemy te osoby,\n który golą wszystkie te i tylko te osoby, które same siebie nie golą.\n\n Póki co sytuacja rozwija się w całkiem niekontrowersyjny sposób. Żeby\n zburzyć tę sielankę, możemy zadać sobie następujące pytanie: czy\n golibroda rzeczywiście istnieje? Dziwne to pytanie, gdy na każdym\n rogu ulicy można spotkać fryzjera, ale nie dajmy się zwieść.\n\n W myśl rzymskich sentencji \"quis custodiet ipsos custodes?\" (\"kto będzie\n pilnował strażników?\") oraz \"medice, cure te ipsum!\" (\"lekarzu, wylecz\n sam siebie!\") możemy zadać dużo bardziej konkretne pytanie: kto goli\n brody golibrody? A idąc jeszcze krok dalej: czy golibroda goli sam siebie?\n\n Rozstrzygnięcie jest banalne i wynika wprost z definicji: jeśli golibroda\n ([barber]) to ten, kto goli ([shaves barber x]) wszystkich tych i tylko\n tych ([forall x : man]), którzy sami siebie nie golą ([~ shaves x x]), to\n podstawiając [barber] za [x] otrzymujemy sprzeczność: [shaves barber\n barber] zachodzi wtedy i tylko wtedy, gdy [~ shaves barber barber].\n\n Tak więc golibroda, zupełnie jak Święty Mikołaj, nie istnieje. Zdanie to\n nie ma jednak wiele wspólnego ze światem rzeczywistym: wynika ono jedynie\n z takiej a nie innej, przyjętej przez nas całkowicie arbitralnie definicji\n słowa \"golibroda\". Można to łatwo zobrazować, przeformułowywując powyższe\n twierdzenie z użyciem innych nazw: *)\n\nLemma barbers_paradox' :\n forall (A : Type) (x : A) (P : A -> A -> Prop),\n (forall y : A, P x y <-> ~ P y y) -> False.\n(* begin hide *)\nProof.\n intros. destruct (H x). apply H0.\n apply H1. intro. apply H0; assumption.\n apply H1. intro. apply H0; assumption.\nQed.\n(* end hide *)\n\n(** Nieistnienie \"golibrody\" i pokrewny mu paradoks pytania \"czy golibroda\n goli sam siebie?\" jest konsekwencją wyłącznie formy powyższego zdania\n logicznego i nie mówi nic o rzeczywistoświatych golibrodach.\n\n Paradoksalność całego \"paradoksu\" bierze się z tego, że typom, zmiennym\n i relacjom specjalnie nadano takie nazwy, żeby zwykły człowiek bez\n głębszych dywagacji nad definicją słowa \"golibroda\" przjął, że golibroda\n istnieje. Robiąc tak, wpada w sidła pułapki zastawionej przez logika i\n zostaje trafiony paradoksalną konkluzją: golibroda nie istnieje. *)\n\n(** ** Inne paradoksy autoreferencji *)\n\n(** **** Ćwiczenie *)\n\n(** Poniższą zagadkę pozwolę sobie wesoło nazwać \"paradoks hetero\". Zagadka\n brzmi tak:\n\n Niektóre słowa opisują same siebie, np. słowo \"krótki\" jest krótkie,\n a niektóre inne nie, np. słowo \"długi\" nie jest długie. Podobnie słowo\n \"polski\" jest słowem polskim, ale słowo \"niemiecki\" nie jest słowem\n niemieckim. Słowa, które nie opisują samych siebie będziemy nazywać\n słowami heterologicznymi. Pytanie: czy słowo \"heterologiczny\" jest\n heterologiczne? *)\n\n(** **** Ćwiczenie *)\n\n(** TODO:\n - paradoks Richarda\n - Hilbert-Bernays: https://en.wikipedia.org/wiki/Hilbert-Bernays_paradox\n - Barbershop: https://en.wikipedia.org/wiki/Barbershop_paradox\n - paradoks kłamcy *)\n\n(** **** Ćwiczenie *)\n\n(** A jak jest z poniższym paradoksem wujka Janusza?\n\n Wujek Janusz lubi tych (i tylko tych) członków rodziny, którzy sami\n siebie nie lubią oraz nie lubi tych (i tylko tych), którzy sami siebie\n lubią. Czy wujek Janusz lubi sam siebie? *)\n\n(** **** Ćwiczenie *)\n\n(** Powyższe ćwiczenie miało być ostatnim, ale co tam, dam jeszcze trochę.\n Co czuje serce twoje (ewentualnie: co widzisz przed oczyma duszy swojej)\n na widok poniższych wesołych zdań?\n\n \"To zdanie jest fałszywe.\"\n\n \"Zdanie po prawej jest fałszywe. Zdanie po lewej jest prawdziwe.\"\n\n \"Zdanie po prawej jest prawdziwe. Zdanie po lewej jest fałszywe.\"\n*)\n\n(** * Predykatywizm i kodowania impredykatywne (TODO) *)\n\n(* begin hide *)\n(* TODO: Tautologie na kodowaniach impredykatywnych jako ćwiczenia z funkcji anonimowych *)\n(* end hide *)\n\nDefinition iand (P Q : Prop) : Prop :=\n forall C : Prop, (P -> Q -> C) -> C.\n\nDefinition ior (P Q : Prop) : Prop :=\n forall C : Prop, (P -> C) -> (Q -> C) -> C.\n\nDefinition iTrue : Prop :=\n forall C : Prop, C -> C.\n\nDefinition iFalse : Prop :=\n forall C : Prop, C.\n\nLemma iand_spec :\n forall P Q : Prop,\n iand P Q <-> P /\\ Q.\n(* begin hide *)\nProof.\n unfold iand. split.\n intro H. apply H. intros p q. split.\n assumption.\n assumption.\n intros [p q] C H. apply H.\n assumption.\n assumption.\nQed.\n(* end hide *)\n\nLemma ior_spec :\n forall P Q : Prop,\n ior P Q <-> P \\/ Q.\n(* begin hide *)\nProof.\n unfold ior. split.\n intro H. apply H.\n intro p. left. assumption.\n intro q. right. assumption.\n intros [p | q] C pc qc.\n apply pc. assumption.\n apply qc. assumption.\nQed.\n(* end hide *)\n\nLemma iTrue_spec :\n iTrue <-> True.\n(* begin hide *)\nProof.\n unfold iTrue. split.\n intros _. trivial.\n intros _ C c. assumption.\nQed.\n(* end hide *)\n\nLemma iFalse_False :\n iFalse <-> False.\n(* begin hide *)\nProof.\n unfold iFalse. split.\n intro H. apply H.\n contradiction.\nQed.\n(* end hide *)\n\nDefinition iexists (A : Type) (P : A -> Prop) : Prop :=\n forall C : Prop, (forall x : A, P x -> C) -> C.\n\nLemma iexists_spec :\n forall (A : Type) (P : A -> Prop),\n iexists A P <-> exists x : A, P x.\n(* begin hide *)\nProof.\n unfold iexists. split.\n intro H. apply H. intros x p. exists x. assumption.\n intros [x p] C H. apply (H x). assumption.\nQed.\n(* end hide *)\n\nDefinition ieq {A : Type} (x y : A) : Prop :=\n forall C : Prop, ((x = y) -> C) -> C.\n\nDefinition ieq' {A : Type} (x : A) : A -> Prop :=\n fun y : A =>\n forall P : A -> Prop, P x -> P y.\n\nLemma ieq_spec :\n forall (A : Type) (x y : A),\n ieq x y <-> x = y.\n(* begin hide *)\nProof.\n unfold ieq. split.\n intro H. apply H. trivial.\n intros [] C H. apply H. reflexivity.\nQed.\n(* end hide *)\n\nLemma ieq'_spec :\n forall (A : Type) (x y : A),\n ieq' x y <-> x = y.\n(* begin hide *)\nProof.\n unfold ieq'. split.\n intro H. apply H. reflexivity.\n intros [] P px. assumption.\nQed.\n(* end hide *)\n\n(** * Spójniki pozytywne i negatywne (TODO) *)\n\n(** TODO:\n - implikacja jest negatywna\n - koniunkcja jest negatywna\n - dysjunkcja jest pozytywna\n - fałsz jest pozytywny\n - prawda jest negatywna\n - słaba negacja jest negatywna\n - silna negacja jest pozytywna\n - równoważność jest negatywna\n*)\n\n(** * Esencjalizm vs strukturalizm (TODO) *)\n\n(** * Harmonia logiki konstruktywnej i prawo zachowania informacji (TODO) *)\n\n(** * Logika intuicjonistyczna jako logika certyfikatów (TODO) *)\n\n(** * Aksjomaty i pojęcie \"tabu\" (TODO) *)\n\n(** * Klasyfikacja zdań (TODO) *)\n\n(** Tutaj drobna klasyfikacja na coś w stylu:\n - zdania prawdziwe ([P] zachodzi)\n - zdania fałszywe ([~ P] zachodzi)\n - zdania niezaprzeczalne ([~ ~ P] zachodzi)\n - zdania kontyngentne ([P] jest fałszywym zdaniem postaci\n [forall x : A, Q x] i zachodzi [exists x : A, Q x]. Inne\n podejście: tylko w kontekście, w którym zdanie [P] składa\n się z nieznanych części, np. [P -> Q] jest kontyngentne,\n bo [P -> P] zachodzi, zaś [True -> False] nie zachodzi.\n - zdania klasycznie prawdziwe ([P] zachodzi w logice klasycznej)\n - zdania tabu ([P] implikuje jakieś inne tabu, np. [LEM])\n\n TODO: być może dać to do podrozdziału o [WLEM] *)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/book/B3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.17781086512112404, "lm_q1q2_score": 0.08059488132201525}} {"text": "(** * ImpParser: Lexing and Parsing in Coq *)\n\n(** The development of the Imp language in [Imp.v] completely ignores\n issues of concrete syntax -- how an ascii string that a programmer\n might write gets translated into abstract syntax trees defined by\n the datatypes [aexp], [bexp], and [com]. In this chapter, we\n illustrate how the rest of the story can be filled in by building\n a simple lexical analyzer and parser using Coq's functional\n programming facilities.\n\n It is not important to understand all the details here (and\n accordingly, the explanations are fairly terse and there are no\n exercises). The main point is simply to demonstrate that it can\n be done. You are invited to look through the code -- most of it\n is not very complicated, though the parser relies on some\n \"monadic\" programming idioms that may require a little work to\n make out -- but most readers will probably want to just skim down\n to the Examples section at the very end to get the punchline. *)\n\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-implicit-arguments\".\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Maps Imp.\n\n(* ################################################################# *)\n(** * Internals *)\n\n(* ================================================================= *)\n(** ** Lexical Analysis *)\n\nDefinition isWhite (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (orb (beq_nat n 32) (* space *)\n (beq_nat n 9)) (* tab *)\n (orb (beq_nat n 10) (* linefeed *)\n (beq_nat n 13)). (* Carriage return. *)\n\nNotation \"x '<=?' y\" := (leb x y)\n (at level 70, no associativity) : nat_scope.\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (97 <=? n) (n <=? 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (andb (65 <=? n) (n <=? 90))\n (andb (97 <=? n) (n <=? 122)).\n\nDefinition isDigit (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (48 <=? n) (n <=? 57).\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n if isWhite c then\n white\n else if isAlpha c then\n alpha\n else if isDigit c then\n digit\n else\n other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n match s with\n | EmptyString => []\n | String c s => c :: (list_of_string s)\n end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n fold_right String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii)\n : list (list ascii) :=\n let tk := match acc with [] => [] | _::_ => [rev acc] end in\n match xs with\n | [] => tk\n | (x::xs') =>\n match cls, classifyChar x, x with\n | _, _, \"(\" =>\n tk ++ [\"(\"]::(tokenize_helper other [] xs')\n | _, _, \")\" =>\n tk ++ [\")\"]::(tokenize_helper other [] xs')\n | _, white, _ =>\n tk ++ (tokenize_helper white [] xs')\n | alpha,alpha,x =>\n tokenize_helper alpha (x::acc) xs'\n | digit,digit,x =>\n tokenize_helper digit (x::acc) xs'\n | other,other,x =>\n tokenize_helper other (x::acc) xs'\n | _,tp,x =>\n tk ++ (tokenize_helper tp [x] xs')\n end\n end %char.\n\nDefinition tokenize (s : string) : list string :=\n map string_of_list (tokenize_helper white [] (list_of_string s)).\n\nExample tokenize_ex1 :\n tokenize \"abc12==3 223*(3+(a+c))\" %string\n = [\"abc\"; \"12\"; \"==\"; \"3\"; \"223\";\n \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n \"a\"; \"+\"; \"c\"; \")\"; \")\"]%string.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Parsing *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Options With Errors *)\n\n(** An [option] type with error messages: *)\n\nInductive optionE (X:Type) : Type :=\n | SomeE : X -> optionE X\n | NoneE : string -> optionE X.\n\nImplicit Arguments SomeE [[X]].\nImplicit Arguments NoneE [[X]].\n\n(** Some syntactic sugar to make writing nested match-expressions on\n optionE more convenient. *)\n\nNotation \"'DO' ( x , y ) <== e1 ; e2\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => NoneE err\n end)\n (right associativity, at level 60).\n\nNotation \"'DO' ( x , y ) <-- e1 ; e2 'OR' e3\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => e3\n end)\n (right associativity, at level 60, e2 at next level).\n\n(* ----------------------------------------------------------------- *)\n(** *** Generic Combinators for Building Parsers *)\n\nOpen Scope string_scope.\n\nDefinition parser (T : Type) :=\n list token -> optionE (T * list token).\n\nFixpoint many_helper {T} (p : parser T) acc steps xs :=\n match steps, p xs with\n | 0, _ =>\n NoneE \"Too many recursive calls\"\n | _, NoneE _ =>\n SomeE ((rev acc), xs)\n | S steps', SomeE (t, xs') =>\n many_helper p (t::acc) steps' xs'\n end.\n\n(** A (step-indexed) parser that expects zero or more [p]s: *)\n\nFixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=\n many_helper p [] steps.\n\n(** A parser that expects a given token, followed by [p]: *)\n\nDefinition firstExpect {T} (t : token) (p : parser T)\n : parser T :=\n fun xs => match xs with\n | x::xs' =>\n if string_dec x t\n then p xs'\n else NoneE (\"expected '\" ++ t ++ \"'.\")\n | [] =>\n NoneE (\"expected '\" ++ t ++ \"'.\")\n end.\n\n(** A parser that expects a particular token: *)\n\nDefinition expect (t : token) : parser unit :=\n firstExpect t (fun xs => SomeE(tt, xs)).\n\n(* ----------------------------------------------------------------- *)\n(** *** A Recursive-Descent Parser for Imp *)\n\n(** Identifiers: *)\n\nDefinition parseIdentifier (xs : list token)\n : optionE (id * list token) :=\nmatch xs with\n| [] => NoneE \"Expected identifier\"\n| x::xs' =>\n if forallb isLowerAlpha (list_of_string x) then\n SomeE (Id x, xs')\n else\n NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\nend.\n\n(** Numbers: *)\n\nDefinition parseNumber (xs : list token)\n : optionE (nat * list token) :=\nmatch xs with\n| [] => NoneE \"Expected number\"\n| x::xs' =>\n if forallb isDigit (list_of_string x) then\n SomeE (fold_left\n (fun n d =>\n 10 * n + (nat_of_ascii d -\n nat_of_ascii \"0\"%char))\n (list_of_string x)\n 0,\n xs')\n else\n NoneE \"Expected number\"\nend.\n\n(** Parse arithmetic expressions *)\n\nFixpoint parsePrimaryExp (steps:nat) \n (xs : list token)\n : optionE (aexp * list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (i, rest) <-- parseIdentifier xs ;\n SomeE (AId i, rest)\n OR DO (n, rest) <-- parseNumber xs ;\n SomeE (ANum n, rest)\n OR (DO (e, rest) <== firstExpect \"(\"\n (parseSumExp steps') xs;\n DO (u, rest') <== expect \")\" rest ;\n SomeE(e,rest'))\n end\n\nwith parseProductExp (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parsePrimaryExp steps' xs ;\n DO (es, rest') <==\n many (firstExpect \"*\" (parsePrimaryExp steps'))\n steps' rest;\n SomeE (fold_left AMult es e, rest')\n end\n\nwith parseSumExp (steps:nat) (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseProductExp steps' xs ;\n DO (es, rest') <==\n many (fun xs =>\n DO (e,rest') <--\n firstExpect \"+\"\n (parseProductExp steps') xs;\n SomeE ( (true, e), rest')\n OR DO (e,rest') <==\n firstExpect \"-\"\n (parseProductExp steps') xs;\n SomeE ( (false, e), rest'))\n steps' rest;\n SomeE (fold_left (fun e0 term =>\n match term with\n (true, e) => APlus e0 e\n | (false, e) => AMinus e0 e\n end)\n es e,\n rest')\n end.\n\nDefinition parseAExp := parseSumExp.\n\n(** Parsing boolean expressions: *)\n\nFixpoint parseAtomicExp (steps:nat)\n (xs : list token) :=\nmatch steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u,rest) <-- expect \"true\" xs;\n SomeE (BTrue,rest)\n OR DO (u,rest) <-- expect \"false\" xs;\n SomeE (BFalse,rest)\n OR DO (e,rest) <-- \n firstExpect \"not\" \n (parseAtomicExp steps') \n xs;\n SomeE (BNot e, rest)\n OR DO (e,rest) <-- \n firstExpect \"(\" \n (parseConjunctionExp steps') xs;\n (DO (u,rest') <== expect \")\" rest; \n SomeE (e, rest'))\n OR DO (e, rest) <== parseProductExp steps' xs;\n (DO (e', rest') <--\n firstExpect \"==\" \n (parseAExp steps') rest;\n SomeE (BEq e e', rest')\n OR DO (e', rest') <--\n firstExpect \"<=\" \n (parseAExp steps') rest;\n SomeE (BLe e e', rest')\n OR\n NoneE \n \"Expected '==' or '<=' after arithmetic expression\")\nend\n\nwith parseConjunctionExp (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseAtomicExp steps' xs ;\n DO (es, rest') <==\n many (firstExpect \"&&\"\n (parseAtomicExp steps'))\n steps' rest;\n SomeE (fold_left BAnd es e, rest')\n end.\n\nDefinition parseBExp := parseConjunctionExp.\n\nCheck parseConjunctionExp.\n\nDefinition testParsing {X : Type}\n (p : nat -> \n list token ->\n optionE (X * list token))\n (s : string) :=\n let t := tokenize s in \n p 100 t.\n\n(*\nEval compute in \n testParsing parseProductExp \"x*y*(x*x)*x\".\n\nEval compute in \n testParsing parseConjunctionExp \"not((x==x||x*x<=(x*x)*x)&&x==x\". \n*)\n\n(** Parsing commands: *)\n\nFixpoint parseSimpleCommand (steps:nat) \n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u, rest) <-- expect \"SKIP\" xs;\n SomeE (SKIP, rest)\n OR DO (e,rest) <--\n firstExpect \"IF\" (parseBExp steps') xs;\n DO (c,rest') <==\n firstExpect \"THEN\" \n (parseSequencedCommand steps') rest;\n DO (c',rest'') <==\n firstExpect \"ELSE\" \n (parseSequencedCommand steps') rest';\n DO (u,rest''') <==\n expect \"END\" rest'';\n SomeE(IFB e THEN c ELSE c' FI, rest''')\n OR DO (e,rest) <--\n firstExpect \"WHILE\" \n (parseBExp steps') xs;\n DO (c,rest') <==\n firstExpect \"DO\" \n (parseSequencedCommand steps') rest;\n DO (u,rest'') <==\n expect \"END\" rest';\n SomeE(WHILE e DO c END, rest'')\n OR DO (i, rest) <==\n parseIdentifier xs;\n DO (e, rest') <==\n firstExpect \":=\" (parseAExp steps') rest;\n SomeE(i ::= e, rest')\n end\n\nwith parseSequencedCommand (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (c, rest) <==\n parseSimpleCommand steps' xs;\n DO (c', rest') <--\n firstExpect \";;\" \n (parseSequencedCommand steps') rest;\n SomeE(c ;; c', rest')\n OR\n SomeE(c, rest)\n end.\n\nDefinition bignumber := 1000.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n let tokens := tokenize str in\n parseSequencedCommand bignumber tokens.\n\n(* ################################################################# *)\n(** * Examples *)\n\n(*\nCompute parse \"\n IF x == y + 1 + 2 - y * 6 + 3 THEN\n x := x * 1;;\n y := 0\n ELSE\n SKIP\n END \".\n====>\n SomeE\n (IFB BEq (AId (Id 0))\n (APlus\n (AMinus (APlus (APlus (AId (Id 1)) (ANum 1)) (ANum 2))\n (AMult (AId (Id 1)) (ANum 6)))\n (ANum 3))\n THEN Id 0 ::= AMult (AId (Id 0)) (ANum 1);; Id 1 ::= ANum 0\n ELSE SKIP FI, [])\n*)\n\n(*\nCompute parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n====>\n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0)\n ELSE SKIP FI;;\n SKIP\n END;;\n Id 1 ::= AId (Id 0),\n [])\n*)\n\n(*\nCompute parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n=====>\n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);;\n Id 2 ::= AId (Id 0)\n ELSE SKIP\n FI;;\n SKIP\n END;;\n Id 1 ::= AId (Id 0),\n []).\n*)\n\n(** $Date: 2017-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/revisit/lf/ImpParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.16885694795909767, "lm_q1q2_score": 0.08047378533802406}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward. \n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (which mostly works), and\n Scheme (a bit out of date). *)\n\nExtraction Language Ocaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import SfLib.\nRequire Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ############################################################## *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ############################################################## *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we need a few\n magic declarations to set up the right correspondence between Coq\n strings and lists of OCaml characters. *)\n\nRequire Import Ascii String.\nExtract Inductive ascii => char\n[\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))\"\n]\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))\".\nExtract Constant zero => \"'\\000'\".\nExtract Constant one => \"'\\001'\".\nExtract Constant shift =>\n \"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)\".\nExtract Inlined Constant ascii_dec => \"(=)\".\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nRequire Import Imp.\nRequire Import ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ############################################################## *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(** $Date: 2016-05-26 12:03:56 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "colinmccabe", "repo": "software-foundations", "sha": "d581e89d47978ed9acc9e2a64ba6209a614fd9f1", "save_path": "github-repos/coq/colinmccabe-software-foundations", "path": "github-repos/coq/colinmccabe-software-foundations/software-foundations-d581e89d47978ed9acc9e2a64ba6209a614fd9f1/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.15817435870093427, "lm_q1q2_score": 0.07908717935046713}} {"text": "(** * Induction: Proof by Induction *)\n(* Name: Zhiwei Wu 3 hours\nWenrui Meng 3 hours\n\n*) \n\n\n\n\n(* $Date: 2012-12-26 16:12:50 -0500 (Wed, 26 Dec 2012) $ *)\n\n(** The next line imports all of our definitions from the\n previous chapter. *)\n\nRequire Export Basics.\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n into [Basics.vo]. (This is like making a .class file from a .java\n file, or a .o file from a .c file.)\n \n Here are two ways to compile your code:\n \n - CoqIDE:\n \n Open [Basics.v].\n In the \"Compile\" menu, click on \"Compile Buffer\".\n \n - Command line:\n \n Run [coqc Basics.v]\n\n In this file, we again use the [Module] feature to wrap all of the\n definitions for pairs and lists of numbers in a module so that,\n later, we can reuse the same names for improved (generic) versions\n of the same operations. *)\n\n(* ###################################################################### *)\n(** * Naming Cases *)\n\n(** The fact that there is no explicit command for moving from\n one branch of a case analysis to the next can make proof scripts\n rather hard to read. In larger proofs, with nested case analyses,\n it can even become hard to stay oriented when you're sitting with\n Coq and stepping through the proof. (Imagine trying to remember\n that the first five subgoals belong to the inner case analysis and\n the remaining seven cases are what remains of the outer one...)\n Disciplined use of indentation and comments can help, but a better\n way is to use the [Case] tactic.\n\n [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- just skip over the\n definition to the example that follows. It uses some facilities\n of Coq that we have not discussed -- the string library (just for\n the concrete syntax of quoted strings) and the [Ltac] command,\n which allows us to declare custom tactics. Kudos to Aaron\n Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\n(** Here's an example of how [Case] is used. Step through the\n following proof and observe how the context changes. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\".\n reflexivity.\n Case \"b = false\".\n rewrite <- H. reflexivity. Qed.\n\n(** [Case] does something very trivial: It simply adds a string\n that we choose (tagged with the identifier \"Case\") to the context\n for the current goal. When subgoals are generated, this string is\n carried over into their contexts. When the last of these subgoals\n is finally proved and the next top-level goal (a sibling of the\n current one) becomes active, this string will no longer appear in\n the context and we will be able to see that the case where we\n introduced it is complete. Also, as a sanity check, if we try to\n execute a new [Case] tactic while the string left by the previous\n one is still in the context, we get a nice clear error message.\n\n For nested case analyses (i.e., when we want to use a [destruct]\n to solve a goal that has itself been generated by a [destruct]),\n there is an [SCase] (\"subcase\") tactic. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2) *)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n (* FILL IN HERE *)\nintros b c H. destruct c. Case \"c = true\". reflexivity.\nCase \"c = false\". rewrite <- H. destruct b. \nSCase \" b= true\". reflexivity.\nSCase \" b=false\". reflexivity. Qed.\n(** [] *)\n\n(** There are no hard and fast rules for how proofs should be\n formatted in Coq -- in particular, where lines should be broken\n and how sections of the proof should be indented to indicate their\n nested structure. However, if the places where multiple subgoals\n are generated are marked with explicit [Case] tactics placed at\n the beginning of lines, then the proof will be readable almost no\n matter what choices are made about other aspects of layout.\n\n This is a good place to mention one other piece of (possibly\n obvious) advice about line lengths. Beginning Coq users sometimes\n tend to the extremes, either writing each tactic on its own line\n or entire proofs on one line. Good style lies somewhere in the\n middle. In particular, one reasonable convention is to limit\n yourself to 80-character lines. Lines longer than this are hard\n to read and can be inconvenient to display and print. Many\n editors have features that help enforce this. *)\n\n(* ###################################################################### *)\n(** * Induction *)\n\n(** We proved above that [0] is a neutral element for [+] on\n the left using a simple partial evaluation argument. The fact\n that it is also a neutral element on the _right_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... cannot be proved in the same simple way. Just applying\n [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. And reasoning by cases using [destruct n] doesn't get\n us much further: the branch of the case analysis where we assume [n\n = 0] goes through, but in the branch where [n = S n'] for some [n']\n we get stuck in exactly the same way. We could use [destruct n'] to\n get one step further, but since [n] can be arbitrarily large, if we\n try to keep on going this way we'll never be done. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAdmitted.\n\n(** Case analysis gets us a little further, but not all the way: *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* so far so good... *)\n Case \"n = S n'\".\n simpl. (* ...but here we are stuck again *)\nAdmitted.\n\n(** To prove such facts -- indeed, to prove most interesting\n facts about numbers, lists, and other inductively defined sets --\n we need a more powerful reasoning principle: _induction_.\n\n Recall (from high school) the principle of induction over natural\n numbers: If [P(n)] is some proposition involving a natural number\n [n] and we want to show that P holds for _all_ numbers [n], we can\n reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same but the order is backwards: we\n begin with the goal of proving [P(n)] for all [n] and break it\n down (by applying the [induction] tactic) into two separate\n subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n n')]. Here's how this works for the theorem we are trying to\n prove at the moment: *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. In the first branch, [n] is replaced by [0] and\n the goal becomes [0 + 0 = 0], which follows by simplification. In\n the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n n'] is added to the context (with the name [IHn'], i.e., the\n Induction Hypothesis for [n']). The goal in this case becomes [(S\n n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in\n turn follows from the induction hypothesis. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, recommended (basic_induction) *)\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n (* FILL IN HERE *)\nintro. induction n as [|n'].\nCase \" n = 0 \". reflexivity. \nCase \" n = S n' \". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\nTheorem plus_n_Sm : forall n m : nat, \n S (n + m) = n + (S m).\nProof. \n (* FILL IN HERE *)\nintros. induction n as [| n'].\nCase \" n = 0 \". reflexivity.\nCase \" n = S n' \". simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n (* FILL IN HERE *) \nintros. induction n as [| n']. \nCase \" n = 0 \". induction m as [| m']. \nSCase \" m = 0\". reflexivity.\nSCase \" m = S m' \". simpl. rewrite <- IHm'. reflexivity. \nCase \" n = S n' \". simpl. induction m as [| m'].\nSCase \" m = 0 \". rewrite IHn'. reflexivity.\nSCase \" m = S m' \". rewrite IHn'. rewrite plus_n_Sm. reflexivity. Qed. \n(** [] *) \n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** **** Exercise: 2 stars (double_plus) *)\nLemma double_plus : forall n, double n = n + n .\nProof. \n (* FILL IN HERE *) \nintros. induction n as [| n'].\nCase \" n = 0 \". reflexivity.\nCase \" n = S n'\". simpl. rewrite IHn'. rewrite <- plus_n_Sm. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics\n [destruct] and [induction]. \n\nBoth tactics allow us to consider all cases of the variables assignments\nin a proof. While general destruct considers substituting \nvariables exhaustively, induction allows us to prove just by looking at \nthe base case and derivation by inductive hypothesis.\n\n(* FILL IN HERE *)\n\n*)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Formal vs. Informal Proof *)\n\n(** \"Informal proofs are algorithms; formal proofs are code.\" *)\n\n(** The question of what, exactly, constitutes a \"proof\" of a\n mathematical claim has challenged philosophers for millenia. A\n rough and ready definition, though, could be this: a proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true.\n That is, a proof is an act of communication.\n\n Now, acts of communication may involve different sorts of readers.\n On one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is a simple mechanical check that\n [P] can be derived from a certain set of formal logical rules, and\n the proof is a recipe that guides the program in performing this\n check. Such recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n thus necessarily _informal_. Here, the criteria for success are\n less clearly specified. A \"good\" proof is one that makes the\n reader believe [P]. But the same proof may be read by many\n different readers, some of whom may be convinced by a particular\n way of phrasing the argument, while others may not be. One reader\n may be particularly pedantic, inexperienced, or just plain\n thick-headed; the only way to convince them will be to make the\n argument in painstaking detail. But another reader, more familiar\n in the area, may find all this detail so overwhelming that they\n lose the overall thread. All they want is to be told the main\n ideas, because it is easier to fill in the details for themselves.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader. In practice, however,\n mathematicians have developed a rich set of conventions and idioms\n for writing about complex mathematical objects that, within a\n certain community, make communication fairly reliable. The\n conventions of this stylized form of communication give a fairly\n clear standard for judging proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can ignore\n the informal ones! Formal proofs are useful in many ways, but\n they are _not_ very efficient ways of communicating ideas between\n human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity. \n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this as a proof. For a human,\n however, it is difficult to make much sense of it. If you're used\n to Coq you can probably step through the tactics one after the\n other in your mind and imagine the state of the context and goal\n stack at each point, but if the proof were even a little bit more\n complicated this would be next to impossible. Instead, a\n mathematician mighty write it like this: *)\n(** - _Theorem_: For any [n], [m] and [p],\n n + (m + p) = (n + m) + p.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show \n 0 + (m + p) = (0 + m) + p. \n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n n' + (m + p) = (n' + m) + p.\n We must show\n (S n') + (m + p) = ((S n') + m) + p.\n By the definition of [+], this follows from\n S (n' + (m + p)) = S ((n' + m) + p),\n which is immediate from the induction hypothesis. [] *)\n\n(** The overall form of the proof is basically similar. This is\n no accident, of course: Coq has been designed so that its\n [induction] tactic generates the same sub-goals, in the same\n order, as the bullet points that a mathematician would write. But\n there are significant differences of detail: the formal proof is\n much more explicit in some ways (e.g., the use of [reflexivity])\n but much less explicit in others; in particular, the \"proof state\"\n at any given point in the Coq proof is completely implicit,\n whereas the informal proof reminds the reader several times where\n things stand. *)\n\n(** Here is a formal proof that shows the structure more\n clearly: *)\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n']. \n Case \"n = 0\".\n reflexivity. \n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative.\n \n Proof: (*\n\nCase \" n = S n' \". simpl. induction m as [| m'].\nSCase \" m = 0 \". rewrite IHn'. reflexivity.\nSCase \" m = S m' \". rewrite IHn'. rewrite plus_n_Sm. reflexivity. Qed. \n \nProof by induction on n. \nFor base case [n = 0]. \nWe have the following inducion on m:\nSub-basecase: m = 0, we have m + n = 0 + 0 = n + m.\nSub-inductive: Assume that 0 + m' = m' + 0 for m' \\geq 0. \nWe would have 0 + (m' + 1) = (m' + 1) + 0 by simplification. \n\nFor inductive case: \nAssume n' + m = m + n' for all natural numbers m, and n' \\geq 0. Then\nwe want to show that (S n') + m = m + (S n').\nWe also have the following induction on m:\nSub-basecase: m = 0, we have m + (n' + 1) = (n' + 1) = (n' + 1) + m.\nSub-inductive: Assume that (n' + 1) + m' = m' + (n' + 1).\nThen by applying the hypothesis twice, we have (n' + 1) + (m' + 1) = (n' + 1) + m' + 1 = m' + (n' + 1) + 1 = m' + 1 + (n' + 1).\n\nTherefore, commutativity holds for all natural numbers m,n.\n*)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n \n Theorem: [true = beq_nat n n] for any [n].\n \n Proof: (* FILL IN HERE *)\n\n\n\n\n\n\n\n[]\n *)\n\n(** **** Exercise: 1 star, optional (beq_nat_refl) *)\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are very\n often broken into a sequence of theorems, with later proofs\n referring to earlier theorems. Occasionally, however, a proof\n will need some miscellaneous fact that is too trivial (and of too\n little general interest) to bother giving it its own top-level\n name. In such cases, it is convenient to be able to simply state\n and prove the needed \"sub-theorem\" right at the point where it is\n used. The [assert] tactic allows us to do this. For example, our\n earlier proof of the [mult_0_plus] theorem referred to a previous\n theorem named [plus_O_n]. We can also use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). \n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (Note that we could also name the assertion with\n [as] just as we did above with [destruct] and [induction], i.e.,\n [assert (0 + n = n) as H]. Also note that we mark the proof of\n this assertion with a [Case], both for readability and so that,\n when using Coq interactively, we can see when we're finished\n proving the assertion by observing when the [\"Proof of assertion\"]\n string disappears from the context.) The second goal is the same\n as the one at the point where we invoke [assert], except that, in\n the context, we have the assumption [H] that [0 + n = n]. That\n is, [assert] generates one subgoal where we must prove the\n asserted fact and a second subgoal where we can use the asserted\n fact to make progress on whatever we were trying to prove in the\n first place. *)\n\n(** Actually, [assert] will turn out to be handy in many sorts of\n situations. For example, suppose we want to prove that [(n + m)\n + (p + q) = (m + n) + (p + q)]. The only difference between the\n two sides of the [=] is that the arguments [m] and [n] to the\n first inner [+] are swapped, so it seems we should be able to\n use the commutativity of addition ([plus_comm]) to rewrite one\n into the other. However, the [rewrite] tactic is a little stupid\n about _where_ it applies the rewrite. There are three uses of\n [+] here, and it turns out that doing [rewrite -> plus_comm]\n will affect only the _outer_ one. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)...\n it seems like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAdmitted.\n\n(** To get [plus_comm] to apply at the point where we want it, we can\n introduce a local lemma stating that [n + m = m + n] (for\n the particular [m] and [n] that we are talking about here), prove\n this lemma using [plus_comm], and then use this lemma to do the\n desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Exercise: 4 stars, recommended (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction. *)\n\nTheorem plus_swap : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) \nintros. rewrite plus_comm. assert ( p+n = n+p).\nCase \"Proof in assertion \".\nrewrite plus_comm. reflexivity.\nrewrite <- H. rewrite -> plus_assoc. reflexivity.\n Qed.\n\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one.) You may find that [plus_swap] comes in\n handy. *)\nTheorem mult_1_r : forall n : nat,\nn * 1 = n.\nProof.\nintros. induction n as [| S n'].\nCase \" n = 0 \". reflexivity. \nCase \" n = S n' \". simpl. rewrite n'. reflexivity. Qed.\nTheorem mult_1_plus' : forall m n : nat,\n(1 + n ) * m = m + n * m.\nProof.\nintros. simpl. reflexivity. Qed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\nintros. induction m as [| m'].\nCase \" m = 0 \".\nsimpl. rewrite -> mult_0_r. reflexivity.\nCase \" m = S m' \". simpl. rewrite IHm'. induction n as [|n'].\nSCase \" n = 0 \". reflexivity.\nSCase \" n = S n' \". simpl. rewrite -> plus_assoc. \n\nassert ( m' + n' * S m' = n' * S m' ). \nSSCase \"Proof assertion \". \n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)\nTheorem evenb_n__oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before hacking!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat, \n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to. More precisely,\n [replace (t) with (u)] replaces (all copies of) expression [t] in\n the goal by expression [u], and generates [t = u] as an additional\n subgoal. This is often useful when a plain [rewrite] acts on the wrong\n part of the goal. \n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. \n*)\n\nTheorem plus_swap' : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 4 stars, recommended (binary) *)\n(** Consider a different, more efficient representation of natural\n numbers using a binary rather than unary system. That is, instead\n of saying that each natural number is either zero or the successor\n of a natural number, we can say that each binary number is either\n\n - zero,\n - twice a binary number, or\n - one more than twice a binary number.\n\n (a) First, write an inductive definition of the type [bin]\n corresponding to this description of binary numbers. \n\n (Hint: recall that the definition of [nat] from class,\n Inductive nat : Type :=\n | O : nat\n | S : nat -> nat.\n says nothing about what [O] and [S] \"mean\". It just says \"[O] is\n a nat (whatever that is), and if [n] is a nat then so is [S n]\".\n The interpretation of [O] as zero and [S] as successor/plus one\n comes from the way that we use nat values, by writing functions to\n do things with them, proving things about them, and so on. Your\n definition of [bin] should be correspondingly simple; it is the\n functions you will write next that will give it mathematical\n meaning.)\n\n (b) Next, write an increment function for binary numbers, and a\n function to convert binary numbers to unary numbers.\n\n (c) Finally, prove that your increment and binary-to-unary\n functions commute: that is, incrementing a binary number and\n then converting it to unary yields the same result as first\n converting it to unary and then incrementing. \n*)\n \n\nInductive bin : Type := \n | zero : bin\n | T : bin -> bin\n | T1: bin -> bin. (* Twice plus 1*)\n\n\nFixpoint increment (b : bin) : bin :=\n match b with \n | zero => T1 zero\n | T b' => T1 b'\n | T1 b' => T (increment b')\n end.\n\nFixpoint to_unary (b : bin) : nat :=\n match b with \n | zero => O\n | T b' => mult 2 (to_unary b')\n | T1 b' => plus (mult 2 (to_unary b')) 1\n end.\n\nExample test_bin1: to_unary (increment (increment (increment zero))) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin2: to_unary (increment (increment (increment (T1 zero)))) = 4.\nProof. simpl. reflexivity. Qed.\n\n \n(** [] *)\n\n(** **** Exercise: 5 stars (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n the previous exercise to complete this one.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, it is not true!\n Explain what the problem is.\n\n (c) Define a function [normalize] from binary numbers to binary\n numbers such that for any binary number b, converting to a\n natural and then back to binary yields [(normalize b)]. Prove\n it.\n*)\n\n(* \n\n\n\n\n\n\n\n\n *)\n \n(** **** Exercise: 2 stars, optional (decreasing) *)\n(** The requirement that some argument to each function be\n \"decreasing\" is a fundamental feature of Coq's design: In\n particular, it guarantees that every function that can be defined\n in Coq will terminate on all inputs. However, because Coq's\n \"decreasing analysis\" is not very sophisticated, it is sometimes\n necessary to write functions in slightly unnatural ways.\n\n To get a concrete sense of this, find a way to write a sensible\n [Fixpoint] definition (of a simple function on numbers, say) that\n _does_ terminate on all inputs, but that Coq will _not_ accept\n because of this restriction. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n", "meta": {"author": "steven7woo", "repo": "Coq-CIS500", "sha": "405653248c19d78ec35f4b7bc2b2144c4aa92738", "save_path": "github-repos/coq/steven7woo-Coq-CIS500", "path": "github-repos/coq/steven7woo-Coq-CIS500/Coq-CIS500-405653248c19d78ec35f4b7bc2b2144c4aa92738/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1710611959045317, "lm_q1q2_score": 0.07753551377941004}} {"text": "\n\n(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n definitions from the previous chapter: *)\n\nFrom LF Require Export Basics.\n\n(** For the [Require Export] to work, Coq needs to be able to\n find a compiled version of [Basics.v], called [Basics.vo], in a directory\n associated with the prefix [LF]. This file is analogous to the [.class]\n files compiled from [.java] source files and the [.o] files compiled from\n [.c] files.\n\n First create a file named [_CoqProject] containing the following line\n (if you obtained the whole volume \"Logical Foundations\" as a single\n archive, a [_CoqProject] should already exist and you can skip this step):\n\n [-Q . LF]\n\n This maps the current directory (\"[.]\", which contains [Basics.v],\n [Induction.v], etc.) to the prefix (or \"logical directory\") \"[LF]\".\n PG and CoqIDE read [_CoqProject] automatically, so they know to where to\n look for the file [Basics.vo] corresponding to the library [LF.Basics].\n\n Once [_CoqProject] is thus created, there are various ways to build\n [Basics.vo]:\n\n - In Proof General: The compilation can be made to happen automatically\n when you submit the [Require] line above to PG, by setting the emacs\n variable [coq-compile-before-require] to [t]. You can also use the\n menu option \"Coq -> Auto Compilation -> Compile Before Require\".\n\n - In CoqIDE: Open [Basics.v]; then, in the \"Compile\" menu, click\n on \"Compile Buffer\".\n\n - From the command line: Generate a [Makefile] using the [coq_makefile]\n utility, that comes installed with Coq (if you obtained the whole\n volume as a single archive, a [Makefile] should already exist\n and you can skip this step):\n\n [coq_makefile -f _CoqProject *.v -o Makefile]\n\n Note: You should rerun that command whenever you add or remove Coq files\n to the directory.\n\n Then you can compile [Basics.v] by running [make] with the corresponding\n [.vo] file as a target:\n\n [make Basics.vo]\n\n All files in the directory can be compiled by giving no arguments:\n\n [make]\n\n Under the hood, [make] uses the Coq compiler, [coqc]. You can also\n run [coqc] directly:\n\n [coqc -Q . LF Basics.v]\n\n But [make] also calculates dependencies between source files to compile\n them in the right order, so [make] should generally be prefered over\n explicit [coqc].\n\n If you have trouble (e.g., if you get complaints about missing\n identifiers later in the file), it may be because the \"load path\"\n for Coq is not set up correctly. The [Print LoadPath.] command\n may be helpful in sorting out such issues.\n\n In particular, if you see a message like\n\n [Compiled library Foo makes inconsistent assumptions over\n library Bar]\n\n check whether you have multiple installations of Coq on your machine.\n It may be that commands (like [coqc]) that you execute in a terminal\n window are getting a different version of Coq than commands executed by\n Proof General or CoqIDE.\n\n - Another common reason is that the library [Bar] was modified and\n recompiled without also recompiling [Foo] which depends on it. Recompile\n [Foo], or everything if too many files are affected. (Using the third\n solution above: [make clean; make].)\n\n One more tip for CoqIDE users: If you see messages like [Error:\n Unable to locate library Basics], a likely reason is\n inconsistencies between compiling things _within CoqIDE_ vs _using\n [coqc] from the command line_. This typically happens when there\n are two incompatible versions of [coqc] installed on your\n system (one associated with CoqIDE, and one associated with [coqc]\n from the terminal). The workaround for this situation is\n compiling using CoqIDE only (i.e. choosing \"make\" from the menu),\n and avoiding using [coqc] directly at all. *)\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left, using an easy argument based on\n simplification. We also observed that proving the fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n n = n + 0.\n\n(** ... can't be done in the same simple way. Just applying\n [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through fine, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n n = n + 0.\nProof.\n intros n. destruct n as [| n'] eqn:E.\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** We could use [destruct n'] to get one step further, but,\n since [n] can be arbitrarily large, if we just go on like this\n we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n inductively defined sets, we usually need a more powerful\n reasoning principle: _induction_.\n\n Recall (from high school, a discrete math course, etc.) the\n _principle of induction over natural numbers_: If [P(n)] is some\n proposition involving a natural number [n] and we want to show\n that [P] holds for all numbers [n], we can reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same: we begin with the goal of proving\n [P(n)] for all [n] and break it down (by applying the [induction]\n tactic) into two separate subgoals: one where we must show [P(O)]\n and another where we must show [P(n') -> P(S n')]. Here's how\n this works for the theorem at hand: *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. Since there are two subgoals, the [as...] clause\n has two parts, separated by [|]. (Strictly speaking, we can omit\n the [as...] clause and Coq will choose names for us. In practice,\n this is a bad idea, as Coq's automatic choices tend to be\n confusing.)\n\n In the first subgoal, [n] is replaced by [0]. No new variables\n are introduced (so the first part of the [as...] is empty), and\n the goal becomes [0 = 0 + 0], which follows by simplification.\n\n In the second subgoal, [n] is replaced by [S n'], and the\n assumption [n' + 0 = n'] is added to the context with the name\n [IHn'] (i.e., the Induction Hypothesis for [n']). These two names\n are specified in the second part of the [as...] clause. The goal\n in this case becomes [S n' = (S n') + 0], which simplifies to\n [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** (The use of the [intros] tactic in these proofs is actually\n redundant. When applied to a goal that contains quantified\n variables, the [induction] tactic will automatically move them\n into the context as needed.) *)\n\n(** **** Exercise: 2 stars, standard, recommended (basic_induction) \n\n Prove the following using induction. You might need previously\n proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. induction m as [| m' IHm']. \n rewrite <- plus_1_l. rewrite <- plus_O_n. rewrite -> IHn'. simpl. reflexivity.\n rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. induction m as [| m' IHm']. \n reflexivity.\n rewrite <- plus_n_O. reflexivity.\n - (* n = S n' *)\n simpl. induction m as [| m' IHm']. simpl. rewrite <- plus_n_O. reflexivity.\n rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. induction m as [| m' IHm'].\n simpl. rewrite <- plus_n_O. reflexivity.\n induction p as [| p' IHp'].\n simpl. rewrite <- plus_n_O. rewrite <- plus_n_O. reflexivity.\n rewrite <- IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (double_plus) \n\n Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. simpl. rewrite -> plus_n_Sm. reflexivity.\n Qed.\n(** [] *)\n \n(** **** Exercise: 2 stars, standard, optional (evenb_S) \n\n One inconvenient aspect of our definition of [evenb n] is the\n recursive call on [n - 2]. This makes proofs about [evenb n]\n harder when done by induction on [n], since we may need an\n induction hypothesis about [n - 2]. The following lemma gives an\n alternative characterization of [evenb (S n)] that works better\n with induction: *)\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (destruct_induction) \n\n Briefly explain the difference between the tactics [destruct]\n and [induction].\n\n(* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_destruct_induction : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n broken into a sequence of theorems, with later proofs referring to\n earlier theorems. But sometimes a proof will require some\n miscellaneous fact that is too trivial and of too little general\n interest to bother giving it its own top-level name. In such\n cases, it is convenient to be able to simply state and prove the\n needed \"sub-theorem\" right at the point where it is used. The\n [assert] tactic allows us to do this. For example, our earlier\n proof of the [mult_0_plus] theorem referred to a previous theorem\n named [plus_O_n]. We could instead use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (We can also name the assertion with [as] just as\n we did above with [destruct] and [induction], i.e., [assert (0 + n\n = n) as H].) Note that we surround the proof of this assertion\n with curly braces [{ ... }], both for readability and so that,\n when using Coq interactively, we can see more easily when we have\n finished this sub-proof. The second goal is the same as the one\n at the point where we invoke [assert] except that, in the context,\n we now have the assumption [H] that [0 + n = n]. That is,\n [assert] generates one subgoal where we must prove the asserted\n fact and a second subgoal where we can use the asserted fact to\n make progress on whatever we were trying to prove in the first\n place. *)\n\n(** Another example of [assert]... *)\n(** For example, suppose we want to prove that [(n + m) + (p + q)\n = (m + n) + (p + q)]. The only difference between the two sides of\n the [=] is that the arguments [m] and [n] to the first inner [+]\n are swapped, so it seems we should be able to use the\n commutativity of addition ([plus_comm]) to rewrite one into the\n other. However, the [rewrite] tactic is not very smart about\n _where_ it applies the rewrite. There are three uses of [+] here,\n and it turns out that doing [rewrite -> plus_comm] will affect\n only the _outer_ one... *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)... seems\n like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work... Coq rewrites the wrong plus! :-( *)\nAbort.\n\n(** To use [plus_comm] at the point where we need it, we can introduce\n a local lemma stating that [n + m = m + n] (for the particular [m]\n and [n] that we are talking about here), prove this lemma using\n [plus_comm], and then use it to do the desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n { rewrite -> plus_comm. reflexivity. }\n rewrite -> H. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** What constitutes a successful proof of a mathematical claim?\n The question has challenged philosophers for millennia, but a\n rough and ready definition could be this: A proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true --\n an unassailable argument for the truth of [P]. That is, a proof\n is an act of communication.\n\n Acts of communication may involve different sorts of readers. On\n one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is that [P] can be mechanically\n derived from a certain set of formal logical rules, and the proof\n is a recipe that guides the program in checking this fact. Such\n recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n and will thus necessarily be _informal_. Here, the criteria for\n success are less clearly specified. A \"valid\" proof is one that\n makes the reader believe [P]. But the same proof may be read by\n many different readers, some of whom may be convinced by a\n particular way of phrasing the argument, while others may not be.\n Some readers may be particularly pedantic, inexperienced, or just\n plain thick-headed; the only way to convince them will be to make\n the argument in painstaking detail. But other readers, more\n familiar in the area, may find all this detail so overwhelming\n that they lose the overall thread; all they want is to be told the\n main ideas, since it is easier for them to fill in the details for\n themselves than to wade through a written presentation of them.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader.\n\n In practice, however, mathematicians have developed a rich set of\n conventions and idioms for writing about complex mathematical\n objects that -- at least within a certain community -- make\n communication fairly reliable. The conventions of this stylized\n form of communication give a fairly clear standard for judging\n proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can\n completely forget about informal ones! Formal proofs are useful\n in many ways, but they are _not_ very efficient ways of\n communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this. For a human, however, it\n is difficult to make much sense of it. We can use comments and\n bullets to show the structure a little more clearly... *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** ... and if you're used to Coq you may be able to step\n through the tactics one after the other in your mind and imagine\n the state of the context and goal stack at each point, but if the\n proof were even a little bit more complicated this would be next\n to impossible.\n\n A (pedantic) mathematician might write the proof something like\n this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n n + (m + p) = (n + m) + p.\n\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n\n 0 + (m + p) = (0 + m) + p.\n\n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n\n n' + (m + p) = (n' + m) + p.\n\n We must show\n\n (S n') + (m + p) = ((S n') + m) + p.\n\n By the definition of [+], this follows from\n\n S (n' + (m + p)) = S ((n' + m) + p),\n\n which is immediate from the induction hypothesis. _Qed_. *)\n\n(** The overall form of the proof is basically similar, and of\n course this is no accident: Coq has been designed so that its\n [induction] tactic generates the same sub-goals, in the same\n order, as the bullet points that a mathematician would write. But\n there are significant differences of detail: the formal proof is\n much more explicit in some ways (e.g., the use of [reflexivity])\n but much less explicit in others (in particular, the \"proof state\"\n at any given point in the Coq proof is completely implicit,\n whereas the informal proof reminds the reader several times where\n things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal) \n\n Translate your solution for [plus_comm] into an informal proof:\n\n Theorem: Addition is commutative.\n\n Proof: (* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_plus_comm_informal : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_refl_informal) \n\n Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n\n Theorem: [true = n =? n] for any [n].\n\n Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, standard, recommended (mult_comm) \n\n Use [assert] to help prove [plus_swap]. You don't need to\n use induction yet. *)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p. simpl. \n assert (H: m + (n + p) = (n + m) + p). rewrite -> plus_assoc'.\n assert (H2: n + m = m + n). rewrite -> plus_comm. reflexivity.\n rewrite -> H2. reflexivity.\n rewrite -> H. simpl. rewrite -> plus_assoc'. reflexivity.\nQed.\n\n(** Now prove commutativity of multiplication. You will probably\n want to define and prove a \"helper\" theorem to be used\n in the proof of this one. Hint: what is [n * (1 + k)]? *)\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros n m. induction n as [| n' IHn'].\n -simpl. rewrite -> mult_0_r. reflexivity. \n -assert(H: m * n'+ m = m * S n'). simpl. rewrite <- mult_n_Sm. reflexivity.\n rewrite <- H. simpl. rewrite <- IHn'. rewrite -> plus_comm. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (more_exercises) \n\n Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n true = (n <=? n).\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n 0 =? (S n) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n (S n) =? 0 = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_refl) *)\n\nTheorem eqb_refl : forall n : nat,\n true = (n =? n).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (plus_swap') \n\n The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to: [replace (t) with (u)]\n replaces (all copies of) expression [t] in the goal by expression\n [u], and generates [t = u] as an additional subgoal. This is often\n useful when a plain [rewrite] acts on the wrong part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (binary_commute) \n\n Recall the [incr] and [bin_to_nat] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that the following diagram commutes:\n\n incr\n bin ----------------------> bin\n | |\n bin_to_nat | | bin_to_nat\n | |\n v v\n nat ----------------------> nat\n S\n\n That is, incrementing a binary number and then converting it to\n a (unary) natural number yields the same result as first converting\n it to a natural number and then incrementing.\n Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n Before you start working on this exercise, copy the definitions of\n [incr] and [bin_to_nat] from your solution to the [binary]\n exercise here so that this file can be graded on its own. If you\n want to change your original definitions to make the property\n easier to prove, feel free to do so! *)\n\n(* FILL IN HERE *)\nInductive bin : Type :=\n | Z\n | B0 (n : bin)\n | B1 (n : bin).\n\nFixpoint incr (m:bin) : bin :=\n match m with \n | Z => B1 Z\n | B0 m' => B1 m'\n | B1 m' => B0 (incr m')\n end.\n\nFixpoint bin_to_nat (m:bin) : nat := \n match m with\n | Z => O\n | B0 m' => mult 2 (bin_to_nat m')\n | B1 m' => S (mult 2 ( bin_to_nat m'))\n end.\n\nTheorem bin_to_nat_pres_inc : forall b : bin, \n bin_to_nat (incr b) = S (bin_to_nat b).\nProof.\n intros b. induction b as [|b0 |b1 IHb'].\n -simpl. reflexivity.\n -simpl. rewrite <- plus_n_O. reflexivity.\n -simpl. rewrite <- plus_n_O. rewrite <- plus_n_O. rewrite -> IHb'. \n rewrite -> plus_n_Sm. rewrite <- plus_n_Sm. rewrite <- plus_n_Sm. simpl.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_commute : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) \n\n This is a further continuation of the previous exercises about\n binary numbers. You may find you need to go back and change your\n earlier definitions to get things to work here.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. *)\n\nFixpoint nat_to_bin (n:nat) : bin\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** Prove that, if we start with any [nat], convert it to binary, and\n convert it back, we get the same [nat] we started with. (Hint: If\n your definition of [nat_to_bin] involved any extra functions, you\n may need to prove a subsidiary lemma showing how such functions\n relate to [nat_to_bin].) *)\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_a : option (nat*string) := None.\n\n(** (b) One might naturally expect that we should also prove the\n opposite direction -- that starting with a binary number,\n converting to a natural, and then back to binary should yield\n the same number we started with. However, this is not the\n case! Explain (in a comment) what the problem is. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_b : option (nat*string) := None.\n\n(** (c) Define a normalization function -- i.e., a function\n [normalize] going directly from [bin] to [bin] (i.e., _not_ by\n converting to [nat] and back) such that, for any binary number\n [b], converting [b] to a natural and then back to binary yields\n [(normalize b)]. Prove it. (Warning: This part is a bit\n tricky -- you may end up defining several auxiliary lemmas.\n One good way to find out what you need is to start by trying\n to prove the main statement, see where you get stuck, and see\n if you can find a lemma -- perhaps requiring its own inductive\n proof -- that will allow the main proof to make progress.) Don't\n define this using [nat_to_bin] and [bin_to_nat]! *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_c : option (nat*string) := None.\n(** [] *)\n\n(* Tue Jan 21 11:44:15 EST 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/a4src/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.23934935274855937, "lm_q1q2_score": 0.07678837070032055}} {"text": "(* Copyright 2021 Pierre Courtieu\n This file is part of LibHyps. It is distributed under the MIT\n \"expat license\". You should have recieved a LICENSE file with it. *)\n\nRequire Import Arith ZArith List LibHyps.TacNewHyps.\nImport ListNotations.\nLocal Open Scope list.\n\n(** This file defines a tactic \"autorename h\" (and \"autorename_strict\n h\") that automatically rename hypothesis h followinh a systematic,\n but customizable heuristic.\n\n Comments welcome. *)\n\n(* Comment this and the Z-dependent lines below if you don't want\n ZArith to be loaded *)\nRequire Import ZArith.\n\n(** ** The custom renaming tactic\n\n The tactic \"rename_hyp\" should be redefined along a coq development,\n it should return a fresh name build from a type th and a depth. It\n should fail if no name is found, so that the fallback scheme is\n called.\n\n Typical use, in increasing order of complexity, approximatively\n equivalent to the decreasing order of interest.\n\n<<\nLtac rename_hyp1 n th :=\n match th with\n | List.In ?e ?l => name ( `_lst_in` ++ e#n ++ l#O)\n | InA _ ?e ?l => name( `_inA` ++ e#n ++ l#0)\n | @StronglySorted _ ?ord ?l => name ( `_strgSorted` ++ l#(S (S n)))\n | @Forall _ ?P ?x => name (`_lst_forall` ++ P#n ++ x#n)\n | @Forall2 _ _ ?P ?x ?y => name (`_lst_forall2` ++ P#n ++ x#n ++ y#n)\n | NoDupA _ ?l => name (`_NoDupA` ++ l#n)\n | NoDup _ ?l => name (`_NoDup` ++ l#n)\n end.\n>>\n(* Overwrite the definition of rename_hyp using the ::= operator. :*)\n\n<<\nLtac rename_hyp ::= my_rename_hyp.\n>> *)\n\n\n(** * Implementation principle:\n\n The name of the hypothesis will be a sequence of chunks. A chunk is\n a word generally starting with \"_\".\n\n Internally (not seen by the user) this sequence is represented by a\n list of small terms. One term of the form (∀ :Prop, DUMMY\n ) per chunk. For instance the sequence \"h_eq_foo\" is\n represented by the following coq term:\n\n [(∀ h,DUMMY h) ; (∀ _eq,DUMMY _eq) ; (∀ _foo, DUMMY _foo)]\n\n where DUMMY is an opaque (identity) function but we don't care. *)\n\n\n(** We define DUMMY as an opaque symbol. *)\nDefinition DUMMY: Prop -> Prop.\n exact (fun x:Prop => x).\nQed.\n\n(* ********** CUSTOMIZATION ********** *)\n\n(** If this is true, then all hyps names will have a trailing \"_\". In\n case of names ending with a digit (like in \"le_1_2\" or \"le_x1_x2\")\n this additional suffix avoids Coq's fresh name generation to\n *replace* the digit. Although this is esthetically bad, it makes\n things more predictable. You may set this to true for backward\n compatility. *)\nLtac add_suffix := constr:(true).\n\n(* This sets the way numerical constants are displayed, default value\n is set below to numerical_names_nosufx, which will give the same\n name to (O<1)%nat and (O<1)%Z and (O<1)%N, i.e. h_lt_0_1_.\n\n but you can use this in your development to change it\n h_lt_0n_1n_/h_lt_0z_1z_/h_lt_0N_1N_:\n Ltac numerical_names ::= numerical_names_sufx *)\nLtac numerical_names := fail.\n\n(** This determines the depth of the recursive analysis of a type to\n compute the corresponding hypothesis name. generally 2 or 3 is\n enough. More gives too log names, less may give identical names\n too often. *)\nLtac rename_depth := constr:(3).\n\n(** Default prefix for hypothesis names. *)\nLtac default_prefix :=constr:(forall h, DUMMY h).\n\n(** A few special default chunks, for special cases in the naming heuristic. *)\nLtac impl_prefix := constr:(forall _impl, DUMMY _impl).\nLtac forall_prefix := constr:(forall _all, DUMMY _all).\nLtac exists_prefix := constr:(forall _ex, DUMMY _ex).\n\n(** This is the customizable naming tactic that the user should\n REDEFINE along his development. See above for an example of such\n redefinition. It should always fail when no name suggestion is\n found, to give a chance to the default naming scheme to apply. *)\n\n Ltac rename_hyp stop th := fail.\n\n(* ************************************** *)\n\n\n(** Builds an id from a sequence of chunks. fresh is not supposed to\n add suffixes anywhere because all the ids we use start with \"_\".\n As long as no constant or hyp name start with \"_\" it is ok. *)\nLtac build_name_gen suffx l :=\n let l := eval lazy beta delta [List.app] iota in l in\n match l with\n | nil => fail\n | (forall id1:Prop, DUMMY id1)::nil =>\n match suffx with\n | true => fresh id1 \"_\"\n | false => fresh id1\n end\n | (forall id1:Prop, DUMMY id1)::?l' =>\n let recres := build_name_gen suffx l' in\n (* id1 starts with \"_\", so fresh do not add any suffix *)\n let res := fresh id1 recres in\n res\n end.\n\nLtac build_name l := build_name_gen add_suffix l.\nLtac build_name_no_suffix l := build_name_gen constr:(false) l.\n\n\n(** Check if t is an eligible argument for fresh function. For instance\n if t is (forall foo, ...), it is not eligible. *)\nLtac freshable t :=\n let x := fresh t \"_dummy_sufx\" in\n idtac.\n\n(** Generate fresh name for numerical constants.\n\n Warning: problem here: hyps names may end with a digit: Coq may\n *replace* the digit in case of name clash. If you are bitten by\n this, you should switch to \"Ltac add_suffix ::= constr:(true).\" so\n that every hyp name ends with \"_\", so that coq never mangle with\n the digits *)\nLtac numerical_names_nosufx t :=\n match t with\n | 0%Z => fresh \"_0\"\n | 1%Z => fresh \"_1\"\n | 2%Z => fresh \"_2\"\n | 3%Z => fresh \"_3\"\n | 4%Z => fresh \"_4\"\n | 5%Z => fresh \"_5\"\n | 6%Z => fresh \"_6\"\n | 7%Z => fresh \"_7\"\n | 8%Z => fresh \"_8\"\n | 9%Z => fresh \"_9\"\n | 10%Z => fresh \"_10\"\n (* | Z0 => fresh \"_0\" *)\n | O%nat => fresh \"_0\"\n | 1%nat => fresh \"_1\"\n | 2%nat => fresh \"_2\"\n | 3%nat => fresh \"_3\"\n | 4%nat => fresh \"_4\"\n | 5%nat => fresh \"_5\"\n | 6%nat => fresh \"_6\"\n | 7%nat => fresh \"_7\"\n | 8%nat => fresh \"_8\"\n | 9%nat => fresh \"_9\"\n | 10%nat => fresh \"_10\"\n | O%N => fresh \"_0\"\n | 1%N => fresh \"_1\"\n | 2%N => fresh \"_2\"\n | 3%N => fresh \"_3\"\n | 4%N => fresh \"_4\"\n | 5%N => fresh \"_5\"\n | 6%N => fresh \"_6\"\n | 7%N => fresh \"_7\"\n | 8%N => fresh \"_8\"\n | 9%N => fresh \"_9\"\n | 10%N => fresh \"_10\"\n end.\n\nLtac numerical_names_sufx t :=\n match t with\n | 0%Z => fresh \"_0z\"\n | 1%Z => fresh \"_1z\"\n | 2%Z => fresh \"_2z\"\n | 3%Z => fresh \"_3z\"\n | 4%Z => fresh \"_4z\"\n | 5%Z => fresh \"_5z\"\n | 6%Z => fresh \"_6z\"\n | 7%Z => fresh \"_7z\"\n | 8%Z => fresh \"_8z\"\n | 9%Z => fresh \"_9z\"\n | 10%Z => fresh \"_10z\"\n (* | Z0 => fresh \"_0\" *)\n | O%nat => fresh \"_0n\"\n | 1%nat => fresh \"_1n\"\n | 2%nat => fresh \"_2n\"\n | 3%nat => fresh \"_3n\"\n | 4%nat => fresh \"_4n\"\n | 5%nat => fresh \"_5n\"\n | 6%nat => fresh \"_6n\"\n | 7%nat => fresh \"_7n\"\n | 8%nat => fresh \"_8n\"\n | 9%nat => fresh \"_9n\"\n | 10%nat => fresh \"_10n\"\n | O%N => fresh \"_0N\"\n | 1%N => fresh \"_1N\"\n | 2%N => fresh \"_2N\"\n | 3%N => fresh \"_3N\"\n | 4%N => fresh \"_4N\"\n | 5%N => fresh \"_5N\"\n | 6%N => fresh \"_6N\"\n | 7%N => fresh \"_7N\"\n | 8%N => fresh \"_8N\"\n | 9%N => fresh \"_9N\"\n | 10%N => fresh \"_10N\"\n end.\n\n(* Default value, see above for another possible one.\nLtac numerical_names ::= numerical_names_sufx *)\nLtac numerical_names ::= numerical_names_nosufx.\n \n\nLtac raw_name X := (constr:((forall X, DUMMY X) :: [])).\n\n(** Build a chunk from a simple term: either a number or a freshable\n term. *)\nLtac box_name t :=\n let id_ :=\n match t with\n | _ => numerical_names t\n | _ =>\n let _ := freshable t in\n fresh \"_\" t\n end\n in constr:(forall id_:Prop, DUMMY id_).\n\n\n(** This will later contain a few default fallback naming strategy. *)\nLtac rename_hyp_default stop th :=\n fail.\n\nLtac decr n :=\n match n with\n | S ?n' => n'\n | 0 => 0\n end.\n\n(* This computes the way we decrement our depth counter when we go\n inside of t. For now we forget the idea of traversing Prop sorted\n terms indefinitely. It gives too long names. *)\nLtac nextlevel n t :=\n let tt := type of t in\n match tt with\n (* | Prop => n *)\n | _ => decr n\n end.\n\n\n(* Determines the number of \"head\" implicit arguments, i.e. implicit\n arguments that are before any explicit one. This shall be ignored\n when naming an application. This is done in very ugly way. Any\n better solution welcome. *)\nLtac count_impl th :=\n lazymatch th with\n | (?z ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ _ _ _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ g h i j k) in constr:(5%nat)\n | _ => let foo := constr:(z _ _ _ _ _ f g h i j k) in constr:(6%nat)\n | _ => let foo := constr:(z _ _ _ _ e f g h i j k) in constr:(7%nat)\n | _ => let foo := constr:(z _ _ _ d e f g h i j k) in constr:(8%nat)\n | _ => let foo := constr:(z _ _ c d e f g h i j k) in constr:(9%nat)\n | _ => let foo := constr:(z _ b c d e f g h i j k) in constr:(10%nat)\n | _ => let foo := constr:(z a b c d e f g h i j k) in constr:(10%nat)\n end\n | (?z ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ _ _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z _ _ _ _ _ g h i j k) in constr:(5%nat)\n | _ => let foo := constr:(z _ _ _ _ f g h i j k) in constr:(6%nat)\n | _ => let foo := constr:(z _ _ _ e f g h i j k) in constr:(7%nat)\n | _ => let foo := constr:(z _ _ d e f g h i j k) in constr:(8%nat)\n | _ => let foo := constr:(z _ c d e f g h i j k) in constr:(9%nat)\n | _ => let foo := constr:(z b c d e f g h i j k) in constr:(10%nat)\n end\n | (?z ?c ?d ?e ?f ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ _ _ _ _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z _ _ _ _ g h i j k) in constr:(5%nat)\n | _ => let foo := constr:(z _ _ _ f g h i j k) in constr:(6%nat)\n | _ => let foo := constr:(z _ _ e f g h i j k) in constr:(7%nat)\n | _ => let foo := constr:(z _ d e f g h i j k) in constr:(8%nat)\n | _ => let foo := constr:(z c d e f g h i j k) in constr:(9%nat)\n end\n | (?z ?d ?e ?f ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ _ _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ _ _ _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z _ _ _ g h i j k) in constr:(5%nat)\n | _ => let foo := constr:(z _ _ f g h i j k) in constr:(6%nat)\n | _ => let foo := constr:(z _ e f g h i j k) in constr:(7%nat)\n | _ => let foo := constr:(z d e f g h i j k) in constr:(8%nat)\n end\n | (?z ?e ?f ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ _ _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z _ _ g h i j k) in constr:(5%nat)\n | _ => let foo := constr:(z _ f g h i j k) in constr:(6%nat)\n | _ => let foo := constr:(z e f g h i j k) in constr:(7%nat)\n end\n | (?z ?f ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z _ g h i j k) in constr:(5%nat)\n | _ => let foo := constr:(z f g h i j k) in constr:(6%nat)\n end\n | (?z ?g ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z _ h i j k) in constr:(4%nat)\n | _ => let foo := constr:(z g h i j k) in constr:(5%nat)\n end\n | (?z ?h ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z _ i j k) in constr:(3%nat)\n | _ => let foo := constr:(z h i j k) in constr:(4%nat)\n end\n | (?z ?i ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ _ k) in constr:(1%nat)\n | _ => let foo := constr:(z _ j k) in constr:(2%nat)\n | _ => let foo := constr:(z i j k) in constr:(3%nat)\n end\n | (?z ?j ?k) =>\n match th with\n | _ => let foo := constr:(z _ k) in constr:(1%nat)\n | _ => let foo := constr:(z j k) in constr:(2%nat)\n end\n | (?z ?j) => constr:(1%nat)\n | _ => constr:(0%nat)\n end.\n\n\n(** Default naming of an application: we name the function if possible\n or fail, then we name all parameters that can be named either\n recursively or simply. Parameters at positions below nonimpl are\n considered implicit and not considered. *)\nLtac rename_app nonimpl stop acc th :=\n match th with\n | ?f => let f'' := box_name f in\n constr:(f''::acc)\n | (?f ?x) =>\n match nonimpl with\n | (S ?nonimpl') =>\n let newstop := nextlevel stop x in\n let namex := match true with\n | _ => fallback_rename_hyp newstop x\n | _ => constr:(@nil Prop)\n end in\n let newacc := constr:(namex ++ acc) in\n rename_app nonimpl' stop newacc f\n | 0%nat => (* don't consider this (implicit) argument *)\n rename_app nonimpl stop acc f\n end\n | _ => constr:(@nil Prop)\n end\n\n(* Go under binder and rebuild a term with a good name inside,\n catchable by a match context. *)\nwith build_dummy_quantified stop th :=\n lazymatch th with\n | forall __z:?A , ?B =>\n constr:(\n fun __z:A =>\n ltac:(\n let th' := constr:((fun __z => B) __z) in\n let th' := eval lazy beta in th' in\n let res := build_dummy_quantified stop th' in\n exact res))\n | ex ?f =>\n match f with\n | (fun __z:?A => ?B) =>\n constr:(\n fun __z:A =>\n ltac:(\n let th' := constr:((fun __z => B) __z) in\n let th' := eval lazy beta in th' in\n let res := build_dummy_quantified stop th' in\n exact res))\n end\n | _ => fallback_rename_hyp stop th\n end\n\n(** ** Calls the (user-defined) rename_hyp + and fallbacks to some\n default namings if needed. [h] is the hypothesis (ident) to\n rename, [th] is its type. *)\n\nwith fallback_rename_hyp_quantif stop th :=\n let prefx :=\n match th with\n | ?A -> ?B => impl_prefix\n | forall _ , _ => forall_prefix\n | ex (fun _ => _) => exists_prefix\n | _ => fail\n end in\n let newstop := decr stop in\n (* sufx_buried contains a list of dummies *)\n let sufx_buried := build_dummy_quantified newstop th in\n (* FIXME: a bit fragile *)\n let sufx_buried' := eval lazy beta delta [List.app] iota in sufx_buried in\n let sufx :=\n match sufx_buried' with\n | context [ (@cons Prop ?x ?y)] => constr:(x::y)\n end\n in\n constr:(prefx::sufx)\n\nwith fallback_rename_hyp_specials stop th :=\n let newstop := decr stop in\n match th with\n (* First see if user has something that applies *)\n | _ => rename_hyp newstop th\n (* if it fails try default specials *)\n | _ => rename_hyp_default newstop th\n end\n\nwith fallback_rename_hyp stop th :=\n match stop with\n (*| 0 => constr:(cons ltac:(box_name th) nil)*)\n | 0 => constr:(@nil Prop)\n | S ?n =>\n match th with\n | _ => fallback_rename_hyp_specials stop th\n | _ => fallback_rename_hyp_quantif stop th\n | _ =>\n (*let newstop := nextlevel stop th in*)\n let numnonimpl := count_impl th in\n rename_app numnonimpl stop (@nil Prop) th\n end\n end.\n\n(** * Notation to define specific naming strategy *)\nDeclare Scope autonaming_scope.\n(** Notation to build a singleton chunk list *)\n\n(* from coq-8.13 we should use name instead of ident. But let us wait\n a few versions before this change. *)\nNotation \"'`' idx '`'\" := (@cons Prop (forall idx:Prop, DUMMY idx) (@nil Prop))\n (at level 1,idx ident,only parsing): autonaming_scope.\n\n\n(** Notation to call naming on a term X, with a given depth n. *)\nNotation \" X '#' n \" := ltac:(\n let c := fallback_rename_hyp n X in exact c)\n (at level 1,X constr, only parsing): autonaming_scope.\n\nNotation \" X '##' \" := \n ltac:(let c := raw_name X in exact c)\n (at level 1,X constr, only parsing): autonaming_scope.\n\n\n(** It is nicer to write name t than constr:t, see below. *)\nLtac name c := (constr:(c)).\n\n\n(** * Default fallback renaming strategy\n\n (Re)defining it now that we have everything we need. *)\n\nLocal Open Scope autonaming_scope.\nLtac rename_hyp_default n th ::=\n let res :=\n match th with\n (* | (@eq _ ?x ?y) => name (`_eq` ++ x#n ++ y#n) *)\n (* | Z.le ?A ?B => name (`_Zle` ++ A#n ++ B#n) *)\n | ?x <> ?y => name ( `_neq` ++ x#(decr n) ++ y#(decr n))\n | @cons _ ?x (cons ?y ?l) =>\n match n with\n | S ?n' => name (`_cons` ++ x#n ++ y#n ++ l#n')\n | 0 => name (`_cons` ++ x#n)\n end\n | @cons _ ?x ?l =>\n match n with\n | S ?n' => name (`_cons` ++ x#n ++ l#n')\n | 0 => name (`_cons` ++ x#n)\n end\n | (@Some _ ?x) => name (x#(S n))\n | (@None _) => name (`_None`)\n | _ => fail\n end in\n res.\n\n(* Call this in your own renaming scheme if you want the \"hneg\" prefix\n on negated properties *)\nLtac rename_hyp_neg n th :=\n match th with\n | ~ (_ = _) => fail 1(* h_neq already dealt by fallback *)\n | ~ ?th' => name (`not` ++ th'#(S n))\n | _ => fail\n end.\n\nLocal Close Scope autonaming_scope.\n\n(* Entry point of the renaming code. *)\nLtac fallback_rename_hyp_name th :=\n let depth := rename_depth in\n let h := constr:(ltac:(let x := default_prefix in exact x)) in\n let l := fallback_rename_hyp depth th in\n match l with\n nil => fail 1\n | _ => let nme := build_name (h::l) in\n fresh nme\n end.\n\n(* Formating Error message *)\nInductive LHMsg t (h:t) := LHMsgC: LHMsg t h.\n\nNotation \"h : t\" := (LHMsgC t h) (at level 1,only printing, format\n\"'[ ' h ':' '/' '[' t ']' ']'\").\n\nLtac rename_hyp_with_name h th := fail.\n\n\n(* Tactic renaming hypothesis H. Ignore Type-sorted hyps, fails if no\nrenaming can be computed. Example of failing type: H:((fun x => True) true). *)\nLtac autorename_strict H :=\n match type of H with\n | ?th =>\n match type of th with\n | _ =>\n let l := rename_hyp_with_name H th in\n let dummy_name := fresh \"dummy\" in\n rename H into dummy_name; (* frees current name of H, in case of idempotency *)\n let newname := build_name_no_suffix l in\n rename dummy_name into newname\n | Prop =>\n let dummy_name := fresh \"dummy\" in\n rename H into dummy_name; (* frees current name of H, in case of idempotency *)\n let newname := fallback_rename_hyp_name th in\n rename dummy_name into newname\n | Prop =>\n let c := constr:(LHMsgC th H) in\n fail 1 \"no renaming pattern for \" c (* \"no renaming pattern for \" H *)\n | _ => idtac (* not in Prop or \"no renaming pattern for \" H *)\n end\n end.\n\n(* Tactic renaming hypothesis H. *)\n\nLtac autorename H := try autorename_strict H.\n\n(*\n(* Tests *)\nPrint Visibility.\nLocal Open Scope autonaming_scope.\nLtac rename_hyp1 n th :=\n match th with\n (* | (?min <= ?x) /\\ (?x < ?max) => name (x#n ++ `_bounded_` ++ min#n ++ `_` ++ max#n) *)\n | ((?min <= ?x) /\\ (?x <= ?max))%nat => name (x#n ++ `_bounded` ++ min#n ++ max#n)\n end.\n(* example of adhoc naming from hyp name: *)\nLtac rename_hyp_with_name h th ::=\n match reverse goal with\n | H: ?A = h |- _ =>\n name ( A## ++ `_same`)\n (* let _ := freshable A in *)\n (* name (`same_as` ++ A#1) *)\n end.\nLocal Close Scope autonaming_scope.\n\nLtac rename_hyp n th ::=\n match th with\n | _ => rename_hyp1 n th\n end.\n\nGoal forall x1 x3:bool, forall a z e : nat,\n z+e = a\n -> z = a\n -> forall SEP:(True -> True),\n a = z+z\n -> z+z <= a <= e + e\n -> ((fun f => z = e) true)\n -> forall b1 b2 b3 b4: bool,\n True -> True.\nProof.\n intros.\n autorename a.\n autorename H2.\n autorename H1.\n Fail autorename_strict H2.\n\n*)\n", "meta": {"author": "Matafou", "repo": "LibHyps", "sha": "3729e94ec0c0400d34ad1cb0d29fd7f3104179ce", "save_path": "github-repos/coq/Matafou-LibHyps", "path": "github-repos/coq/Matafou-LibHyps/LibHyps-3729e94ec0c0400d34ad1cb0d29fd7f3104179ce/LibHyps/LibHypsNaming.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.20689404392565783, "lm_q1q2_score": 0.07584523300933226}} {"text": "(* Copyright (c) 2009-2012, 2015, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n * http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import Arith.\n\nRequire Import Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\n\n(** %\\part{The Big Picture}\n\n \\chapter{Proving in the Large}% *)\n\n(** It is somewhat unfortunate that the term \"theorem proving\" looks so much like the word \"theory.\" Most researchers and practitioners in software assume that mechanized theorem proving is profoundly impractical. Indeed, until recently, most advances in theorem proving for higher-order logics have been largely theoretical. However, starting around the beginning of the 21st century, there was a surge in the use of proof assistants in serious verification efforts. That line of work is still quite new, but I believe it is not too soon to distill some lessons on how to work effectively with large formal proofs.\n\n Thus, this chapter gives some tips for structuring and maintaining large Coq developments. *)\n\n\n(** * Ltac Anti-Patterns *)\n\n(** In this book, I have been following an unusual style, where proofs are not considered finished until they are %\\index{fully automated proofs}%\"fully automated,\" in a certain sense. Each such theorem is proved by a single tactic. Since Ltac is a Turing-complete programming language, it is not hard to squeeze arbitrary heuristics into single tactics, using operators like the semicolon to combine steps. In contrast, most Ltac proofs \"in the wild\" consist of many steps, performed by individual tactics followed by periods. Is it really worth drawing a distinction between proof steps terminated by semicolons and steps terminated by periods?\n\n I argue that this is, in fact, a very important distinction, with serious consequences for a majority of important verification domains. The more uninteresting drudge work a proof domain involves, the more important it is to work to prove theorems with single tactics. From an automation standpoint, single-tactic proofs can be extremely effective, and automation becomes more and more critical as proofs are populated by more uninteresting detail. In this section, I will give some examples of the consequences of more common proof styles.\n\n As a running example, consider a basic language of arithmetic expressions, an interpreter for it, and a transformation that scales up every constant in an expression. *)\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Plus : exp -> exp -> exp.\n\nFixpoint eval (e : exp) : nat :=\n match e with\n | Const n => n\n | Plus e1 e2 => eval e1 + eval e2\n end.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n end.\n\n(** We can write a very manual proof that [times] really implements multiplication. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e.\n\n trivial.\n\n simpl.\n rewrite IHe1.\n rewrite IHe2.\n rewrite mult_plus_distr_l.\n trivial.\nQed.\n\n(* begin thide *)\n(** We use spaces to separate the two inductive cases, but note that these spaces have no real semantic content; Coq does not enforce that our spacing matches the real case structure of a proof. The second case mentions automatically generated hypothesis names explicitly. As a result, innocuous changes to the theorem statement can invalidate the proof. *)\n\nReset eval_times.\n\nTheorem eval_times : forall k x,\n eval (times k x) = k * eval x.\n induction x.\n\n trivial.\n\n simpl.\n(** %\\vspace{-.15in}%[[\n rewrite IHe1.\n]]\n\n<<\nError: The reference IHe1 was not found in the current environment.\n>>\n\n The inductive hypotheses are named [IHx1] and [IHx2] now, not [IHe1] and [IHe2]. *)\n\nAbort.\n\n(** We might decide to use a more explicit invocation of [induction] to give explicit binders for all of the names that we will reference later in the proof. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 ].\n\n trivial.\n\n simpl.\n rewrite IHe1.\n rewrite IHe2.\n rewrite mult_plus_distr_l.\n trivial.\nQed.\n\n(** We pass %\\index{tactics!induction}%[induction] an%\\index{intro pattern}% _intro pattern_, using a [|] character to separate instructions for the different inductive cases. Within a case, we write [?] to ask Coq to generate a name automatically, and we write an explicit name to assign that name to the corresponding new variable. It is apparent that, to use intro patterns to avoid proof brittleness, one needs to keep track of the seemingly unimportant facts of the orders in which variables are introduced. Thus, the script keeps working if we replace [e] by [x], but it has become more cluttered. Arguably, neither proof is particularly easy to follow.\n\n That category of complaint has to do with understanding proofs as static artifacts. As with programming in general, with serious projects, it tends to be much more important to be able to support evolution of proofs as specifications change. Unstructured proofs like the above examples can be very hard to update in concert with theorem statements. For instance, consider how the last proof script plays out when we modify [times] to introduce a bug. *)\n\nReset times.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (1 + k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n end.\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 ].\n\n trivial.\n\n simpl.\n(** %\\vspace{-.15in}%[[\n rewrite IHe1.\n]]\n\n<<\nError: The reference IHe1 was not found in the current environment.\n>>\n *)\n\nAbort.\n\n(** Can you spot what went wrong, without stepping through the script step-by-step? The problem is that [trivial] never fails. Originally, [trivial] had been succeeding in proving an equality that follows by reflexivity. Our change to [times] leads to a case where that equality is no longer true. The invocation [trivial] happily leaves the false equality in place, and we continue on to the span of tactics intended for the second inductive case. Unfortunately, those tactics end up being applied to the _first_ case instead.\n\n The problem with [trivial] could be \"solved\" by writing, e.g., [solve [ trivial ]] instead, so that an error is signaled early on if something unexpected happens. However, the root problem is that the syntax of a tactic invocation does not imply how many subgoals it produces. Much more confusing instances of this problem are possible. For example, if a lemma [L] is modified to take an extra hypothesis, then uses of [apply L] will generate more subgoals than before. Old unstructured proof scripts will become hopelessly jumbled, with tactics applied to inappropriate subgoals. Because of the lack of structure, there is usually relatively little to be gleaned from knowledge of the precise point in a proof script where an error is raised. *)\n\nReset times.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n end.\n\n(** Many real developments try to make essentially unstructured proofs look structured by applying careful indentation conventions, idempotent case-marker tactics included solely to serve as documentation, and so on. All of these strategies suffer from the same kind of failure of abstraction that was just demonstrated. I like to say that if you find yourself caring about indentation in a proof script, it is a sign that the script is structured poorly.\n\n We can rewrite the current proof with a single tactic. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 ]; [\n trivial\n | simpl; rewrite IHe1; rewrite IHe2; rewrite mult_plus_distr_l; trivial ].\nQed.\n\n(** We use the form of the semicolon operator that allows a different tactic to be specified for each generated subgoal. This change improves the robustness of the script: we no longer need to worry about tactics from one case being applied to a different case. Still, the proof script is not especially readable. Probably most readers would not find it helpful in explaining why the theorem is true. The same could be said for scripts using the%\\index{bullets}% _bullets_ or curly braces provided by Coq 8.4, which allow code like the above to be stepped through interactively, with periods in place of the semicolons, while representing proof structure in a way that is enforced by Coq. Interactive replay of scripts becomes easier, but readability is not really helped.\n\n The situation gets worse in considering extensions to the theorem we want to prove. Let us add multiplication nodes to our [exp] type and see how the proof fares. *)\n\nReset exp.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Plus : exp -> exp -> exp\n| Mult : exp -> exp -> exp.\n\nFixpoint eval (e : exp) : nat :=\n match e with\n | Const n => n\n | Plus e1 e2 => eval e1 + eval e2\n | Mult e1 e2 => eval e1 * eval e2\n end.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n | Mult e1 e2 => Mult (times k e1) e2\n end.\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n(** %\\vspace{-.25in}%[[\n induction e as [ | ? IHe1 ? IHe2 ]; [\n trivial\n | simpl; rewrite IHe1; rewrite IHe2; rewrite mult_plus_distr_l; trivial ].\n]]\n\n<<\nError: Expects a disjunctive pattern with 3 branches.\n>>\n *)\nAbort.\n\n(** Unsurprisingly, the old proof fails, because it explicitly says that there are two inductive cases. To update the script, we must, at a minimum, remember the order in which the inductive cases are generated, so that we can insert the new case in the appropriate place. Even then, it will be painful to add the case, because we cannot walk through proof steps interactively when they occur inside an explicit set of cases. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 | ? IHe1 ? IHe2 ]; [\n trivial\n | simpl; rewrite IHe1; rewrite IHe2; rewrite mult_plus_distr_l; trivial\n | simpl; rewrite IHe1; rewrite mult_assoc; trivial ].\nQed.\n\n(** Now we are in a position to see how much nicer is the style of proof that we have followed in most of this book. *)\n\nReset eval_times.\n\nHint Rewrite mult_plus_distr_l.\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e; crush.\nQed.\n(* end thide *)\n\n(** This style is motivated by a hard truth: one person's manual proof script is almost always mostly inscrutable to most everyone else. I claim that step-by-step formal proofs are a poor way of conveying information. Thus, we might as well cut out the steps and automate as much as possible.\n\n What about the illustrative value of proofs? Most informal proofs are read to convey the big ideas of proofs. How can reading [induction e; crush] convey any big ideas? My position is that any ideas that standard automation can find are not very big after all, and the _real_ big ideas should be expressed through lemmas that are added as hints.\n\n An example should help illustrate what I mean. Consider this function, which rewrites an expression using associativity of addition and multiplication. *)\n\nFixpoint reassoc (e : exp) : exp :=\n match e with\n | Const _ => e\n | Plus e1 e2 =>\n let e1' := reassoc e1 in\n let e2' := reassoc e2 in\n match e2' with\n | Plus e21 e22 => Plus (Plus e1' e21) e22\n | _ => Plus e1' e2'\n end\n | Mult e1 e2 =>\n let e1' := reassoc e1 in\n let e2' := reassoc e2 in\n match e2' with\n | Mult e21 e22 => Mult (Mult e1' e21) e22\n | _ => Mult e1' e2'\n end\n end.\n\nTheorem reassoc_correct : forall e, eval (reassoc e) = eval e.\n(* begin thide *)\n induction e; crush;\n match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\n\n (** One subgoal remains:\n [[\n IHe2 : eval e3 * eval e4 = eval e2\n ============================\n eval e1 * eval e3 * eval e4 = eval e1 * eval e2\n ]]\n\n The [crush] tactic does not know how to finish this goal. We could finish the proof manually. *)\n\n rewrite <- IHe2; crush.\n\n (** However, the proof would be easier to understand and maintain if we separated this insight into a separate lemma. *)\n\nAbort.\n\nLemma rewr : forall a b c d, b * c = d -> a * b * c = a * d.\n crush.\nQed.\n\nHint Resolve rewr.\n\nTheorem reassoc_correct : forall e, eval (reassoc e) = eval e.\n induction e; crush;\n match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\nQed.\n(* end thide *)\n\n(** In the limit, a complicated inductive proof might rely on one hint for each inductive case. The lemma for each hint could restate the associated case. Compared to manual proof scripts, we arrive at more readable results. Scripts no longer need to depend on the order in which cases are generated. The lemmas are easier to digest separately than are fragments of tactic code, since lemma statements include complete proof contexts. Such contexts can only be extracted from monolithic manual proofs by stepping through scripts interactively.\n\n The more common situation is that a large induction has several easy cases that automation makes short work of. In the remaining cases, automation performs some standard simplification. Among these cases, some may require quite involved proofs; such a case may deserve a hint lemma of its own, where the lemma statement may copy the simplified version of the case. Alternatively, the proof script for the main theorem may be extended with some automation code targeted at the specific case. Even such targeted scripting is more desirable than manual proving, because it may be read and understood without knowledge of a proof's hierarchical structure, case ordering, or name binding structure.\n\n A competing alternative to the common style of Coq tactics is the%\\index{declarative proof scripts}% _declarative_ style, most frequently associated today with the %\\index{Isar}%Isar%~\\cite{Isar}% language. A declarative proof script is very explicit about subgoal structure and introduction of local names, aiming for human readability. The coding of proof automation is taken to be outside the scope of the proof language, an assumption related to the idea that it is not worth building new automation for each serious theorem. I have shown in this book many examples of theorem-specific automation, which I believe is crucial for scaling to significant results. Declarative proof scripts make it easier to read scripts to modify them for theorem statement changes, but the alternate%\\index{adaptive proof scripts}% _adaptive_ style from this book allows use of the _same_ scripts for many versions of a theorem.\n\n Perhaps I am a pessimist for thinking that fully formal proofs will inevitably consist of details that are uninteresting to people, but it is my preference to focus on conveying proof-specific details through choice of lemmas. Additionally, adaptive Ltac scripts contain bits of automation that can be understood in isolation. For instance, in a big [repeat match] loop, each case can generally be digested separately, which is a big contrast from trying to understand the hierarchical structure of a script in a more common style. Adaptive scripts rely on variable binding, but generally only over very small scopes, whereas understanding a traditional script requires tracking the identities of local variables potentially across pages of code.\n\n One might also wonder why it makes sense to prove all theorems automatically (in the sense of adaptive proof scripts) but not construct all programs automatically. My view there is that _program synthesis_ is a very useful idea that deserves broader application! In practice, there are difficult obstacles in the way of finding a program automatically from its specification. A typical specification is not exhaustive in its description of program properties. For instance, details of performance on particular machine architectures are often omitted. As a result, a synthesized program may be correct in some sense while suffering from deficiencies in other senses. Program synthesis research will continue to come up with ways of dealing with this problem, but the situation for theorem proving is fundamentally different. Following mathematical practice, the only property of a formal proof that we care about is which theorem it proves, and it is trivial to check this property automatically. In other words, with a simple criterion for what makes a proof acceptable, automatic search is straightforward. Of course, in practice we also care about understandability of proofs to facilitate long-term maintenance, which is just what motivates the techniques outlined above, and the next section gives some related advice. *)\n\n\n(** * Debugging and Maintaining Automation *)\n\n(** Fully automated proofs are desirable because they open up possibilities for automatic adaptation to changes of specification. A well-engineered script within a narrow domain can survive many changes to the formulation of the problem it solves. Still, as we are working with higher-order logic, most theorems fall within no obvious decidable theories. It is inevitable that most long-lived automated proofs will need updating.\n\n Before we are ready to update our proofs, we need to write them in the first place. While fully automated scripts are most robust to changes of specification, it is hard to write every new proof directly in that form. Instead, it is useful to begin a theorem with exploratory proving and then gradually refine it into a suitable automated form.\n\n Consider this theorem from Chapter 8, which we begin by proving in a mostly manual way, invoking [crush] after each step to discharge any low-hanging fruit. Our manual effort involves choosing which expressions to case-analyze on. *)\n\n(* begin hide *)\nRequire Import MoreDep.\n(* end hide *)\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n(* begin thide *)\n induction e; crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (cfold e2); crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (cfold e2); crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (cfold e2); crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (expDenote e1); crush.\n\n dep_destruct (cfold e); crush.\n\n dep_destruct (cfold e); crush.\nQed.\n\n(** In this complete proof, it is hard to avoid noticing a pattern. We rework the proof, abstracting over the patterns we find. *)\n\nReset cfold_correct.\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n induction e; crush.\n\n (** The expression we want to destruct here turns out to be the discriminee of a [match], and we can easily enough write a tactic that destructs all such expressions. *)\n\n Ltac t :=\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n end; crush).\n\n t.\n\n (** This tactic invocation discharges the whole case. It does the same on the next two cases, but it gets stuck on the fourth case. *)\n\n t.\n\n t.\n\n t.\n\n (** The subgoal's conclusion is:\n [[\n ============================\n (if expDenote e1 then expDenote (cfold e2) else expDenote (cfold e3)) =\n expDenote (if expDenote e1 then cfold e2 else cfold e3)\n ]]\n\n We need to expand our [t] tactic to handle this case. *)\n\n Ltac t' :=\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n | [ |- (if ?E then _ else _) = _ ] => destruct E\n end; crush).\n\n t'.\n\n (** Now the goal is discharged, but [t'] has no effect on the next subgoal. *)\n\n t'.\n\n (** A final revision of [t] finishes the proof. *)\n\n Ltac t'' :=\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n | [ |- (if ?E then _ else _) = _ ] => destruct E\n | [ |- context[match pairOut ?E with Some _ => _\n | None => _ end] ] =>\n dep_destruct E\n end; crush).\n\n t''.\n\n t''.\nQed.\n\n(** We can take the final tactic and move it into the initial part of the proof script, arriving at a nicely automated proof. *)\n\nReset cfold_correct.\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n induction e; crush;\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n | [ |- (if ?E then _ else _) = _ ] => destruct E\n | [ |- context[match pairOut ?E with Some _ => _\n | None => _ end] ] =>\n dep_destruct E\n end; crush).\nQed.\n(* end thide *)\n\n(** Even after we put together nice automated proofs, we must deal with specification changes that can invalidate them. It is not generally possible to step through single-tactic proofs interactively. There is a command %\\index{Vernacular commands!Debug On}%[Debug On] that lets us step through points in tactic execution, but the debugger tends to make counterintuitive choices of which points we would like to stop at, and per-point output is quite verbose, so most Coq users do not find this debugging mode very helpful. How are we to understand what has broken in a script that used to work?\n\n An example helps demonstrate a useful approach. Consider what would have happened in our proof of [reassoc_correct] if we had first added an unfortunate rewriting hint. *)\n\nReset reassoc_correct.\n\nTheorem confounder : forall e1 e2 e3,\n eval e1 * eval e2 * eval e3 = eval e1 * (eval e2 + 1 - 1) * eval e3.\n crush.\nQed.\n\nHint Rewrite confounder.\n\nTheorem reassoc_correct : forall e, eval (reassoc e) = eval e.\n(* begin thide *)\n induction e; crush;\n match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\n\n (** One subgoal remains:\n \n [[\n ============================\n eval e1 * (eval e3 + 1 - 1) * eval e4 = eval e1 * eval e2\n ]]\n\n The poorly chosen rewrite rule fired, changing the goal to a form where another hint no longer applies. Imagine that we are in the middle of a large development with many hints. How would we diagnose the problem? First, we might not be sure which case of the inductive proof has gone wrong. It is useful to separate out our automation procedure and apply it manually. *)\n\n Restart.\n\n Ltac t := crush; match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\n\n induction e.\n\n (** Since we see the subgoals before any simplification occurs, it is clear that we are looking at the case for constants. Our [t] makes short work of it. *)\n \n t.\n\n (** The next subgoal, for addition, is also discharged without trouble. *)\n\n t.\n\n (** The final subgoal is for multiplication, and it is here that we get stuck in the proof state summarized above. *)\n\n t.\n\n (** What is [t] doing to get us to this point? The %\\index{tactics!info}%[info] command can help us answer this kind of question. (As of this writing, [info] is no longer functioning in the most recent Coq release, but I hope it returns.) *)\n\n Undo.\n info t.\n\n (* begin hide *)\n (* begin thide *)\n Definition eir := eq_ind_r.\n (* end thide *)\n (* end hide *)\n\n (** %\\vspace{-.15in}%[[\n == simpl in *; intuition; subst; autorewrite with core in *; \n simpl in *; intuition; subst; autorewrite with core in *; \n simpl in *; intuition; subst; destruct (reassoc e2).\n simpl in *; intuition.\n \n simpl in *; intuition.\n \n simpl in *; intuition; subst; autorewrite with core in *;\n refine (eq_ind_r\n (fun n : nat =>\n n * (eval e3 + 1 - 1) * eval e4 = eval e1 * eval e2) _ IHe1);\n autorewrite with core in *; simpl in *; intuition; \n subst; autorewrite with core in *; simpl in *; \n intuition; subst.\n \n ]]\n\n A detailed trace of [t]'s execution appears. Since we are using the very general [crush] tactic, many of these steps have no effect and only occur as instances of a more general strategy. We can copy-and-paste the details to see where things go wrong. *)\n\n Undo.\n\n (** We arbitrarily split the script into chunks. The first few seem not to do any harm. *)\n\n simpl in *; intuition; subst; autorewrite with core in *.\n simpl in *; intuition; subst; autorewrite with core in *.\n simpl in *; intuition; subst; destruct (reassoc e2).\n simpl in *; intuition.\n simpl in *; intuition.\n\n (** The next step is revealed as the culprit, bringing us to the final unproved subgoal. *)\n\n simpl in *; intuition; subst; autorewrite with core in *.\n\n (** We can split the steps further to assign blame. *)\n\n Undo.\n\n simpl in *.\n intuition.\n subst.\n autorewrite with core in *.\n\n (** It was the final of these four tactics that made the rewrite. We can find out exactly what happened. The [info] command presents hierarchical views of proof steps, and we can zoom down to a lower level of detail by applying [info] to one of the steps that appeared in the original trace. *)\n\n Undo.\n\n info autorewrite with core in *.\n (** %\\vspace{-.15in}%[[\n == refine (eq_ind_r (fun n : nat => n = eval e1 * eval e2) _\n (confounder (reassoc e1) e3 e4)).\n ]]\n\n The way a rewrite is displayed is somewhat baroque, but we can see that theorem [confounder] is the final culprit. At this point, we could remove that hint, prove an alternate version of the key lemma [rewr], or come up with some other remedy. Fixing this kind of problem tends to be relatively easy once the problem is revealed. *)\n\nAbort.\n(* end thide *)\n\n(** Sometimes a change to a development has undesirable performance consequences, even if it does not prevent any old proof scripts from completing. If the performance consequences are severe enough, the proof scripts can be considered broken for practical purposes.\n\n Here is one example of a performance surprise. *)\n\nSection slow.\n Hint Resolve trans_eq.\n\n (** The central element of the problem is the addition of transitivity as a hint. With transitivity available, it is easy for proof search to wind up exploring exponential search spaces. We also add a few other arbitrary variables and hypotheses, designed to lead to trouble later. *)\n\n Variable A : Set.\n Variables P Q R S : A -> A -> Prop.\n Variable f : A -> A.\n\n Hypothesis H1 : forall x y, P x y -> Q x y -> R x y -> f x = f y.\n Hypothesis H2 : forall x y, S x y -> R x y.\n\n (** We prove a simple lemma very quickly, using the %\\index{Vernacular commands!Time}%[Time] command to measure exactly how quickly. *)\n\n Lemma slow : forall x y, P x y -> Q x y -> S x y -> f x = f y.\n Time eauto 6.\n(** <<\nFinished transaction in 0. secs (0.068004u,0.s)\n>>\n*)\n\n Qed.\n\n (** Now we add a different hypothesis, which is innocent enough; in fact, it is even provable as a theorem. *)\n\n Hypothesis H3 : forall x y, x = y -> f x = f y.\n\n Lemma slow' : forall x y, P x y -> Q x y -> S x y -> f x = f y.\n Time eauto 6.\n (** <<\nFinished transaction in 2. secs (1.264079u,0.s)\n >>\n %\\vspace{-.15in}%Why has the search time gone up so much? The [info] command is not much help, since it only shows the result of search, not all of the paths that turned out to be worthless. *)\n\n(* begin thide *)\n Restart.\n info eauto 6.\n (** %\\vspace{-.15in}%[[\n == intro x; intro y; intro H; intro H0; intro H4;\n simple eapply trans_eq.\n simple apply eq_refl.\n \n simple eapply trans_eq.\n simple apply eq_refl.\n \n simple eapply trans_eq.\n simple apply eq_refl.\n \n simple apply H1.\n eexact H.\n \n eexact H0.\n \n simple apply H2; eexact H4.\n ]]\n\n This output does not tell us why proof search takes so long, but it does provide a clue that would be useful if we had forgotten that we added transitivity as a hint. The [eauto] tactic is applying depth-first search, and the proof script where the real action is ends up buried inside a chain of pointless invocations of transitivity, where each invocation uses reflexivity to discharge one subgoal. Each increment to the depth argument to [eauto] adds another silly use of transitivity. This wasted proof effort only adds linear time overhead, as long as proof search never makes false steps. No false steps were made before we added the new hypothesis, but somehow the addition made possible a new faulty path. To understand which paths we enabled, we can use the %\\index{tactics!debug}%[debug] command. *)\n\n Restart.\n debug eauto 6.\n\n (* begin hide *)\n (* begin thide *)\n Definition deeeebug := (@eq_refl, @sym_eq).\n (* end thide *)\n (* end hide *)\n\n (** The output is a large proof tree. The beginning of the tree is enough to reveal what is happening:\n [[\n1 depth=6 \n1.1 depth=6 intro\n1.1.1 depth=6 intro\n1.1.1.1 depth=6 intro\n1.1.1.1.1 depth=6 intro\n1.1.1.1.1.1 depth=6 intro\n1.1.1.1.1.1.1 depth=5 apply H3\n1.1.1.1.1.1.1.1 depth=4 eapply trans_eq\n1.1.1.1.1.1.1.1.1 depth=4 apply eq_refl\n1.1.1.1.1.1.1.1.1.1 depth=3 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1 depth=3 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1 depth=2 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1 depth=2 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1.1.1 depth=1 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.1 depth=1 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.2 depth=1 apply sym_eq ; trivial\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.2.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.3 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2 depth=2 apply sym_eq ; trivial\n1.1.1.1.1.1.1.1.1.1.1.1.2.1 depth=1 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.1 depth=1 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.1.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.2 depth=1 apply sym_eq ; trivial\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.2.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.3 depth=0 eapply trans_eq\n ]]\n\n The first choice [eauto] makes is to apply [H3], since [H3] has the fewest hypotheses of all of the hypotheses and hints that match. However, it turns out that the single hypothesis generated is unprovable. That does not stop [eauto] from trying to prove it with an exponentially sized tree of applications of transitivity, reflexivity, and symmetry of equality. It is the children of the initial [apply H3] that account for all of the noticeable time in proof execution. In a more realistic development, we might use this output of [debug] to realize that adding transitivity as a hint was a bad idea. *)\n\n Qed.\n(* end thide *)\nEnd slow.\n\n(** As aggravating as the above situation may be, there is greater aggravation to be had from importing library modules with commands like %\\index{Vernacular commands!Require Import}%[Require Import]. Such a command imports not just the Gallina terms from a module, but also all the hints for [auto], [eauto], and [autorewrite]. Some very recent versions of Coq include mechanisms for removing hints from databases, but the proper solution is to be very conservative in exporting hints from modules. Consider putting hints in named databases, so that they may be used only when called upon explicitly, as demonstrated in Chapter 13.\n\nIt is also easy to end up with a proof script that uses too much memory. As tactics run, they avoid generating proof terms, since serious proof search will consider many possible avenues, and we do not want to build proof terms for subproofs that end up unused. Instead, tactic execution maintains%\\index{thunks}% _thunks_ (suspended computations, represented with closures), such that a tactic's proof-producing thunk is only executed when we run %\\index{Vernacular commands!Qed}%[Qed]. These thunks can use up large amounts of space, such that a proof script exhausts available memory, even when we know that we could have used much less memory by forcing some thunks earlier.\n\n The %\\index{tactics!abstract}%[abstract] tactical helps us force thunks by proving some subgoals as their own lemmas. For instance, a proof [induction x; crush] can in many cases be made to use significantly less peak memory by changing it to [induction x; abstract crush]. The main limitation of [abstract] is that it can only be applied to subgoals that are proved completely, with no undetermined unification variables in their initial states. Still, many large automated proofs can realize vast memory savings via [abstract]. *)\n\n\n(** * Modules *)\n\n(** Last chapter's examples of proof by reflection demonstrate opportunities for implementing abstract proof strategies with stronger formal guarantees than can be had with Ltac scripting. Coq's _module system_ provides another tool for more rigorous development of generic theorems. This feature is inspired by the module systems found in Standard ML%~\\cite{modules}% and OCaml, and the discussion that follows assumes familiarity with the basics of one of those systems.\n\n ML modules facilitate the grouping of %\\index{abstract type}%abstract types with operations over those types. Moreover, there is support for%\\index{functor}% _functors_, which are functions from modules to modules. A canonical example of a functor is one that builds a data structure implementation from a module that describes a domain of keys and its associated comparison operations.\n\n When we add modules to a base language with dependent types, it becomes possible to use modules and functors to formalize kinds of reasoning that are common in algebra. For instance, the following module signature captures the essence of the algebraic structure known as a group. A group consists of a carrier set [G], an associative binary operation [f], a left identity element [id] for [f], and an operation [i] that is a left inverse for [f].%\\index{Vernacular commands!Module Type}% *)\n\nModule Type GROUP.\n Parameter G : Set.\n Parameter f : G -> G -> G.\n Parameter id : G.\n Parameter i : G -> G.\n\n Axiom assoc : forall a b c, f (f a b) c = f a (f b c).\n Axiom ident : forall a, f id a = a.\n Axiom inverse : forall a, f (i a) a = id.\nEnd GROUP.\n\n(** Many useful theorems hold of arbitrary groups. We capture some such theorem statements in another module signature.%\\index{Vernacular commands!Declare Module}% *)\n\nModule Type GROUP_THEOREMS.\n Declare Module M : GROUP.\n\n Axiom ident' : forall a, M.f a M.id = a.\n\n Axiom inverse' : forall a, M.f a (M.i a) = M.id.\n\n Axiom unique_ident : forall id', (forall a, M.f id' a = a) -> id' = M.id.\nEnd GROUP_THEOREMS.\n\n(** We implement generic proofs of these theorems with a functor, whose input is an arbitrary group [M]. %\\index{Vernacular commands!Module}% *)\n\nModule GroupProofs (M : GROUP) : GROUP_THEOREMS with Module M := M.\n\n (** As in ML, Coq provides multiple options for ascribing signatures to modules. Here we use just the colon operator, which implements%\\index{opaque ascription}% _opaque ascription_, hiding all details of the module not exposed by the signature. Another option is%\\index{transparent ascription}% _transparent ascription_ via the [<:] operator, which checks for signature compatibility without hiding implementation details. Here we stick with opaque ascription but employ the [with] operation to add more detail to a signature, exposing just those implementation details that we need to. For instance, here we expose the underlying group representation set and operator definitions. Without such a refinement, we would get an output module proving theorems about some unknown group, which is not very useful. Also note that opaque ascription can in Coq have some undesirable consequences without analogues in ML, since not just the types but also the _definitions_ of identifiers have significance in type checking and theorem proving. *)\n\n Module M := M.\n (** To ensure that the module we are building meets the [GROUP_THEOREMS] signature, we add an extra local name for [M], the functor argument. *)\n\n Import M.\n (** It would be inconvenient to repeat the prefix [M.] everywhere in our theorem statements and proofs, so we bring all the identifiers of [M] into the local scope unqualified.\n\n Now we are ready to prove the three theorems. The proofs are completely manual, which may seem ironic given the content of the previous sections! This illustrates another lesson, which is that short proof scripts that change infrequently may be worth leaving unautomated. It would take some effort to build suitable generic automation for these theorems about groups, so I stick with manual proof scripts to avoid distracting us from the main message of the section. We take the proofs from the Wikipedia page on elementary group theory. *)\n\n Theorem inverse' : forall a, f a (i a) = id.\n intro.\n rewrite <- (ident (f a (i a))).\n rewrite <- (inverse (f a (i a))) at 1.\n rewrite assoc.\n rewrite assoc.\n rewrite <- (assoc (i a) a (i a)).\n rewrite inverse.\n rewrite ident.\n apply inverse.\n Qed.\n\n Theorem ident' : forall a, f a id = a.\n intro.\n rewrite <- (inverse a).\n rewrite <- assoc.\n rewrite inverse'.\n apply ident.\n Qed.\n\n Theorem unique_ident : forall id', (forall a, M.f id' a = a) -> id' = M.id.\n intros.\n rewrite <- (H id).\n symmetry.\n apply ident'.\n Qed.\nEnd GroupProofs.\n\n(** We can show that the integers with [+] form a group. *)\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nModule Int.\n Definition G := Z.\n Definition f x y := x + y.\n Definition id := 0.\n Definition i x := -x.\n\n Theorem assoc : forall a b c, f (f a b) c = f a (f b c).\n unfold f; crush.\n Qed.\n Theorem ident : forall a, f id a = a.\n unfold f, id; crush.\n Qed.\n Theorem inverse : forall a, f (i a) a = id.\n unfold f, i, id; crush.\n Qed.\nEnd Int.\n\n(** Next, we can produce integer-specific versions of the generic group theorems. *)\n\nModule IntProofs := GroupProofs(Int).\n\nCheck IntProofs.unique_ident.\n(** %\\vspace{-.15in}% [[\n IntProofs.unique_ident\n : forall e' : Int.G, (forall a : Int.G, Int.f e' a = a) -> e' = Int.e\n ]]\n\nProjections like [Int.G] are known to be definitionally equal to the concrete values we have assigned to them, so the above theorem yields as a trivial corollary the following more natural restatement: *)\n\nTheorem unique_ident : forall id', (forall a, id' + a = a) -> id' = 0.\n(* begin thide *)\n exact IntProofs.unique_ident.\nQed.\n(* end thide *)\n\n(** As in ML, the module system provides an effective way to structure large developments. Unlike in ML, Coq modules add no expressiveness; we can implement any module as an inhabitant of a dependent record type. It is the second-class nature of modules that makes them easier to use than dependent records in many cases. Because modules may only be used in quite restricted ways, it is easier to support convenient module coding through special commands and editing modes, as the above example demonstrates. An isomorphic implementation with records would have suffered from lack of such conveniences as module subtyping and importation of the fields of a module. On the other hand, all module values must be determined statically, so modules may not be computed, e.g., within the definitions of normal functions, based on particular function parameters. *)\n\n\n(** * Build Processes *)\n\n(* begin hide *)\n(* begin thide *)\nModule Lib.\n Module A.\n End A.\n Module B.\n End B.\n Module C.\n End C.\nEnd Lib.\nModule Client.\n Module D.\n End D.\n Module E.\n End E.\nEnd Client.\n(* end thide *)\n(* end hide *)\n\n(** As in software development, large Coq projects are much more manageable when split across multiple files and when decomposed into libraries. Coq and Proof General provide very good support for these activities.\n\n Consider a library that we will name [Lib], housed in directory <> and split between files <>, <>, and <>. A simple %\\index{Makefile}%Makefile will compile the library, relying on the standard Coq tool %\\index{coq\\_makefile}%<> to do the hard work.\n\n<<\nMODULES := A B C\nVS := $(MODULES:%=%.v)\n\n.PHONY: coq clean\n\ncoq: Makefile.coq\n $(MAKE) -f Makefile.coq\n\nMakefile.coq: Makefile $(VS)\n coq_makefile -R . Lib $(VS) -o Makefile.coq\n\nclean:: Makefile.coq\n $(MAKE) -f Makefile.coq clean\n rm -f Makefile.coq\n>>\n\n The Makefile begins by defining a variable <> holding the list of filenames to be included in the project. The primary target is <>, which depends on the construction of an auxiliary Makefile called <>. Another rule explains how to build that file. We call <>, using the <<-R>> flag to specify that files in the current directory should be considered to belong to the library [Lib]. This Makefile will build a compiled version of each module, such that <> is compiled into <>.\n\n Now code in <> may refer to definitions in <> after running\n [[\nRequire Import Lib.A.\n ]]\n %\\vspace{-.15in}%Library [Lib] is presented as a module, containing a submodule [A], which contains the definitions from <>. These are genuine modules in the sense of Coq's module system, and they may be passed to functors and so on.\n\n The command [Require Import] is a convenient combination of two more primitive commands. The %\\index{Vernacular commands!Require}%[Require] command finds the <<.vo>> file containing the named module, ensuring that the module is loaded into memory. The %\\index{Vernacular commands!Import}%[Import] command loads all top-level definitions of the named module into the current namespace, and it may be used with local modules that do not have corresponding <<.vo>> files. Another command, %\\index{Vernacular commands!Load}%[Load], is for inserting the contents of a named file verbatim. It is generally better to use the module-based commands, since they avoid rerunning proof scripts, and they facilitate reorganization of directory structure without the need to change code.\n\n Now we would like to use our library from a different development, called [Client] and found in directory <>, which has its own Makefile.\n\n<<\nMODULES := D E\nVS := $(MODULES:%=%.v)\n\n.PHONY: coq clean\n\ncoq: Makefile.coq\n $(MAKE) -f Makefile.coq\n\nMakefile.coq: Makefile $(VS)\n coq_makefile -R LIB Lib -R . Client $(VS) -o Makefile.coq\n\nclean:: Makefile.coq\n $(MAKE) -f Makefile.coq clean\n rm -f Makefile.coq\n>>\n\n We change the <> call to indicate where the library [Lib] is found. Now <> and <> can refer to definitions from [Lib] module [A] after running\n [[\nRequire Import Lib.A.\n ]]\n %\\vspace{-.15in}\\noindent{}%and <> can refer to definitions from <> by running\n [[\nRequire Import Client.D.\n ]]\n %\\vspace{-.15in}%It can be useful to split a library into several files, but it is also inconvenient for client code to import library modules individually. We can get the best of both worlds by, for example, adding an extra source file <> to [Lib]'s directory and Makefile, where that file contains just this line:%\\index{Vernacular commands!Require Export}%\n [[\nRequire Export Lib.A Lib.B Lib.C.\n ]]\n %\\vspace{-.15in}%Now client code can import all definitions from all of [Lib]'s modules simply by running\n [[\nRequire Import Lib.\n ]]\n %\\vspace{-.15in}%The two Makefiles above share a lot of code, so, in practice, it is useful to define a common Makefile that is included by multiple library-specific Makefiles.\n\n %\\medskip%\n\n The remaining ingredient is the proper way of editing library code files in Proof General. Recall this snippet of <<.emacs>> code from Chapter 2, which tells Proof General where to find the library associated with this book.\n\n<<\n(custom-set-variables\n ...\n '(coq-prog-args '(\"-R\" \"/path/to/cpdt/src\" \"Cpdt\"))\n ...\n)\n>>\n\n To do interactive editing of our current example, we just need to change the flags to point to the right places.\n\n<<\n(custom-set-variables\n ...\n; '(coq-prog-args '(\"-R\" \"/path/to/cpdt/src\" \"Cpdt\"))\n '(coq-prog-args '(\"-R\" \"LIB\" \"Lib\" \"-R\" \"CLIENT\" \"Client\"))\n ...\n)\n>>\n\n When working on multiple projects, it is useful to leave multiple versions of this setting in your <<.emacs>> file, commenting out all but one of them at any moment in time. To switch between projects, change the commenting structure and restart Emacs.\n\n Alternatively, we can revisit the directory-local settings approach and write the following into a file <<.dir-locals.el>> in <>:\n\n<<\n((coq-mode . ((coq-prog-args .\n (\"-emacs-U\" \"-R\" \"LIB\" \"Lib\" \"-R\" \"CLIENT\" \"Client\")))))\n>>\n\n A downside of this approach is that users of your code may not want to trust the arbitrary Emacs Lisp programs that you are allowed to place in such files, so that they prefer to add mappings manually.\n\n Relatively recent versions of Coq support another, more principled approach to all this. A project's list of settings and source files may be saved in a single file named <<_CoqProject>>, which is processed uniformly by recent enough versions of <>, Proof General, and CoqIDE. For details, see the Coq manual.\n*)\n", "meta": {"author": "paul-kline", "repo": "protosynth", "sha": "1b66397cea554f086cf4bdc95d61bfa269da890a", "save_path": "github-repos/coq/paul-kline-protosynth", "path": "github-repos/coq/paul-kline-protosynth/protosynth-1b66397cea554f086cf4bdc95d61bfa269da890a/cpdt/src/Large.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.15610488959337065, "lm_q1q2_score": 0.07561409957728622}} {"text": "(** * Preface *)\n\n(* ###################################################################### *)\n(** * Welcome *)\n\n(** This electronic book is a course on _Software Foundations_, the\n mathematical underpinnings of reliable software. Topics include\n basic concepts of logic, computer-assisted theorem proving, the\n Coq proof assistant, functional programming, operational\n semantics, Hoare logic, and static type systems. The exposition\n is intended for a broad range of readers, from advanced\n undergraduates to PhD students and researchers. No specific\n background in logic or programming languages is assumed, though a\n degree of mathematical maturity will be helpful.\n\n The principal novelty of the course is that it is one hundred per\n cent formalized and machine-checked: the entire text is literally\n a script for Coq. It is intended to be read alongside an\n interactive session with Coq. All the details in the text are\n fully formalized in Coq, and the exercises are designed to be\n worked using Coq.\n\n The files are organized into a sequence of core chapters, covering\n about one semester's worth of material and organized into a\n coherent linear narrative, plus a number of \"appendices\" covering\n additional topics. All the core chapters are suitable for both\n upper-level undergraduate and graduate students. *)\n\n\n(* ###################################################################### *)\n(** * Overview *)\n\n(** Building reliable software is hard. The scale and complexity of\n modern systems, the number of people involved in building them,\n and the range of demands placed on them make it extremely\n difficult even to build software that is more or less correct,\n much less to get it 100%% correct. At the same time, the\n increasing degree to which information processing is woven into\n every aspect of society continually amplifies the cost of bugs and\n insecurities.\n\n Computer scientists and software engineers have responded to these\n challenges by developing a whole host of techniques for improving\n software reliability, ranging from recommendations about managing\n software projects and organizing programming teams (e.g., extreme\n programming) to design philosophies for libraries (e.g.,\n model-view-controller, publish-subscribe, etc.) and programming\n languages (e.g., object-oriented programming, aspect-oriented\n programming, functional programming, ...) and to mathematical\n techniques for specifying and reasoning about properties of\n software and tools for helping validate these properties.\n\n The present course is focused on this last set of techniques. The\n text weaves together five conceptual threads:\n\n (1) basic tools from _logic_ for making and justifying precise\n claims about programs;\n\n (2) the use of _proof assistants_ to construct rigorous logical\n arguments;\n\n (3) the idea of _functional programming_, both as a method of\n programming and as a bridge between programming and logic;\n\n (4) formal techniques for _reasoning about the properties of\n specific programs_ (e.g., the fact that a loop terminates on\n all inputs, or that a sorting function or a compiler obeys a\n particular specification); and\n\n (5) the use of _type systems_ for establishing well-behavedness\n guarantees for _all_ programs in a given programming\n language (e.g., the fact that well-typed Java programs cannot\n be subverted at runtime).\n\n Each of these topics is easily rich enough to fill a whole course\n in its own right; taking all of them together naturally means that\n much will be left unsaid. But we hope readers will find that the\n themes illuminate and amplify each other in useful ways, and that\n bringing them together creates a foundation from which it will be\n easy to dig into any of them more deeply. Some suggestions for\n further reading can be found in the [Postscript] chapter. *)\n\n(** ** Logic *)\n\n(** Logic is the field of study whose subject matter is _proofs_ --\n unassailable arguments for the truth of particular propositions.\n Volumes have been written about the central role of logic in\n computer science. Manna and Waldinger called it \"the calculus of\n computer science,\" while Halpern et al.'s paper _On the Unusual\n Effectiveness of Logic in Computer Science_ catalogs scores of\n ways in which logic offers critical tools and insights. Indeed,\n they observe that \"As a matter of fact, logic has turned out to be\n significiantly more effective in computer science than it has been\n in mathematics. This is quite remarkable, especially since much\n of the impetus for the development of logic during the past one\n hundred years came from mathematics.\"\n\n In particular, the fundamental notion of inductive proofs is\n ubiquitous in all of computer science. You have surely seen them\n before, in contexts from discrete math to analysis of algorithms,\n but in this course we will examine them much more deeply than you\n have probably done so far. *)\n\n(** ** Proof Assistants *)\n\n(** The flow of ideas between logic and computer science has not been\n in just one direction: CS has also made important contributions to\n logic. One of these has been the development of software tools\n for helping construct proofs of logical propositions. These tools\n fall into two broad categories:\n\n - _Automated theorem provers_ provide \"push-button\" operation:\n you give them a proposition and they return either _true_,\n _false_, or _ran out of time_. Although their capabilities\n are limited to fairly specific sorts of reasoning, they have\n matured tremendously in recent years and are used now in a\n huge variety of settings. Examples of such tools include SAT\n solvers, SMT solvers, and model checkers.\n\n - _Proof assistants_ are hybrid tools that automate the more\n routine aspects of building proofs while depending on human\n guidance for more difficult aspects. Widely used proof\n assistants include Isabelle, Agda, Twelf, ACL2, PVS, and Coq,\n among many others.\n\n This course is based around Coq, a proof assistant that has been\n under development since 1983 at a number of French research labs\n and universities. Coq provides a rich environment for interactive\n development of machine-checked formal reasoning. The kernel of\n the Coq system is a simple proof-checker which guarantees that\n only correct deduction steps are performed. On top of this\n kernel, the Coq environment provides high-level facilities for\n proof development, including powerful tactics for constructing\n complex proofs semi-automatically, and a large library of common\n definitions and lemmas.\n\n Coq has been a critical enabler for a huge variety of work across\n computer science and mathematics:\n\n - As a _platform for modeling programming languages_, it has become\n a standard tool for researchers who need to describe and reason\n about complex language definitions. It has been used, for\n example, to check the security of the JavaCard platform,\n obtaining the highest level of common criteria certification,\n and for formal specifications of the x86 and LLVM instruction\n sets.\n\n - As an _environment for developing formally certified software_,\n Coq has been used to build CompCert, a fully-verified optimizing\n compiler for C, for proving the correctness of subtle algorithms\n involving floating point numbers, and as the basis for\n Certicrypt, an environment for reasoning about the security of\n cryptographic algorithms.\n\n - As a _realistic environment for programming with dependent\n types_, it has inspired numerous innovations. For example, the\n Ynot project at Harvard embeds \"relational Hoare reasoning\" (an\n extension of the _Hoare Logic_ we will see later in this course)\n in Coq.\n\n - As a _proof assistant for higher-order logic_, it has been used\n to validate a number of important results in mathematics. For\n example, its ability to include complex computations inside\n proofs made it possible to develop the first formally verified\n proof of the 4-color theorem. This proof had previously been\n controversial among mathematicians because part of it included\n checking a large number of configurations using a program. In\n the Coq formalization, everything is checked, including the\n correctness of the computational part. More recently, an even\n more massive effort led to a Coq formalization of the\n Feit-Thompson Theorem -- the first major step in the\n classification of finite simple groups.\n\n By the way, in case you're wondering about the name, here's what\n the official Coq web site says: \"Some French computer scientists\n have a tradition of naming their software as animal species: Caml,\n Elan, Foc or Phox are examples of this tacit convention. In French,\n 'coq' means rooster, and it sounds like the initials of the\n Calculus of Constructions (CoC) on which it is based.\" The rooster\n is also the national symbol of France, and \"Coq\" are the first\n three letters of the name of Thierry Coquand, one of Coq's early\n developers. *)\n\n(** ** Functional Programming *)\n\n(** The term _functional programming_ refers both to a collection of\n programming idioms that can be used in almost any programming\n language and to a family of programming languages designed to\n emphasize these idioms, including Haskell, OCaml, Standard ML,\n F##, Scala, Scheme, Racket, Common Lisp, Clojure, Erlang, and Coq.\n\n Functional programming has been developed over many decades --\n indeed, its roots go back to Church's lambda-calculus, which was\n invented in the 1930s before the era of the computer began! But\n since the early '90s it has enjoyed a surge of interest among\n industrial engineers and language designers, playing a key role in\n high-value systems at companies like Jane St. Capital, Microsoft,\n Facebook, and Ericsson.\n\n The most basic tenet of functional programming is that, as much as\n possible, computation should be _pure_, in the sense that the only\n effect of execution should be to produce a result: the computation\n should be free from _side effects_ such as I/O, assignments to\n mutable variables, redirecting pointers, etc. For example,\n whereas an _imperative_ sorting function might take a list of\n numbers and rearrange its pointers to put the list in order, a\n pure sorting function would take the original list and return a\n _new_ list containing the same numbers in sorted order.\n\n One significant benefit of this style of programming is that it\n makes programs easier to understand and reason about. If every\n operation on a data structure yields a new data structure, leaving\n the old one intact, then there is no need to worry about how that\n structure is being shared and whether a change by one part of the\n program might break an invariant that another part of the program\n relies on. These considerations are particularly critical in\n concurrent programs, where every piece of mutable state that is\n shared between threads is a potential source of pernicious bugs.\n Indeed, a large part of the recent interest in functional\n programming in industry is due to its simple behavior in the\n presence of concurrency.\n\n Another reason for the current excitement about functional\n programming is related to the first: functional programs are often\n much easier to parallelize than their imperative counterparts. If\n running a computation has no effect other than producing a result,\n then it does not matter _where_ it is run. Similarly, if a data\n structure is never modified destructively, then it can be copied\n freely, across cores or across the network. Indeed, the MapReduce\n idiom that lies at the heart of massively distributed query\n processors like Hadoop and is used by Google to index the entire\n web is a classic example of functional programming.\n\n For purposes of this course, functional programming has yet\n another significant attraction: it serves as a bridge between\n logic and computer science. Indeed, Coq itself can be viewed as a\n combination of a small but extremely expressive functional\n programming language plus with a set of tools for stating and\n proving logical assertions. Moreover, when we come to look more\n closely, we find that these two sides of Coq are actually aspects\n of the very same underlying machinery -- i.e., _proofs are\n programs_. *)\n\n(** ** Program Verification *)\n\n(** The first third of the book is devoted to developing the\n conceptual framework of logic and functional programming and\n gaining enough fluency with Coq to use it for modeling and\n reasoning about nontrivial artifacts. From this point on, we\n increasingly turn our attention to two broad topics of critical\n importance to the enterprise of building reliable software (and\n hardware): techniques for proving specific properties of\n particular _programs_ and for proving general properties of whole\n programming _languages_.\n\n For both of these, the first thing we need is a way of\n representing programs as mathematical objects, so we can talk\n about them precisely, and ways of describing their behavior in\n terms of mathematical functions or relations. Our tools for these\n tasks are _abstract syntax_ and _operational semantics_, a method\n of specifying the behavior of programs by writing abstract\n interpreters. At the beginning, we work with operational\n semantics in the so-called \"big-step\" style, which leads to\n somewhat simpler and more readable definitions, in those cases\n where it is applicable. Later on, we switch to a more detailed\n \"small-step\" style, which helps make some useful distinctions\n between different sorts of \"nonterminating\" program behaviors and\n which is applicable to a broader range of language features,\n including concurrency.\n\n The first programming language we consider in detail is _Imp_, a\n tiny toy language capturing the core features of conventional\n imperative programming: variables, assignment, conditionals, and\n loops. We study two different ways of reasoning about the\n properties of Imp programs.\n\n First, we consider what it means to say that two Imp programs are\n _equivalent_ in the sense that they give the same behaviors for\n all initial memories. This notion of equivalence then becomes a\n criterion for judging the correctness of _metaprograms_ --\n programs that manipulate other programs, such as compilers and\n optimizers. We build a simple optimizer for Imp and prove that it\n is correct.\n\n Second, we develop a methodology for proving that Imp programs\n satisfy formal specifications of their behavior. We introduce the\n notion of _Hoare triples_ -- Imp programs annotated with pre- and\n post-conditions describing what should be true about the memory in\n which they are started and what they promise to make true about\n the memory in which they terminate -- and the reasoning principles\n of _Hoare Logic_, a \"domain-specific logic\" specialized for\n convenient compositional reasoning about imperative programs, with\n concepts like \"loop invariant\" built in.\n\n This part of the course is intended to give readers a taste of the\n key ideas and mathematical tools used for a wide variety of\n real-world software and hardware verification tasks.\n*)\n\n(** ** Type Systems *)\n\n(** Our final major topic, covering the last third of the course, is\n _type systems_, a powerful set of tools for establishing\n properties of _all_ programs in a given language.\n\n Type systems are the best established and most popular example of\n a highly successful class of formal verification techniques known\n as _lightweight formal methods_. These are reasoning techniques\n of modest power -- modest enough that automatic checkers can be\n built into compilers, linkers, or program analyzers and thus be\n applied even by programmers unfamiliar with the underlying\n theories. (Other examples of lightweight formal methods include\n hardware and software model checkers, contract checkers, and\n run-time property monitoring techniques for detecting when some\n component of a system is not behaving according to specification).\n\n This topic brings us full circle: the language whose properties we\n study in this part, called the _simply typed lambda-calculus_, is\n essentially a simplified model of the core of Coq itself!\n\n*)\n\n(* ###################################################################### *)\n(** * Practicalities *)\n\n(* ###################################################################### *)\n(** ** Chapter Dependencies *)\n\n(** A diagram of the dependencies between chapters and some suggested\n paths through the material can be found in the file [deps.html]. *)\n\n(* ###################################################################### *)\n(** ** System Requirements *)\n\n(** Coq runs on Windows, Linux, and OS X. You will need:\n\n - A current installation of Coq, available from the Coq home\n page. Everything should work with version 8.4.\n\n - An IDE for interacting with Coq. Currently, there are two\n choices:\n\n - Proof General is an Emacs-based IDE. It tends to be\n preferred by users who are already comfortable with\n Emacs. It requires a separate installation (google\n \"Proof General\").\n\n - CoqIDE is a simpler stand-alone IDE. It is distributed\n with Coq, but on some platforms compiling it involves\n installing additional packages for GUI libraries and\n such. *)\n\n(* ###################################################################### *)\n(** ** Exercises *)\n\n(** Each chapter includes numerous exercises. Each is marked with a\n \"star rating,\" which can be interpreted as follows:\n\n - One star: easy exercises that underscore points in the text\n and that, for most readers, should take only a minute or two.\n Get in the habit of working these as you reach them.\n\n - Two stars: straightforward exercises (five or ten minutes).\n\n - Three stars: exercises requiring a bit of thought (ten\n minutes to half an hour).\n\n - Four and five stars: more difficult exercises (half an hour\n and up).\n\n Also, some exercises are marked \"advanced\", and some are marked\n \"optional.\" Doing just the non-optional, non-advanced exercises\n should provide good coverage of the core material. Optional\n exercises provide a bit of extra practice with key concepts and\n introduce secondary themes that may be of interest to some\n readers. Advanced exercises are for readers who want an extra\n challenge (and, in return, a deeper contact with the material).\n\n _Please do not post solutions to the exercises in public places_:\n Software Foundations is widely used both for self-study and for\n university courses. Having solutions easily available makes it\n much less useful for courses, which typically have graded homework\n assignments. The authors especially request that readers not post\n solutions to the exercises anyplace where they can be found by\n search engines.\n*)\n\n(* ###################################################################### *)\n(** ** Downloading the Coq Files *)\n\n(** A tar file containing the full sources for the \"release version\"\n of these notes (as a collection of Coq scripts and HTML files) is\n available here:\n<<\n http://www.cis.upenn.edu/~bcpierce/sf \n>>\n If you are using the notes as part of a class, you may be given\n access to a locally extended version of the files, which you\n should use instead of the release version.\n*)\n\n(* ###################################################################### *)\n(** * Note for Instructors *)\n\n(** If you intend to use these materials in your own course, you will\n undoubtedly find things you'd like to change, improve, or add.\n Your contributions are welcome!\n\n Please send an email to Benjamin Pierce describing yourself and\n how you would like to use the materials, and including the result\n of doing \"htpasswd -s -n NAME\", where NAME is your preferred user\n name. We'll set you up with read/write access to our subversion\n repository and developers' mailing list; in the repository you'll\n find a [README] with further instructions. *)\n\n(* ###################################################################### *)\n(** * Translations *)\n\n(** Thanks to the efforts of a team of volunteer translators, _Software \n Foundations_ can now be enjoyed in Japanese at [http://proofcafe.org/sf]\n*)\n\n(** $Date: 2014-12-31 15:31:47 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "elfi", "repo": "sf", "sha": "169c89f59bec1415ddf8d290a40c533d19f862d5", "save_path": "github-repos/coq/elfi-sf", "path": "github-repos/coq/elfi-sf/sf-169c89f59bec1415ddf8d290a40c533d19f862d5/orig_files/Preface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.15405756463346185, "lm_q1q2_score": 0.07522375073023425}} {"text": "(**\n\n<<\n Lecture 2: Fundamentals of Coq\n -------------------------------------------------------------\n Anders Mörtberg (Carnegie Mellon and Stockholm University)\n>>\n\nThe Coq proof assistant is a programming language for writing\nproofs: https://coq.inria.fr/\n\nIt has been around since 1984 and was initially implemented by Thierry\nCoquand and his PhD supervisor Gérard Huet. The first version, called\nCoC, implemented the Calculus of Constructions as presented in:\n\n\"The Calculus of Constructions\"\nThierry Coquand and Gérard Huet\nInformation and Computation 76(2–3): 95–120. 1988.\n\nIt was later extended to the Calculus of Inductive Constructions and\nthe name changed to Coq. These type theories are similar to Martin-Löf\ntype theory. As Coq is supposed to be a programming language for\ndeveloping proofs all programs have to be terminating, so it can be\nseen as a \"total\" programming language.\n\nThe Coq system has a very long and detailed reference manual:\n\nhttps://coq.inria.fr/distrib/current/refman/\n\nHowever, UniMath is only using a small subset of Coq, so there is a\nlot of information that is not relevant for UniMath development in\nthere. The fragment of Coq that UniMath uses consists of:\n\n- Pi-types (with judgmental eta)\n- Sigma-types (with judgmental eta)\n- The inductive types of natural numbers, booleans, unit and empty\n- Coproduct types\n- A universe UU\n\nThe reason we only have one universe is that there is no support for\nuniverse resizing axioms in Coq yet. Because of this we assume the\ninconsistent rule UU : UU, but we are working on improving this so\nthat we can make use of Coq's universe consistency checker.\nFurthermore, the reason UniMath only relies on this subset is that\neverything in UniMath has to be motivated by the model in simplicial\nsets:\n\nhttps://arxiv.org/abs/1211.2851\n\nIn this lecture I will show some things than can be done in UniMath as\na programming language. In the later lectures we will also see how to\nprove properties about the programs that we can write in UniMath.\n\nThe UniMath library can be found at:\n\nhttps://github.com/UniMath/UniMath\n\nThis whole file is a Coq file and it hence has the file ending \".v\" (v\nfor \"vernacular\") and can be processed using:\n\n- emacs with proof-general: https://proofgeneral.github.io/\n\n- Coq IDE\n\nI use emacs as it is also an extremely powerful text editor, but if\nyou never saw emacs before it might be quite overwhelming. An\nalternative that might be easier for newcomers is Coq IDE (interactive\ndevelopment environment). It also has some features that emacs doesn't\nhave so some Coq experts use it as well, but in this talk I will use\nemacs.\n\nIn order to make emacs interact with Coq one should install Proof\nGeneral. This is an extension to emacs that enables it to interact\nwith a range of proof assistants, including Coq. For UniMath\ndevelopment one should also install agda-mode in order to be able to\nproperly insert unicode characters.\n\nThe basic keybinding that I use when working in Proof General are:\n<<\nC-c C-n -- Process one line\nC-c C-u -- Unprocess a line\nC-c C-ENTER -- Process the whole buffer up until the cursor\nC-c C-b -- Process the whole file\nC-c C-r -- Unprocess (retract) the whole file\nC-x C-c -- Kill the Coq process\n>>\nFor more commands see:\n\nhttps://proofgeneral.github.io/doc/master/userman/Basic-Script-Management/#Script-processing-commands\nhttps://proofgeneral.github.io/doc/master/userman/Coq-Proof-General/#Coq_002dspecific-commands\n\nHere C = CTRL and M = ALT on a standard emacs setup, so \"C-c C-n\"\nmeans \"press c while holding CTRL and then press n while still holding\nCTRL\" (note that the keybindings are case sensitive). ENTER is the\n\"return\" key on my keyboard.\n\nVarious basic emacs commands:\n<<\nC-x C-f -- Find file\nC-x C-s -- Save file\nC-x C-x -- Exit emacs\nC-x b -- Kill buffer\nC-_ -- Undo\nC-x 1 -- Maximize buffer\nC-x 2 -- Split buffer horizontally\nC-x 3 -- Split buffer vertically\nM-% -- Search-and-replace\nM-; -- Comment region\n>>\nFor more commands see: https://www.gnu.org/software/emacs/ (or just\nGoogle \"emacs tutorial\")\n\n*)\n\n(** To import a file write:\n<<\nRequire Import Dir.Filename.\n>>\n*)\n\n(**\n\nThis will import the file Filename in the directory Dir. This assumes\nthat directory Dir is visible to Coq, that is, in the list of\ndirectories in which Coq looks for files to import. If you are working\nin the UniMath directory then Coq will be able to find all of the\nfiles in the UniMath library, but if you are in another directory you\nneed to the update your LoadPath by running\n<<\nAdd LoadPath \"/path/to/UniMath\".\n>>\n(where \"/path/to/UniMath/\" is replaced to the path where UniMath is\nlocated on your computer).\n\nCoq has a fancy module system which allows you to import and export\ndefinitions in various complicated ways. We extremely rarely use\nthis in UniMath so you can safely ignore it for now. The only thing\nyou need to know is that there is an alternative to Require Import:\n<<\nRequire Export Dir.Filename.\n>>\nthat is used in some files. This will make the file you are working\non import all of the definitions in Dir.Filename and then export\nthem again so that any file that imports this file also gets the\ndefinitions in Dir.Filename. I personally only use Require Import.\n\n*)\n\n(* Let's import one of the most basic UniMath file: *)\nRequire Import UniMath.Foundations.Preamble.\n(* This file contains definition of the inductive types of UniMath,\nmakes UU the name for the universe and various other basic things. *)\n\n(** * Definitions, lambda terms *)\n\n(** The polymorphic identity function *)\nDefinition idfun : forall (A : UU), A -> A := fun (A : UU) (a : A) => a.\n\n(** forall = Pi *)\n(** fun = lambda *)\n\nCheck idfun.\nPrint idfun.\n\nDefinition idfun' (A : UU) (a : A) : A := a.\n\nCheck idfun'.\nPrint idfun'.\n\n(** The constant function that returns its first argument *)\nDefinition const (A B : UU) (a : A) (b : B) : A := a.\n\n(** The booleans are defined in UniMath.Foundations.Preamble *)\nAbout bool.\nPrint bool.\n\n(** These are generated by true and false *)\nCheck true.\nCheck false.\n\n(** They also come with an induction principle *)\nAbout bool_rect.\n\n(** Using this we can define a \"recursion\" principle *)\nDefinition ifbool (A : UU) (x y : A) : bool -> A :=\n bool_rect (fun _ : bool => A) x y.\n\n(** We can define boolean negation: *)\nDefinition negbool : bool -> bool :=\n ifbool bool false true.\n\n(** and compute with it *)\nEval compute in negbool true.\n\n(** Coq supports many evaluation strategies, like cbn and cbv, for\ndetails see:\n\nhttps://coq.inria.fr/refman/tactics.html#Conversion-tactics\n\n*)\n\n(** boolean and *)\nDefinition andbool (b : bool) : bool -> bool :=\n ifbool (bool -> bool) (idfun bool) (const bool bool false) b.\n\nEval compute in andbool true true.\nEval compute in andbool true false.\nEval compute in andbool false true.\nEval compute in andbool false false.\n\n(** The natural numbers are defined in UniMath.Foundations.Preamble *)\nAbout nat.\nPrint nat.\n\n(** They are defined as Peano numbers, but we can use numerals *)\nCheck 3.\n\n(** This type also comes with an induction principle *)\nCheck nat_rect.\n\n(** We can define the recursor: *)\nDefinition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=\n nat_rect (fun _ : nat => A) a f.\n\n(**\n\nThis can be understood as a function defined by the following clauses:\n<<\nnat_rec m f 0 = m\nnat_rec m f (S n) = f n (nat_rec m f n)\n>>\n*)\n\n(** We can look at the normal form of the recursor by *)\nEval compute in nat_rec.\n\n(** This contains a both a \"fix\" and \"match _ with _\". These primitives\nof Coq are not allowed in UniMath. Instead we write everything using\nrecursors. The reason is that everything we write in UniMath has to be\njustified by the simplicial set model and the situation for general\ninductive types with match is not spelled out in detail. *)\n\n(** If you are used to regular programming languages it might seem very\nstrange to only program with the recursors, but it's actually not too\nbad and we can do many programs quite directly. *)\n\n(** Truncated predecessor function *)\nDefinition pred : nat -> nat := nat_rec nat 0 (const nat nat).\n\nEval compute in pred 3.\n\n(** We can test if a number is even by: *)\nDefinition even : nat -> bool := nat_rec bool true (fun _ b => negbool b).\n\nEval compute in even 3.\nEval compute in even 4.\n\n(** Addition *)\nDefinition add (m : nat) : nat -> nat := nat_rec nat m (fun _ y => S y).\n\nEval compute in add 2 3.\n\n(** We can define a nice notation for addition by: *)\nNotation \"x + y\" := (add x y).\n\nEval compute in 4 + 9.\n\n(** To find information about a notation we can write: *)\nLocate \"+\".\n\n(** Coq allows us to write very sophisticated notations, for details\nsee: https://coq.inria.fr/refman/syntax-extensions.html *)\n\n(** In UniMath we use a lot of unicode symbols. To input a unicode\nsymbol type \\ and then the name of the symbol. For example \\alpha\ngives α. To get information about a unicode character, including\nhow to write it, put the cursor on top of the symbol and type:\nM-x describe-char\n\nWe can write:\n<<\n λ x, e instead of fun x => e\n ∏ (x : A), T instead of forall (x : A), T\n A → B instead of A -> B\n>>\n*)\n\n(** Iterate a function n times *)\nDefinition iter (A : UU) (a : A) (f : A → A) (n : nat) : A :=\n nat_rec A a (λ _ y, f y) n.\n\nNotation \"f ^ n\" := (λ x, iter _ x f n).\n\nEval compute in (pred ^ 2) 5.\n\nDefinition sub (m n : nat) : nat := (pred ^ n) m.\n\nEval compute in sub 15 4.\nEval compute in sub 11 15.\n\nDefinition is_zero : nat → bool := nat_rec bool true (λ _ _, false).\n\nEval compute in is_zero 3.\nEval compute in is_zero 0.\n\nDefinition eqnat (m n : nat) : bool :=\n andbool (is_zero (sub m n)) (is_zero (sub n m)).\n\nNotation \"m == n\" := (eqnat m n) (at level 50).\n\nEval compute in 1 + 1 == 2.\nEval compute in 5 == 3.\nEval compute in 9 == 5.\n\n(** Note that I could omit the A from the definition of f ̂ n and just\nreplace it by _. The reason is that Coq very often can infer what\narguments are so that we can omit them. *)\n\n(** For example if I omit nat in *)\nCheck idfun _ 3.\n(** Coq will figure it out for us. *)\n\n(** We can tell Coq to always put _ for an argument by using curly\nbraces in the definition: *)\n\nDefinition idfun'' {A : UU} (a : A) : A := a.\n\nCheck idfun'' 3.\nCheck idfun'' true.\n\n(** Such an argument is called an \"implicit\" and these are very useful\nto get definitions that don't take too many arguments. However, it is\nsometimes necessary to be able to give some of the arguments\nexplicitly, this is using \"@\". *)\n\nCheck @idfun'' nat 3.\n\n\n(** * More inductive types *)\n\n(** The inductive types we have seen so far come from the standard\nlibrary, but Coq allows us to define any inductive types we want. In\nUniMath we don't allow this and the additional inductive types we have\nare defined in Foundations. *)\n\n(** One of these is the coproduct (disjoint union) of types *)\nAbout coprod.\nPrint coprod.\nCheck ii1.\nCheck ii2.\nPrint inl.\nPrint inr.\n\nCheck (λ A B C : UU, @coprod_rect A B (λ _, C)).\n\nDefinition coprod_rec {A B C : UU} (f : A → C) (g : B → C) : coprod A B → C :=\n @coprod_rect A B (λ _, C) f g.\n\n(** We can define integers as a coproduct of nat with itself *)\n\nDefinition Z : UU := coprod nat nat.\n\nNotation \"⊹ x\" := (inl x) (at level 20).\nNotation \"─ x\" := (inr x) (at level 40).\n\n(** +1 = inl 1 *)\n(** 0 = inl 0 *)\n(** -1 = inr 0 *)\n(** Note that we get the negative numbers \"off-by-one\". *)\n\n\nDefinition Z1 : Z := ⊹ 1.\nDefinition Z0 : Z := ⊹ 0.\nDefinition Zn3 : Z := ─ 2.\n\n(** We can define a function by case on whether the number is ⊹ n or ─ n *)\nDefinition Zcase (A : UU) (fpos : nat → A) (fneg : nat → A) : Z → A :=\n coprod_rec fpos fneg.\n\nDefinition negate : Z → Z :=\n Zcase Z (λ x, ifbool Z Z0 (─ pred x) (is_zero x)) (λ x, ⊹ S x).\n\nEval compute in negate Z0.\nEval compute in negate Z1.\nEval compute in negate Zn3.\n\n(** We also have two more inductive types: *)\n\n(** The unit type with one inhabitant tt *)\nAbout unit.\nPrint unit.\n\n(** The empty type with no inhabitants *)\nAbout empty.\nPrint empty.\n\n\n(** * Sigma types *)\n\n(** Sigma types are called total2 and this is the only example of a\nRecord in the whole UniMath library. The reason we use a record is so\nthat we can get the eta principle definitionally. *)\n\nAbout total2.\nPrint total2.\n\n(** We have a notation ∑ (x : A), B for Sigma types *)\n\n(** To form a pair use *)\nCheck tpair.\nLocate \",,\".\n\n(** and to project out of a pair use *)\nCheck pr1.\nCheck pr2.\n\n(** In PartA.v we define the direct product as a Sigma type *)\nDefinition dirprod (X Y : UU) : UU := ∑ x : X, Y.\n\nNotation \"A × B\" := (dirprod A B) (at level 75, right associativity) : type_scope.\n\nDefinition dirprod_pr1 {X Y : UU} : X × Y → X := pr1.\nDefinition dirprod_pr2 {X Y : UU} : X × Y → Y := pr2.\n\nDefinition dirprodf {X Y X' Y' : UU} (f : X → Y) (f' : X' → Y')\n (xx' : X × X') : Y × Y' := (f (pr1 xx'),,f' (pr2 xx')).\n\nDefinition swap {X Y : UU} (xy : X × Y) : Y × X :=\n dirprodf dirprod_pr2 dirprod_pr1 (xy,,xy).\n\n(** We can define the type of even numbers as a Sigma-type: *)\nDefinition even_nat : UU := ∑ (n : nat), ifbool _ unit empty (even n).\n\nDefinition test20 : even_nat := (20,,tt).\n\n(** This Definition does not work *)\nFail Definition test3 : even_nat := (3,,tt).\n\n(** Section's can be very useful to only write parameters that are used\nmany times once and for all. They are also useful for organizing your\nfiles into logical sections. *)\nSection curry.\n\nVariables A B C : UU.\n\n(** To make these arguments implicit use:\n<<\nContext {A B C : UU}.\n>>\n*)\n\nDefinition curry : (A × B → C) → (A → B → C) :=\n λ (f : A × B → C) (a : A) (b : B), f (a,,b).\n\nDefinition uncurry : (A → B → C) → (A × B → C) :=\n λ (f : A → B → C) (ab : A × B), f (pr1 ab) (pr2 ab).\n\nEnd curry.\n\nCheck curry.\nPrint curry.\nCheck uncurry.\nPrint uncurry.\n\n\n(** These were all the basics for interacting with Coq in this\nlecture. The UniMath library is a very large library and so far we\nhave only seen parts of Preamble.v. When writing programs and proofs\nin UniMath it is very important to be able to search the library so\nthat you don't do something someone else has already done. *)\n\n(** To find everything about nat type: *)\nSearch nat.\n\n(** To search for all lemmas involving the pattern *)\n(* Search _ (_ -> _ -> _). *)\n\n(** To find information about a notation *)\nLocate \"+\".\n\n(** More information about searching can be found in the reference\nmanual:\n\nhttps://coq.inria.fr/distrib/current/refman/proof-engine/vernacular-commands.html?highlight=search#coq:cmd.search\n*)\n\n(**\n\nOne can also generate HTML documentation for UniMath that is a bit\neasier to browse than reading text files. This is done by typing:\n<<\n> make html\n>>\nYou can then open this documentation in your browser:\n<<\n> firefox html/toc.html\n>>\nIn order to have your comments display properly in the HTML use the\nfollowing format:\n\n(** This comment will be displayed *)\n(** * This will be displayed as a section header *)\n(** ** This will be a subsection *)\n\nFor more details see:\n\nhttps://coq.inria.fr/distrib/current/refman/tools.html#coqdoc\n\n*)\n\n(**\n\nThe UniMath library is organized into a collection of packages that\ncan be found in the UniMath folder. The library is then compiled using\na Makefile which specifies in which order things has to be compiled\nand how they should be compiled.\n\nIn order to have your file get compiled when you type \"make\" add it to\nthe .package/files file of the package where it belongs. See for\nexample: UniMath/UniMath/Foundations/.package/files\n\nIf you're working on a new package then you need to add it to the\nMakefile by writing:\n\nPACKAGES += MyPackage\n\n*)\n\n (*⋆⋆⋆⋆⋆⋆ THE END ⋆⋆⋆⋆⋆⋆*)\n", "meta": {"author": "UniMath", "repo": "Schools", "sha": "ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b", "save_path": "github-repos/coq/UniMath-Schools", "path": "github-repos/coq/UniMath-Schools/Schools-ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b/2019-04-Birmingham/Part2_Fundamentals_Coq/fundamentals_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1500288262426238, "lm_q1q2_score": 0.0750144131213119}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(* ################################################################# *)\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward.\n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (mostly works), and Scheme (a bit\n out of date). *)\n\nExtraction Language Ocaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nFrom LF Require Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ################################################################# *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ################################################################# *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we first need\n to set up the right correspondence between Coq strings and lists\n of OCaml characters. *)\n\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlString.\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nFrom LF Require Import Imp.\nFrom LF Require Import ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ################################################################# *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(* ################################################################# *)\n(** * Going Further *)\n\n(** Further details about extraction can be found in the Extract\n chapter in _Verified Functional Algorithms_ (_Software\n Foundations_ volume 3). *)\n\n(** $Date: 2017-08-24 17:13:02 -0400 (Thu, 24 Aug 2017) $ *)\n", "meta": {"author": "qq456cvb", "repo": "lf", "sha": "1a0b565880df5f4d891aa88c9674afeff8991cc8", "save_path": "github-repos/coq/qq456cvb-lf", "path": "github-repos/coq/qq456cvb-lf/lf-1a0b565880df5f4d891aa88c9674afeff8991cc8/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1500288262426238, "lm_q1q2_score": 0.07442837494173042}} {"text": "(*|\n#############################################\nBest practices for parametrized Coq libraries\n#############################################\n\n:Link: https://stackoverflow.com/q/71143362\n|*)\n\n(*|\nQuestion\n********\n\nI'm writing a library in Coq that depends on user-supplied type\nparameters. One central part is a construction along the lines of\n|*)\n\nRequire Import Ascii.\nRequire Import String.\nParameter UserType : Set. (* <<- placeholder for this example *)\nParameter UserToString : UserType -> string.\n\nInductive Tag : Set :=\n| TBool\n| TNat\n| TUser\n| TList : Tag -> Tag\n| TSum : Tag -> Tag -> Tag.\n\nFixpoint decodeT (t : Tag) : Set :=\n match t with\n | TBool => bool\n | TNat => nat\n | TUser => UserType (* <<- needed here *)\n | TList t' => list (decodeT t')\n | TSum l r => sum (decodeT l) (decodeT r)\n end.\n(* ...etc..., including: *)\nDefinition tostring (t : Tag) (v : decodeT t) : string :=\n (* match t with ... end *) \"dummy\".\n(* and other stuff *)\n\n(*|\nso I can't avoid those ``Parameter``\\ s in some form. The whole\nlibrary is split across multiple files, and because of the size it\nwould be pretty uncomfortable to put everything in one file.\n\nThere's a top-level wrapper that exports all sub-modules. Ideally, I'd\nlike to pass the parameters *once* when importing the library, and\nthen this wrapper can do some magic to propagate them to all\nsub-modules, so that afterwards I don't have to worry about it\nanymore.\n\nI've looked into various approaches, but nothing worked so far.\n\nIf I wrap the file contents in ``Section``\\ s, then the ``Parameter``\\\ns become extra arguments only on the definitions that use them, and\nthen I have to manually splice them in everywhere when using the\nlibrary's functions from outside.\n\nIf I don't wrap them in a ``Section``, they are module parameters but\nI can't find a way to actually provide the value. (All forms of ``with\nDefinition`` seem to require a module signature / ``Module Type``?\nDuplicating all names & types to make an explicit signature would be\nprohibitively redundant, so maybe there is a way to make it work, but\nI couldn't find it. The documentation is also rather unhelpful...)\nVariations like using ``Context`` instead seem to have the same\nproblem, as far as I tested things.\n\nI'm happy to make a ``Module Type UserDefs`` (or typeclass, or\nwhatever) that combines all the user definitions in a single value. I\njust don't know how to actually get it into the submodules.\n\nSo how do I do it? What needs to happen inside that sample file above,\nand what needs to happen on the outside, so that I can pass the\ndefinitions in *once* and then get a fully configured library to\n``Import``?\n|*)\n\n(*|\nAnswer\n******\n\n then I have to manually splice them in everywhere when using the\n library's functions from outside.\n\nThis is typically addressed by a mix of implicit parameters and type\nclasses.\n\nDeclare a class for user-provided parameters.\n|*)\n\nReset Initial. (* .none *)\nRequire Import String. (* .none *)\nClass UserParams : Type :=\n { UserType : Set\n ; UserToString : UserType -> string\n }.\n\n(* Make sure UserType and UserToString have UserParams as a maximally\n inserted implicit *)\n\n(*|\nThen in your library open sections parameterized by instances of that\nclass:\n|*)\n\nRequire Import Ascii.\nRequire Import String.\n\nSection MyLib.\n Context {userParams : UserParams}.\n (* Context generalizes Variable and allows you to set implicitness *)\n\n Inductive Tag : Set :=\n | TBool\n | TNat\n | TUser\n | TList : Tag -> Tag\n | TSum : Tag -> Tag -> Tag.\n\n Fixpoint decodeT (t : Tag) : Set :=\n match t with\n | TBool => bool\n | TNat => nat\n | TUser => UserType (* <<- needed here *)\n | TList t' => list (decodeT t')\n | TSum l r => sum (decodeT l) (decodeT r)\n end.\n (* ...etc..., including: *)\n Definition tostring (t : Tag) (v : decodeT t) : string :=\n (* match t with ... end *) \"dummy\".\n (* and other stuff *)\n\nEnd MyLib.\n\n(*|\nThen users instantiate the class\n\n.. code-block:: coq\n\n Require Import MyLib.\n\n Instance myParams : UserParams :=\n {| UserType := ...\n ; UserToString := ... |}.\n\nAnd then your library functions will automatically be instantiated\nwhen you use them.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/best-practices-for-parametrized-coq-libraries.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.1666754067576692, "lm_q1q2_score": 0.07425881402109528}} {"text": "(*|\n################################################\nWhy can't I define the following ``CoFixpoint``?\n################################################\n\n:Link: https://stackoverflow.com/q/30023530\n|*)\n\n(*|\nQuestion\n********\n\nI defined the following ``CoInductive`` type, ``stream``:\n|*)\n\nCoInductive stream (A : Type) : Type :=\n| Cons : A -> stream A -> stream A.\n\nCheck stream. (* .unfold *)\n\nCheck Cons. (* .unfold *)\n\n(*|\nThen, I tried to define the following ``CoFixpoint`` definition, ``zeros``:\n|*)\n\nFail CoFixpoint zeros : stream nat := Cons 0 zeros. (* .fails *)\n\n(*|\nI figured out that I have to explicitly instantiate the variable A:\n|*)\n\nCoFixpoint zeros : stream nat := Cons nat 0 zeros.\n\n(*|\nWhy doesn't the Coq infer the type of ``A`` by itself? How do I make\nit infer the type of ``A``?\n|*)\n\n(*|\nAnswer\n******\n\nYou need to declare ``A`` as implicit to ask Coq to infer it for you.\nThere are a few ways of doing it:\n\n1. Add the following declaration to your file: ``Set Implicit\n Arguments.``. This will cause Coq to turn on automatic inference\n for arguments such as ``A`` for ``Cons``, allowing you to write\n ``Cons 0 zeros``.\n\n2. Turn on implicit arguments just for ``Cons``, without affecting the\n rest of the file:\n|*)\n\nArguments Cons {A} _ _.\n\n(*|\n This declaration marks ``A`` as implicit and leaves the other two\n arguments as explicit.\n\n3. Mark ``A`` as implicit in the definition of ``stream``:\n\n .. coq::\n|*)\n\nReset Initial. (* .none *)\nCoInductive stream {A : Type} : Type :=\n| Cons : A -> stream -> stream.\n\n(*|\n I personally do not recommend doing this, however, as it will mark\n ``A`` as implicit for ``stream`` as well.\n\nYou can find more information about implicit arguments in the\n`reference manual\n`__\n\n----\n\n**A:** Side note: items 2. and 3. declare ``A`` as a\n`maximally-inserted\n`__\nargument. Implicit arguments inferred with the ``Set Implicit\nArguments`` directive are not declared to be insertable maximally. So,\nwhen applicable, one might want to add ``Set Maximal Implicit\nInsertion.``.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/why-cant-i-define-the-following-cofixpoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.21733751090819795, "lm_q1q2_score": 0.07423868728424658}} {"text": "(** * Preliminaries *)\n\n(** This file contains definitions and proofs from the Base Library for the ICL lecture. \n - Version: 3 October 2016\n - Author: Gert Smolka, Saarland University\n - Acknowlegments: Sigurd Schneider, Dominik Kirst, Yannick Forster\n *)\n\nFrom Undecidability.L Require Import Tactics.\n\nRequire Export Bool Omega List Setoid Morphisms.\n\nGlobal Set Implicit Arguments. \nGlobal Unset Strict Implicit.\nGlobal Unset Printing Records.\nGlobal Unset Printing Implicit Defensive.\nGlobal Set Regular Subst Tactic.\n\nHint Extern 4 => exact _.\n\n(** ** Lists *)\nExport ListNotations.\nNotation \"x 'el' A\" := (In x A) (at level 70).\nNotation \"A <<= B\" := (incl A B) (at level 70).\nNotation \"| A |\" := (length A) (at level 65).\n\nHint Extern 4 => \nmatch goal with\n|[ H: ?x el nil |- _ ] => destruct H\nend.\n\nLemma incl_nil X (A : list X) :\n nil <<= A.\nProof. intros x []. Qed.\n\nHint Rewrite <- app_assoc : list.\nHint Rewrite rev_app_distr map_app prod_length : list.\nHint Resolve in_eq in_nil in_cons in_or_app.\nHint Resolve incl_refl incl_tl incl_cons incl_appl incl_appr incl_app incl_nil.\n\n(** ** Tactics *)\nLtac inv H := inversion H; subst; try clear H.\n\nTactic Notation \"destruct\" \"_\":=\n match goal with\n | [ |- context[match ?X with _ => _ end] ] => destruct X\n | [ H : context[match ?X with _ => _ end] |- _ ] => destruct X \n end.\n\nHint Extern 4 => \nmatch goal with\n|[ H: False |- _ ] => destruct H\n|[ H: true=false |- _ ] => discriminate H\n|[ H: false=true |- _ ] => discriminate H\nend.\n\nLemma size_induction X (f : X -> nat) (p : X -> Type) :\n (forall x, (forall y, f y < f x -> p y) -> p x) -> \n forall x, p x.\n\nProof. \n intros IH x. apply IH. \n assert (G: forall n y, f y < n -> p y).\n { intros n. induction n.\n - intros y B. exfalso. omega.\n - intros y B. apply IH. intros z C. apply IHn. omega. }\n apply G.\nQed.\n\n\nLemma size_induction_dep L (X : L -> Type) (f : forall l, X l -> nat) (p : forall l, X l -> Type) :\n (forall l x, (forall l' y, f l' y < f l x -> p l' y) -> p l x) -> \n forall l x, p l x.\nProof. \n intros IH l x. apply IH. intros l'.\n assert (G: forall n l' y, f l' y < n -> p l' y).\n { intros n. induction n; intros l'' y.\n - intros B. exfalso. omega.\n - intros B. apply IH. intros ll z C. eapply IHn. omega. }\n apply G.\nQed.\n\n(* Definition Injective {A B} (f : A->B) := *)\n(* forall x y, f x = f y -> x = y. *)\n\n(* Section fix_X. *)\n(* Variable X:Type. *)\n(* Implicit Types (A B: list X) (a b c: X). *)\n\n(* Lemma last_app_eq A B a b : *)\n(* A++[a] = B++[b] -> A = B /\\ a = b. *)\n(* Proof. *)\n(* intros H%(f_equal (@rev X)). rewrite !rev_app_distr in H. split. *)\n(* - inv H. apply (f_equal (@rev X)) in H2. now rewrite !rev_involutive in H2. *)\n(* - now inv H. *)\n(* Qed. *)\n \n(* Lemma rev_eq A B: *)\n(* List.rev A = List.rev B <-> A = B. *)\n(* Proof. *)\n(* split. *)\n(* - intros H%(f_equal (@rev X)). now rewrite !rev_involutive in H. *)\n(* - now intros <-. *)\n(* Qed. *)\n\n(* Lemma rev_nil A: *)\n(* rev A = [] -> A = []. *)\n(* Proof. *)\n(* destruct A. auto. now intros H%symmetry%app_cons_not_nil. *)\n(* Qed. *)\n\n(* Lemma map_inj (Y:Type) A B (f: X -> Y) : *)\n(* Injective f -> map f A = map f B <-> A = B. *)\n(* Proof. *)\n(* intros inj. split. *)\n(* - revert B. induction A; intros B H; cbn in *; destruct B; auto; cbn in H; inv H. *)\n(* rewrite (inj a x H1). specialize (IHA B H2). now subst. *)\n(* - now intros <-. *)\n(* Qed. *)\n(* End fix_X. *)\n\n\nLemma app_incl_l X (A B C : list X) :\n A ++ B <<= C -> A <<= C.\nProof.\n firstorder eauto.\nQed.\n\nLemma app_incl_R X (A B C : list X) :\n A ++ B <<= C -> B <<= C.\nProof.\n firstorder eauto.\nQed.\n\nLemma cons_incl X (a : X) (A B : list X) : a :: A <<= B -> A <<= B.\nProof.\n intros ? ? ?. eapply H. firstorder.\nQed.\n\nLemma incl_sing X (a : X) A : a el A -> [a] <<= A.\nProof.\n now intros ? ? [-> | [] ].\nQed.\n\nHint Resolve app_incl_l app_incl_R cons_incl incl_sing.\n\n\n(* Hint Extern 4 (_ el map _ _) => eapply in_map_iff. *)\n(* Hint Extern 4 (_ el filter _ _) => eapply filter_In. *)\n\n(* Fixpoint count (l : list nat) (n : nat) := *)\n(* match l with *)\n(* | [] => 0 *)\n(* | m :: l => if Nat.eqb n m then S (count l n) else count l n *)\n(* end. *)\n\n(* Lemma countSplit (A B: list nat) (x: nat) : count A x + count B x = count (A ++ B) x. *)\n(* Proof. *)\n(* induction A. *)\n(* - reflexivity. *)\n(* - cbn. destruct (x =? a). *)\n(* + cbn. f_equal; exact IHA. *)\n(* + exact IHA. *)\n(* Qed. *)\n\n(* Lemma notInZero (x: nat) A : *)\n(* not (x el A) <-> count A x = 0. *)\n(* Proof. *)\n(* split; induction A. *)\n(* - reflexivity. *)\n(* - intros H. cbn in *. destruct (Nat.eqb_spec x a). *)\n(* + exfalso. apply H. left. congruence. *)\n(* + apply IHA. intros F. apply H. now right. *)\n(* - tauto. *)\n(* - cbn. destruct (Nat.eqb_spec x a). *)\n(* + subst a. omega. *)\n(* + intros H [E | E]. *)\n(* * now symmetry in E. *)\n(* * tauto. *)\n(* Qed. *)\n\n\n(** Positions and map-products for lists *)\n\nSection Positions.\n Variables (X: Type) (d: forall x y : X, {x = y} + {x <> y}).\n Implicit Types (x y: X) (A B : list X).\n\n Fixpoint pos x A : option nat :=\n match A with\n | nil => None\n | y :: A' => if d x y then Some 0\n else match pos x A' with\n | Some n => Some (S n)\n | None => None\n end\n end.\n\n Lemma el_pos x A :\n x el A -> { n | pos x A = Some n }.\n Proof.\n induction A as [|y A IH]; cbn; intros H.\n - destruct H as [].\n - destruct (d x y) as [<-|H1].\n + now exists 0.\n + destruct IH as [n IH].\n * destruct H as [->|H]; tauto.\n * rewrite IH. now exists (S n).\n Qed.\n\n Notation nthe n A := (nth_error A n).\n \n Lemma nthe_length A n :\n length A > n -> { x | nthe n A = Some x }.\n Proof.\n revert n.\n induction A as [|y A IH]; cbn; intros n H.\n - exfalso. omega.\n - destruct n as [|n]; cbn.\n + now exists y.\n + destruct (IH n) as [x H1]. omega. now exists x.\n Qed.\n \n Lemma pos_nthe x A n :\n pos x A = Some n -> nthe n A = Some x.\n Proof.\n revert n.\n induction A as [|y A IH]; cbn; intros n.\n - intros [=].\n - destruct (d x y) as [<-|H1].\n + now intros [= <-].\n + destruct (pos x A) as [k|]; intros [= <-]; cbn.\n now apply IH.\n Qed.\n \n Lemma nthe_app_l x n A B :\n nthe n A = Some x -> nthe n (A ++ B) = Some x.\n Proof.\n revert n.\n induction A as [|y A IH]; cbn; intros k H.\n - destruct k; discriminate H.\n - destruct k as [|k]; cbn in *. exact H.\n apply IH, H.\n Qed.\n\nEnd Positions.\n\nNotation nthe n A := (nth_error A n).\n\nLemma pos_nth X d (x : X) l n def : pos d x l = Some n -> nth n l def = x.\nProof.\n revert n; induction l; cbn; intros; try congruence.\n destruct (d x a); try destruct (pos d x l) eqn:E; inv H; eauto.\nQed.\n\nLemma pos_length X d (x : X) l n : pos d x l = Some n -> n < | l |.\nProof.\n revert n; induction l; cbn; intros; try congruence.\n destruct (d x a).\n - inv H. omega.\n - destruct (pos d x l) eqn:E; inv H; try omega. specialize (IHl _ eq_refl). omega.\nQed.\n\n\nFixpoint omap X Y (f : X -> option Y) l :=\n match l with\n | nil => nil\n | x :: l => match f x with Some y => y :: omap f l | None => omap f l end\n end.\n\nLemma in_omap_iff X Y (f : X -> option Y) l y : y el omap f l <-> exists x, x el l /\\ f x = Some y.\nProof.\n induction l; cbn.\n - firstorder.\n - destruct (f a) eqn:E; firstorder (subst; firstorder congruence).\nQed.\n\n\nSection neList.\n\n Variable X : Type.\n Variable P : list X -> Prop.\n\n Hypothesis B : (forall x : X, P [x]).\n Hypothesis S : (forall x A, P A -> P (x :: A)).\n \n Lemma list_ind_ne A : A <> [] -> P A.\n Proof.\n intros H. destruct A. congruence. clear H.\n revert x. induction A; eauto.\n Qed.\n\nEnd neList.\n\n\n(** ** Boolean propositions and decisions *)\n\nCoercion bool2Prop (b : bool) := if b then True else False.\n\nLemma bool_Prop_true b :\n b = true -> b.\nProof.\n intros A. rewrite A. cbn. eauto.\nQed.\n\nLemma bool_Prop_false b :\n b = false -> ~ b.\nProof.\n intros A. rewrite A. cbn. auto.\nQed.\n\nHint Resolve bool_Prop_true bool_Prop_false.\n\nHint Extern 4 => \nmatch goal with\n|[ H: False |- _ ] => destruct H\n|[ H: ~ bool2Prop true |- _ ] => destruct H\n|[ H: bool2Prop false |- _ ] => destruct H\n|[ H: true=false |- _ ] => discriminate H\n|[ H: false=true |- _ ] => discriminate H\n|[ H: ?b=false, H': bool2Prop(?b) |- _ ] => rewrite H in H'; destruct H'\n(* |[ H: ?x el nil |- _ ] => destruct H *)\nend.\n\nDefinition dec (X: Prop) : Type := {X} + {~ X}.\n\nCoercion dec2bool P (d: dec P) := if d then true else false.\n\nExisting Class dec.\n\nDefinition Dec (X: Prop) (d: dec X) : dec X := d.\nArguments Dec X {d}.\n\n\nLtac dec := repeat match goal with\n | [ |- context [ Dec ?x ] ] => let E := fresh \"E\" in destruct (Dec x) as [E | ]; [ try (rewrite E in *; clear E)| ]\n | [H : context [ Dec ?x ] |- _ ] => let E := fresh \"E\" in destruct (Dec x) as [E | ];\n [ try (rewrite E in *; clear E)| ]\n end; cbn [dec2bool].\n\nLemma Dec_reflect (X: Prop) (d: dec X) :\n Dec X <-> X.\nProof.\n destruct d as [A|A]; cbn; tauto.\nQed.\n\nNotation Decb X := (dec2bool (Dec X)).\n\nLemma Dec_reflect_eq (X Y: Prop) (d: dec X) (e: dec Y) :\n Decb X = Decb Y <-> (X <-> Y).\nProof.\n destruct d as [D|D], e as [E|E]; cbn; intuition congruence.\nQed.\n\nLemma Dec_auto (X: Prop) (d: dec X) :\n X -> Dec X.\nProof.\n destruct d as [A|A]; cbn; tauto.\nQed.\n\nLemma Dec_auto_not (X: Prop) (d: dec X) :\n ~ X -> ~ Dec X.\nProof.\n destruct d as [A|A]; cbn; tauto.\nQed.\n\nHint Resolve Dec_auto Dec_auto_not.\nHint Extern 4 => (* Improves type class inference *)\nmatch goal with\n | [ |- dec ((fun _ => _) _) ] => cbn\nend : typeclass_instances.\n\nTactic Notation \"decide\" constr(p) := \n destruct (Dec p).\nTactic Notation \"decide\" constr(p) \"as\" simple_intropattern(i) := \n destruct (Dec p) as i.\nTactic Notation \"decide\" \"_\" :=\n destruct (Dec _).\nTactic Notation \"have\" constr(E) := let X := fresh \"E\" in decide E as [X|X]; subst; try congruence; try omega; clear X.\n\nLemma Dec_true P {H : dec P} : dec2bool (Dec P) = true -> P.\nProof.\n decide P; cbv in *; firstorder.\nQed.\n\nLemma Dec_false P {H : dec P} : dec2bool (Dec P) = false -> ~P.\nProof.\n decide P; cbv in *; firstorder.\nQed.\n\nHint Extern 4 =>\nmatch goal with\n [ H : dec2bool (Dec ?P) = true |- _ ] => apply Dec_true in H\n| [ H : dec2bool (Dec ?P) = false |- _ ] => apply Dec_false in H\nend.\n\n(** Decided propositions behave classically *)\n\nLemma dec_DN X : \n dec X -> ~~ X -> X.\nProof. \n unfold dec; tauto. \nQed.\n\nLemma dec_DM_and X Y : \n dec X -> dec Y -> ~ (X /\\ Y) -> ~ X \\/ ~ Y.\nProof. \n unfold dec; tauto. \nQed.\n\nLemma dec_DM_impl X Y : \n dec X -> dec Y -> ~ (X -> Y) -> X /\\ ~ Y.\nProof. \n unfold dec; tauto. \nQed.\n\n(** Propagation rules for decisions *)\n\nFact dec_transfer P Q :\n P <-> Q -> dec P -> dec Q.\nProof.\n unfold dec. tauto.\nQed.\n\nInstance bool_dec (b: bool) :\n dec b.\nProof. \n unfold dec. destruct b; cbn; auto. \nQed.\n\nInstance True_dec :\n dec True.\nProof. \n unfold dec; tauto. \nQed.\n\nInstance False_dec :\n dec False.\nProof. \n unfold dec; tauto. \nQed.\n\nInstance impl_dec (X Y : Prop) : \n dec X -> dec Y -> dec (X -> Y).\nProof. \n unfold dec; tauto. \nQed.\n\nInstance and_dec (X Y : Prop) : \n dec X -> dec Y -> dec (X /\\ Y).\nProof. \n unfold dec; tauto. \nQed.\n\nInstance or_dec (X Y : Prop) : \n dec X -> dec Y -> dec (X \\/ Y).\nProof. \n unfold dec; tauto. \nQed.\n\n(* Coq standard modules make \"not\" and \"iff\" opaque for type class inference, \n can be seen with Print HintDb typeclass_instances. *)\n\nInstance not_dec (X : Prop) : \n dec X -> dec (~ X).\nProof. \n unfold not. auto.\nQed.\n\nInstance iff_dec (X Y : Prop) : \n dec X -> dec Y -> dec (X <-> Y).\nProof. \n unfold iff. auto.\nQed.\n\n(** ** Discrete types *)\n\nNotation \"'eq_dec' X\" := (forall x y : X, dec (x=y)) (at level 70).\n\nStructure eqType := EqType {\n eqType_X :> Type;\n eqType_dec : eq_dec eqType_X }.\n\nArguments EqType X {_} : rename.\n\nCanonical Structure eqType_CS X (A: eq_dec X) := EqType X.\n\nExisting Instance eqType_dec.\n\nInstance unit_eq_dec :\n eq_dec unit.\nProof.\n unfold dec. decide equality. \nQed.\n\nInstance bool_eq_dec : \n eq_dec bool.\nProof.\n unfold dec. decide equality. \nDefined.\n\nInstance nat_eq_dec : \n eq_dec nat.\nProof.\n unfold dec. decide equality.\nDefined.\n\nInstance prod_eq_dec X Y : \n eq_dec X -> eq_dec Y -> eq_dec (X * Y).\nProof.\n unfold dec. decide equality. \nDefined.\n\nInstance list_eq_dec X : \n eq_dec X -> eq_dec (list X).\nProof.\n unfold dec. decide equality. \nDefined.\n\nInstance sum_eq_dec X Y : \n eq_dec X -> eq_dec Y -> eq_dec (X + Y).\nProof.\n unfold dec. decide equality. \nDefined.\n\nInstance option_eq_dec X :\n eq_dec X -> eq_dec (option X).\nProof.\n unfold dec. decide equality.\nDefined.\n\nInstance Empty_set_eq_dec:\n eq_dec Empty_set.\nProof.\n unfold dec. decide equality.\nQed.\n\nInstance True_eq_dec:\n eq_dec True.\nProof.\n intros x y. destruct x,y. now left.\nQed.\n\nInstance False_eq_dec:\n eq_dec False.\nProof.\n intros [].\nQed.\n\nExport ListNotations.\nNotation \"x 'el' A\" := (In x A) (at level 70).\nNotation \"A <<= B\" := (incl A B) (at level 70).\nNotation \"| A |\" := (length A) (at level 65).\nDefinition equi X (A B : list X) : Prop := incl A B /\\ incl B A.\nNotation \"A === B\" := (equi A B) (at level 70).\nHint Unfold equi.\n\nHint Extern 4 => \nmatch goal with\n|[ H: ?x el nil |- _ ] => destruct H\nend.\n\n(** ** Lists *)\n\n(* Register additional simplification rules with autorewrite / simpl_list *)\n(* Print Rewrite HintDb list. *)\nHint Rewrite <- app_assoc : list.\nHint Rewrite rev_app_distr map_app prod_length : list.\n\nLemma list_cycle (X : Type) (A : list X) x :\n x::A <> A.\nProof.\n intros B.\n assert (C: |x::A| <> |A|) by (cbn; omega).\n apply C. now rewrite B.\nQed.\n\n(** *** Decisions for lists *)\n\nInstance list_in_dec X (x : X) (A : list X) : \n eq_dec X -> dec (x el A).\nProof.\n intros D. apply in_dec. exact D.\nQed.\n\n(* Certifying find *)\n\nLemma cfind X A (p: X -> Prop) (p_dec: forall x, dec (p x)) :\n {x | x el A /\\ p x} + {forall x, x el A -> ~ p x}.\nProof.\n destruct (find (fun x => Dec (p x)) A) eqn:E.\n - apply find_some in E. firstorder.\n - right. intros. eapply find_none in E; eauto.\nQed.\n\nArguments cfind {X} A p {p_dec}.\n\nInstance list_forall_dec X A (p : X -> Prop) :\n (forall x, dec (p x)) -> dec (forall x, x el A -> p x).\nProof.\n intros p_dec.\n destruct (find (fun x => Dec (~ p x)) A) eqn:Eq.\n - apply find_some in Eq as [H1 H0 %Dec_true]; right; auto. \n - left. intros x E. apply find_none with (x := x) in Eq. apply dec_DN; auto. auto.\nQed.\n\nInstance list_exists_dec X A (p : X -> Prop) :\n (forall x, dec (p x)) -> dec (exists x, x el A /\\ p x).\nProof.\n intros p_dec.\n destruct (find (fun x => Dec (p x)) A) eqn:Eq. (* New: eta expansion needed *)\n - apply find_some in Eq as [H0 H1 %Dec_true]. firstorder. (* New: Need firstorder here *)\n - right. intros [x [E F]]. apply find_none with (x := x) in Eq; auto. eauto. (* New: Why can't auto solve this? *)\nQed.\n\nLemma list_exists_DM X A (p : X -> Prop) : \n (forall x, dec (p x)) ->\n ~ (forall x, x el A -> ~ p x) -> exists x, x el A /\\ p x.\nProof. \n intros D E. \n destruct (find (fun x => Dec (p x)) A) eqn:Eq.\n + apply find_some in Eq as [? ?%Dec_true]. eauto.\n + exfalso. apply E. intros. apply find_none with (x := x) in Eq; eauto. \nQed.\n\nLemma list_exists_not_incl (X: eqType) (A B : list X) :\n ~ A <<= B -> exists x, x el A /\\ ~ x el B.\nProof.\n intros E.\n apply list_exists_DM; auto.\n intros F. apply E. intros x G.\n apply dec_DN; auto.\nQed.\n\nLemma list_cc X (p : X -> Prop) A : \n (forall x, dec (p x)) -> \n (exists x, x el A /\\ p x) -> {x | x el A /\\ p x}.\nProof.\n intros D E. \n destruct (cfind A p) as [[x [F G]]|F].\n - eauto.\n - exfalso. destruct E as [x [G H]]. apply (F x); auto.\nQed.\n\n\n\n(** *** Membership\n\nWe use the following lemmas from Coq's standard library List.\n- [in_eq : x el x::A]\n- [in_nil : ~ x el nil]\n- [in_cons : x el A -> x el y::A]\n- [in_or_app : x el A \\/ x el B -> x el A++B]\n- [in_app_iff : x el A++B <-> x el A \\/ x el B]\n- [in_map_iff : y el map f A <-> exists x, f x = y /\\ x el A]\n*)\n\nHint Resolve in_eq in_nil in_cons in_or_app.\n\nSection Membership.\n Variable X : Type.\n Implicit Types (x y: X) (A B: list X).\n\n Lemma in_sing x y :\n x el [y] -> x = y.\n Proof. \n cbn. intros [[]|[]]. reflexivity. \n Qed.\n\n Lemma in_cons_neq x y A :\n x el y::A -> x <> y -> x el A.\n Proof. \n cbn. intros [[]|D] E; congruence. \n Qed.\n\n Lemma not_in_cons x y A :\n ~ x el y :: A -> x <> y /\\ ~ x el A.\n Proof.\n intuition; subst; auto.\n Qed.\n\n(** *** Disjointness *)\n\n Definition disjoint A B :=\n ~ exists x, x el A /\\ x el B.\n\n Lemma disjoint_forall A B :\n disjoint A B <-> forall x, x el A -> ~ x el B.\n Proof.\n split.\n - intros D x E F. apply D. exists x. auto.\n - intros D [x [E F]]. exact (D x E F).\n Qed.\n\n Lemma disjoint_symm A B :\n disjoint A B -> disjoint B A.\n Proof.\n firstorder.\n Qed.\n\n Lemma disjoint_incl A B B' :\n B' <<= B -> disjoint A B -> disjoint A B'.\n Proof.\n firstorder.\n Qed.\n\n Lemma disjoint_nil B :\n disjoint nil B.\n Proof.\n firstorder.\n Qed.\n\n Lemma disjoint_nil' A :\n disjoint A nil.\n Proof.\n firstorder.\n Qed.\n \n Lemma disjoint_cons x A B :\n disjoint (x::A) B <-> ~ x el B /\\ disjoint A B.\n Proof.\n split.\n - intros D. split.\n + intros E. apply D. eauto.\n + intros [y [E F]]. apply D. eauto.\n - intros [D E] [y [[F|F] G]]. \n + congruence.\n + apply E. eauto.\n Qed.\n\n Lemma disjoint_app A B C :\n disjoint (A ++ B) C <-> disjoint A C /\\ disjoint B C.\n Proof.\n split.\n - intros D. split.\n + intros [x [E F]]. eauto 6.\n + intros [x [E F]]. eauto 6.\n - intros [D E] [x [F G]]. \n apply in_app_iff in F as [F|F]; eauto.\n Qed.\n\nEnd Membership.\n\nHint Resolve disjoint_nil disjoint_nil'.\n\n(** *** Inclusion\n\nWe use the following lemmas from Coq's standard library List.\n- [incl_refl : A <<= A]\n- [incl_tl : A <<= B -> A <<= x::B]\n- [incl_cons : x el B -> A <<= B -> x::A <<= B]\n- [incl_appl : A <<= B -> A <<= B++C]\n- [incl_appr : A <<= C -> A <<= B++C]\n- [incl_app : A <<= C -> B <<= C -> A++B <<= C]\n*)\n\nHint Resolve incl_refl incl_tl incl_cons incl_appl incl_appr incl_app.\n\nHint Resolve incl_nil.\n\nLemma incl_map X Y A B (f : X -> Y) :\n A <<= B -> map f A <<= map f B.\n\nProof.\n intros D y E. apply in_map_iff in E as [x [E E']].\n subst y. apply in_map_iff. eauto.\nQed.\n\nSection Inclusion.\n Variable X : Type.\n Implicit Types A B : list X.\n\n Lemma incl_nil_eq A :\n A <<= nil -> A=nil.\n\n Proof.\n intros D. destruct A as [|x A].\n - reflexivity.\n - exfalso. apply (D x). auto.\n Qed.\n\n Lemma incl_shift x A B :\n A <<= B -> x::A <<= x::B.\n\n Proof. auto. Qed.\n\n Lemma incl_lcons x A B :\n x::A <<= B <-> x el B /\\ A <<= B.\n Proof. \n split. \n - intros D. split; hnf; auto.\n - intros [D E] z [F|F]; subst; auto.\n Qed.\n\n Lemma incl_rcons x A B :\n A <<= x::B -> ~ x el A -> A <<= B.\n\n Proof. intros C D y E. destruct (C y E) as [F|F]; congruence. Qed.\n\n Lemma incl_lrcons x A B :\n x::A <<= x::B -> ~ x el A -> A <<= B.\n\n Proof.\n intros C D y E.\n assert (F: y el x::B) by auto.\n destruct F as [F|F]; congruence.\n Qed.\n\n Lemma incl_app_left A B C :\n A ++ B <<= C -> A <<= C /\\ B <<= C.\n Proof.\n firstorder.\n Qed.\n\nEnd Inclusion.\n\nDefinition inclp (X : Type) (A : list X) (p : X -> Prop) : Prop :=\n forall x, x el A -> p x.\n\n(** *** Setoid rewriting with list inclusion and list equivalence *)\n\nInstance incl_preorder X : \n PreOrder (@incl X).\nProof. \n constructor; hnf; unfold incl; auto. \nQed.\n\nInstance equi_Equivalence X : \n Equivalence (@equi X).\nProof. \n constructor; hnf; firstorder. \nQed.\n\nInstance incl_equi_proper X : \n Proper (@equi X ==> @equi X ==> iff) (@incl X).\nProof. \n hnf. intros A B D. hnf. firstorder. \nQed.\n\nInstance cons_incl_proper X x : \n Proper (@incl X ==> @incl X) (@cons X x).\nProof.\n hnf. apply incl_shift.\nQed.\n\nInstance cons_equi_proper X x : \n Proper (@equi X ==> @equi X) (@cons X x).\nProof. \n hnf. firstorder.\nQed.\n\nInstance in_incl_proper X x : \n Proper (@incl X ==> Basics.impl) (@In X x).\nProof.\n intros A B D. hnf. auto.\nQed.\n\nInstance in_equi_proper X x : \n Proper (@equi X ==> iff) (@In X x).\nProof. \n intros A B D. firstorder. \nQed.\n\nInstance app_incl_proper X : \n Proper (@incl X ==> @incl X ==> @incl X) (@app X).\nProof. \n intros A B D A' B' E. auto.\nQed.\n\nInstance app_equi_proper X : \n Proper (@equi X ==> @equi X ==> @equi X) (@app X).\nProof. \n hnf. intros A B D. hnf. intros A' B' E.\n destruct D, E; auto.\nQed.\n\nSection Equi.\n Variable X : Type.\n Implicit Types A B : list X.\n\n Lemma equi_push x A :\n x el A -> A === x::A.\n Proof.\n auto.\n Qed.\n\n Lemma equi_dup x A :\n x::A === x::x::A.\n\n Proof.\n auto.\n Qed.\n\n Lemma equi_swap x y A:\n x::y::A === y::x::A.\n Proof.\n split; intros z; cbn; tauto.\n Qed.\n\n Lemma equi_shift x A B :\n x::A++B === A++x::B.\n Proof. \n split; intros y.\n - intros [D|D].\n + subst; auto.\n + apply in_app_iff in D as [D|D]; auto.\n - intros D. apply in_app_iff in D as [D|D].\n + auto.\n + destruct D; subst; auto.\n Qed.\n\n Lemma equi_rotate x A :\n x::A === A++[x]. \n Proof. \n split; intros y; cbn.\n - intros [D|D]; subst; auto.\n - intros D. apply in_app_iff in D as [D|D].\n + auto.\n + apply in_sing in D. auto.\n Qed.\n \nEnd Equi.\n\nLemma in_concat_iff A l (a:A) : a el concat l <-> exists l', a el l' /\\ l' el l.\nProof.\n induction l; cbn.\n - intuition. now destruct H. \n - rewrite in_app_iff, IHl. firstorder subst. auto. (* TODO: find something faster than firstorder subst *)\nQed.\n\n\n\n(** *** Filter *)\n\nSection Filter.\n Variable X : Type.\n Implicit Types (x y: X) (A B C: list X) (p q: X -> bool).\n \n Fixpoint filter p A : list X :=\n match A with\n | nil => nil\n | x::A' => if p x then x :: filter p A' else filter p A'\n end.\n\n Lemma in_filter_iff x p A :\n x el filter p A <-> x el A /\\ p x.\n Proof. \n induction A as [|y A]; cbn.\n - tauto.\n - destruct (p y) eqn:E; cbn;\n rewrite IHA; intuition; subst; auto.\n Qed.\n\n Lemma filter_incl p A :\n filter p A <<= A. \n Proof.\n intros x D. apply in_filter_iff in D. apply D.\n Qed.\n\n Lemma filter_mono p A B :\n A <<= B -> filter p A <<= filter p B.\n Proof.\n intros D x E. apply in_filter_iff in E as [E E'].\n apply in_filter_iff. auto.\n Qed.\n\n Lemma filter_id p A :\n (forall x, x el A -> p x) -> filter p A = A.\n Proof.\n intros D.\n induction A as [|x A]; cbn.\n - reflexivity.\n - destruct (p x) eqn:E.\n + f_equal; auto.\n + exfalso. apply bool_Prop_false in E. auto.\n Qed.\n\n Lemma filter_app p A B :\n filter p (A ++ B) = filter p A ++ filter p B.\n Proof.\n induction A as [|y A]; cbn.\n - reflexivity.\n - rewrite IHA. destruct (p y); reflexivity. \n Qed.\n\n Lemma filter_fst p x A :\n p x -> filter p (x::A) = x::filter p A.\n Proof.\n cbn. destruct (p x); auto.\n Qed.\n\n Lemma filter_fst' p x A :\n ~ p x -> filter p (x::A) = filter p A.\n Proof.\n cbn. destruct (p x); auto.\n Qed.\n\n Lemma filter_pq_mono p q A :\n (forall x, x el A -> p x -> q x) -> filter p A <<= filter q A.\n Proof. \n intros D x E. apply in_filter_iff in E as [E E'].\n apply in_filter_iff. auto.\n Qed.\n\n Lemma filter_pq_eq p q A :\n (forall x, x el A -> p x = q x) -> filter p A = filter q A.\n Proof. \n intros C; induction A as [|x A]; cbn.\n - reflexivity.\n - destruct (p x) eqn:D, (q x) eqn:E.\n + f_equal. auto.\n + exfalso. enough (p x = q x) by congruence. auto.\n + exfalso. enough (p x = q x) by congruence. auto.\n + auto.\n Qed.\n\n Lemma filter_and p q A :\n filter p (filter q A) = filter (fun x => p x && q x) A.\n Proof.\n induction A as [|x A]; cbn. reflexivity.\n destruct (p x) eqn:E, (q x); cbn;\n try rewrite E; now rewrite IHA.\n Qed.\n\n Lemma filter_comm p q A :\n filter p (filter q A) = filter q (filter p A).\n Proof.\n rewrite !filter_and. apply filter_pq_eq.\n intros x _. now destruct (p x), (q x).\n Qed.\n \nEnd Filter.\n\n\n(** *** Element removal *)\n\nSection Removal.\n Variable X : eqType.\n Implicit Types (x y: X) (A B: list X).\n\n Definition rem A x : list X :=\n filter (fun z => Dec (z <> x)) A.\n\n Lemma in_rem_iff x A y :\n x el rem A y <-> x el A /\\ x <> y.\n Proof.\n unfold rem. rewrite in_filter_iff, Dec_reflect. tauto.\n Qed.\n\n Lemma rem_not_in x y A :\n x = y \\/ ~ x el A -> ~ x el rem A y.\n Proof.\n unfold rem. rewrite in_filter_iff, Dec_reflect. tauto.\n Qed.\n\n Lemma rem_incl A x :\n rem A x <<= A.\n Proof.\n apply filter_incl.\n Qed.\n\n Lemma rem_mono A B x :\n A <<= B -> rem A x <<= rem B x.\n Proof.\n apply filter_mono.\n Qed.\n\n Lemma rem_cons A B x :\n A <<= B -> rem (x::A) x <<= B.\n Proof.\n intros E y F. apply E. apply in_rem_iff in F.\n destruct F as [[|]]; congruence.\n Qed.\n\n Lemma rem_cons' A B x y :\n x el B -> rem A y <<= B -> rem (x::A) y <<= B.\n Proof.\n intros E F u G. \n apply in_rem_iff in G as [[[]|G] H]. exact E.\n apply F. apply in_rem_iff. auto.\n Qed.\n\n Lemma rem_in x y A :\n x el rem A y -> x el A.\n Proof.\n apply rem_incl.\n Qed.\n\n Lemma rem_neq x y A :\n x <> y -> x el A -> x el rem A y.\n Proof.\n intros E F. apply in_rem_iff. auto.\n Qed.\n\n Lemma rem_app x A B :\n x el A -> B <<= A ++ rem B x.\n Proof.\n intros E y F. decide (x=y) as [[]|]; auto using rem_neq.\n Qed.\n\n Lemma rem_app' x A B C :\n rem A x <<= C -> rem B x <<= C -> rem (A ++ B) x <<= C.\n Proof.\n unfold rem; rewrite filter_app; auto.\n Qed.\n\n Lemma rem_equi x A :\n x::A === x::rem A x.\n Proof.\n split; intros y; \n intros [[]|E]; decide (x=y) as [[]|D]; \n eauto using rem_in, rem_neq. \n Qed.\n\n Lemma rem_comm A x y :\n rem (rem A x) y = rem (rem A y) x.\n Proof.\n apply filter_comm.\n Qed.\n\n Lemma rem_fst x A :\n rem (x::A) x = rem A x.\n Proof.\n unfold rem. rewrite filter_fst'; auto.\n Qed.\n\n Lemma rem_fst' x y A :\n x <> y -> rem (x::A) y = x::rem A y.\n Proof.\n intros E. unfold rem. rewrite filter_fst; auto.\n Qed.\n\n Lemma rem_id x A :\n ~ x el A -> rem A x = A.\n Proof.\n intros D. apply filter_id. intros y E.\n apply Dec_reflect. congruence.\n Qed.\n\n Lemma rem_reorder x A :\n x el A -> A === x :: rem A x.\n Proof.\n intros D. rewrite <- rem_equi. apply equi_push, D.\n Qed.\n\n Lemma rem_inclr A B x :\n A <<= B -> ~ x el A -> A <<= rem B x.\n Proof.\n intros D E y F. apply in_rem_iff.\n intuition; subst; auto. \n Qed.\n\nEnd Removal.\n\nHint Resolve rem_not_in rem_incl rem_mono rem_cons rem_cons' rem_app rem_app' rem_in rem_neq rem_inclr.\n\n\nNotation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n\nNotation \"[ s | p ∈ A ',' P ]\" :=\n (map (fun p => s) (filter (fun p => Dec P) A)) (p pattern).\nNotation \"[ s | p ∈ A ]\" :=\n (map (fun p => s) A) (p pattern).\n\nLtac in_app n :=\n (match goal with\n | [ |- _ el _ ++ _ ] => \n match n with\n | 0 => idtac\n | 1 => eapply in_app_iff; left\n | S ?n => eapply in_app_iff; right; in_app n\n end\n | [ |- _ el _ :: _ ] => match n with 0 => idtac | 1 => left | S ?n => right; in_app n end\n end) || (repeat (try right; eapply in_app_iff; right)).\n\nLemma to_dec (P : Prop) `{dec P} : P <-> Dec P.\nProof.\n firstorder. destruct (Dec P); cbn in *; firstorder.\nQed.\n\nLtac in_collect a :=\n eapply in_map_iff; exists a; split; [ eauto | match goal with [ |- _ el filter _ _ ] => eapply in_filter_iff; split; [ try (rewrite !in_prod_iff; repeat split) | rewrite <- to_dec; repeat split; eauto ] | _ => try (rewrite !in_prod_iff; repeat split) end ].\nLtac inv_collect :=\n repeat\n (match goal with\n | [ H : ?x el concat _ |- _ ] => eapply in_concat_iff in H as (? & ? & ?)\n | [ H : ?x el map _ _ |- _ ] => let x := fresh \"x\" in eapply in_map_iff in H as (x & ? & ?)\n | [ x : ?A * ?B |- _ ] => destruct x; subst\n | [ H : ?x el filter _ _ |- _ ] => let H' := fresh \"H\" in eapply in_filter_iff in H as (? & H' % to_dec)\n | [ H : ?x el list_prod _ _ |- _ ] => eapply in_prod_iff in H\n | [ H : _ el _ ++ _ |- _ ] => try eapply in_app_iff in H as []\n | [H : _ el _ :: _ |- _ ] => destruct H\n end; intuition; subst).\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/FOL/Prelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367020358429, "lm_q2_score": 0.16238004274695514, "lm_q1q2_score": 0.07422987721778226}} {"text": "(** * Imp: Simple Imperative Programs *)\n\n(** In this chapter, we begin a new direction that will continue for\n the rest of the course. Up to now most of our attention has been\n focused on various aspects of Coq itself, while from now on we'll\n mostly be using Coq to formalize other things. (We'll continue to\n pause from time to time to introduce a few additional aspects of\n Coq.)\n\n Our first case study is a _simple imperative programming language_\n called Imp, embodying a tiny core fragment of conventional\n mainstream languages such as C and Java. Here is a familiar\n mathematical function written in Imp.\n\n Z ::= X;;\n Y ::= 1;;\n WHILE not (Z = 0) DO\n Y ::= Y * Z;;\n Z ::= Z - 1\n END\n*)\n\n(** This chapter looks at how to define the _syntax_ and _semantics_\n of Imp; the chapters that follow develop a theory of _program\n equivalence_ and introduce _Hoare Logic_, a widely used logic for\n reasoning about imperative programs. *)\n\n(* ####################################################### *)\n(** *** Sflib *)\n\n(** A minor technical point: Instead of asking Coq to import our\n earlier definitions from chapter [Logic], we import a small library\n called [Sflib.v], containing just a few definitions and theorems\n from earlier chapters that we'll actually use in the rest of the\n course. This change should be nearly invisible, since most of what's\n missing from Sflib has identical definitions in the Coq standard\n library. The main reason for doing it is to tidy the global Coq\n environment so that, for example, it is easier to search for\n relevant theorems. *)\n\n(** * SfLib: Software Foundations Library *)\n\n(** Here we collect together several useful definitions and theorems\n from Basics.v, List.v, Poly.v, Ind.v, and Logic.v that are not\n already in the Coq standard library. From now on we can [Import]\n or [Export] this file, instead of cluttering our environment with\n all the examples and false starts in those files. *)\n\n(** * From the Coq Standard Library *)\n\nRequire Omega. (* needed for using the [omega] tactic *)\nRequire Export Bool.\nRequire Export List.\nExport ListNotations.\nRequire Export Arith.\nRequire Export Arith.EqNat. (* Contains [beq_nat], among other things *)\n\n(** * From Basics.v *)\n\nDefinition admit {T: Type} : T. Admitted.\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\nFixpoint ble_nat (n m : nat) : bool :=\n match n with\n | O => true\n | S n' =>\n match m with\n | O => false\n | S m' => ble_nat n' m'\n end\n end.\n\nTheorem andb_true_elim1 : forall b c,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\".\n reflexivity.\n Case \"b = false\".\n rewrite <- H. reflexivity. Qed.\n\nTheorem andb_true_elim2 : forall b c,\n andb b c = true -> c = true.\nProof.\n(* An exercise in Basics.v *)\nAdmitted.\n\nTheorem beq_nat_sym : forall (n m : nat),\n beq_nat n m = beq_nat m n.\n(* An exercise in Lists.v *)\nAdmitted.\n\n(** * From Props.v *)\n\nInductive ev : nat -> Prop :=\n | ev_0 : ev O\n | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** * From Logic.v *)\n\nTheorem andb_true : forall b c,\n andb b c = true -> b = true /\\ c = true.\nProof.\n intros b c H.\n destruct b.\n destruct c.\n apply conj. reflexivity. reflexivity.\n inversion H.\n inversion H. Qed.\n\nTheorem false_beq_nat: forall n n' : nat,\n n <> n' ->\n beq_nat n n' = false.\nProof. \n(* An exercise in Logic.v *)\nAdmitted.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n False -> P.\nProof.\n intros P contra.\n inversion contra. Qed.\n\nTheorem ev_not_ev_S : forall n,\n ev n -> ~ ev (S n).\nProof. \n(* An exercise in Logic.v *)\nAdmitted.\n\nTheorem ble_nat_true : forall n m,\n ble_nat n m = true -> n <= m.\n(* An exercise in Logic.v *)\nAdmitted.\n\nTheorem ble_nat_false : forall n m,\n ble_nat n m = false -> ~(n <= m).\n(* An exercise in Logic.v *)\nAdmitted.\n\nInductive appears_in (n : nat) : list nat -> Prop :=\n| ai_here : forall l, appears_in n (n::l)\n| ai_later : forall m l, appears_in n l -> appears_in n (m::l).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n | nn : next_nat n (S n).\n\nInductive total_relation : nat -> nat -> Prop :=\n tot : forall n m : nat, total_relation n m.\n\nInductive empty_relation : nat -> nat -> Prop := .\n\n(** * From Later Files *)\n\nDefinition relation (X:Type) := X -> X -> Prop.\n\nDefinition deterministic {X: Type} (R: relation X) :=\n forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2. \n\nInductive multi (X:Type) (R: relation X) \n : X -> X -> Prop :=\n | multi_refl : forall (x : X),\n multi X R x x\n | multi_step : forall (x y z : X),\n R x y ->\n multi X R y z ->\n multi X R x z.\nImplicit Arguments multi [[X]]. \n\nTactic Notation \"multi_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"multi_refl\" | Case_aux c \"multi_step\" ].\n\nTheorem multi_R : forall (X:Type) (R:relation X) (x y : X),\n R x y -> multi R x y.\nProof.\n intros X R x y r.\n apply multi_step with y. apply r. apply multi_refl. Qed.\n\nTheorem multi_trans :\n forall (X:Type) (R: relation X) (x y z : X),\n multi R x y ->\n multi R y z ->\n multi R x z.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** Identifiers and polymorphic partial maps. *)\n\nInductive id : Type := \n Id : nat -> id.\n\nTheorem eq_id_dec : forall id1 id2 : id, {id1 = id2} + {id1 <> id2}.\nProof.\n intros id1 id2.\n destruct id1 as [n1]. destruct id2 as [n2].\n destruct (eq_nat_dec n1 n2) as [Heq | Hneq].\n Case \"n1 = n2\".\n left. rewrite Heq. reflexivity.\n Case \"n1 <> n2\".\n right. intros contra. inversion contra. apply Hneq. apply H0.\nDefined. \n\nLemma eq_id : forall (T:Type) x (p q:T), \n (if eq_id_dec x x then p else q) = p. \nProof.\n intros. \n destruct (eq_id_dec x x); try reflexivity. \n apply ex_falso_quodlibet; auto.\nQed.\n\nLemma neq_id : forall (T:Type) x y (p q:T), x <> y -> \n (if eq_id_dec x y then p else q) = q. \nProof.\n (* FILL IN HERE *) Admitted.\n\nDefinition partial_map (A:Type) := id -> option A.\n\nDefinition empty {A:Type} : partial_map A := (fun _ => None). \n\nNotation \"'\\empty'\" := empty.\n\nDefinition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=\n fun x' => if eq_id_dec x x' then Some T else Gamma x'.\n\nLemma extend_eq : forall A (ctxt: partial_map A) x T,\n (extend ctxt x T) x = Some T.\nProof.\n intros. unfold extend. rewrite eq_id; auto. \nQed.\n\nLemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,\n x2 <> x1 ->\n (extend ctxt x2 T) x1 = ctxt x1.\nProof.\n intros. unfold extend. rewrite neq_id; auto. \nQed.\n\nLemma extend_shadow : forall A (ctxt: partial_map A) t1 t2 x1 x2,\n extend (extend ctxt x2 t1) x2 t2 x1 = extend ctxt x2 t2 x1.\nProof with auto.\n intros. unfold extend. destruct (eq_id_dec x2 x1)...\nQed.\n\n(** -------------------- *)\n\n(** * Some useful tactics *)\n\nTactic Notation \"solve_by_inversion_step\" tactic(t) := \n match goal with \n | H : _ |- _ => solve [ inversion H; subst; t ] \n end\n || fail \"because the goal is not solvable by inversion.\".\n\nTactic Notation \"solve\" \"by\" \"inversion\" \"1\" :=\n solve_by_inversion_step idtac.\nTactic Notation \"solve\" \"by\" \"inversion\" \"2\" :=\n solve_by_inversion_step (solve by inversion 1).\nTactic Notation \"solve\" \"by\" \"inversion\" \"3\" :=\n solve_by_inversion_step (solve by inversion 2).\nTactic Notation \"solve\" \"by\" \"inversion\" :=\n solve by inversion 1.\n\n\n(*Require Export SfLib.*)\n\n(* ####################################################### *)\n(** * Arithmetic and Boolean Expressions *)\n\n(** We'll present Imp in three parts: first a core language of\n _arithmetic and boolean expressions_, then an extension of these\n expressions with _variables_, and finally a language of _commands_\n including assignment, conditions, sequencing, and loops. *)\n\n(* ####################################################### *)\n(** ** Syntax *)\n\nModule AExp.\n\n(** These two definitions specify the _abstract syntax_ of\n arithmetic and boolean expressions. *)\n\nInductive aexp : Type :=\n | ANum : nat -> aexp\n | APlus : aexp -> aexp -> aexp\n | AMinus : aexp -> aexp -> aexp\n | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n | BTrue : bexp\n | BFalse : bexp\n | BEq : aexp -> aexp -> bexp\n | BLe : aexp -> aexp -> bexp\n | BNot : bexp -> bexp\n | BAnd : bexp -> bexp -> bexp.\n\n(** In this chapter, we'll elide the translation from the\n concrete syntax that a programmer would actually write to these\n abstract syntax trees -- the process that, for example, would\n translate the string [\"1+2*3\"] to the AST [APlus (ANum\n 1) (AMult (ANum 2) (ANum 3))]. The optional chapter [ImpParser]\n develops a simple implementation of a lexical analyzer and parser\n that can perform this translation. You do _not_ need to\n understand that file to understand this one, but if you haven't\n taken a course where these techniques are covered (e.g., a\n compilers course) you may want to skim it. *)\n\n(** *** *)\n(** For comparison, here's a conventional BNF (Backus-Naur Form)\n grammar defining the same abstract syntax:\n a ::= nat\n | a + a\n | a - a\n | a * a\n\n b ::= true\n | false\n | a = a\n | a <= a\n | not b\n | b and b\n*)\n\n(** Compared to the Coq version above...\n\n - The BNF is more informal -- for example, it gives some\n suggestions about the surface syntax of expressions (like the\n fact that the addition operation is written [+] and is an\n infix symbol) while leaving other aspects of lexical analysis\n and parsing (like the relative precedence of [+], [-], and\n [*]) unspecified. Some additional information -- and human\n intelligence -- would be required to turn this description\n into a formal definition (when implementing a compiler, for\n example).\n\n The Coq version consistently omits all this information and\n concentrates on the abstract syntax only.\n\n - On the other hand, the BNF version is lighter and\n easier to read. Its informality makes it flexible, which is\n a huge advantage in situations like discussions at the\n blackboard, where conveying general ideas is more important\n than getting every detail nailed down precisely.\n\n Indeed, there are dozens of BNF-like notations and people\n switch freely among them, usually without bothering to say which\n form of BNF they're using because there is no need to: a\n rough-and-ready informal understanding is all that's\n needed. *)\n\n(** It's good to be comfortable with both sorts of notations:\n informal ones for communicating between humans and formal ones for\n carrying out implementations and proofs. *)\n\n(* ####################################################### *)\n(** ** Evaluation *)\n\n(** _Evaluating_ an arithmetic expression produces a number. *)\n\nFixpoint aeval (a : aexp) : nat :=\n match a with\n | ANum n => n\n | APlus a1 a2 => (aeval a1) + (aeval a2)\n | AMinus a1 a2 => (aeval a1) - (aeval a2)\n | AMult a1 a2 => (aeval a1) * (aeval a2)\n end.\n\nExample test_aeval1:\n aeval (APlus (ANum 2) (ANum 2)) = 4.\nProof. reflexivity. Qed.\n\n(** *** *)\n(** Similarly, evaluating a boolean expression yields a boolean. *)\n\nFixpoint beval (b : bexp) : bool :=\n match b with\n | BTrue => true\n | BFalse => false\n | BEq a1 a2 => beq_nat (aeval a1) (aeval a2)\n | BLe a1 a2 => ble_nat (aeval a1) (aeval a2)\n | BNot b1 => negb (beval b1)\n | BAnd b1 b2 => andb (beval b1) (beval b2)\n end.\n\n(* ####################################################### *)\n(** ** Optimization *)\n\n(** We haven't defined very much yet, but we can already get\n some mileage out of the definitions. Suppose we define a function\n that takes an arithmetic expression and slightly simplifies it,\n changing every occurrence of [0+e] (i.e., [(APlus (ANum 0) e])\n into just [e]. *)\n\nFixpoint optimize_0plus (a:aexp) : aexp :=\n match a with\n | ANum n =>\n ANum n\n | APlus (ANum 0) e2 =>\n optimize_0plus e2\n | APlus e1 e2 =>\n APlus (optimize_0plus e1) (optimize_0plus e2)\n | AMinus e1 e2 =>\n AMinus (optimize_0plus e1) (optimize_0plus e2)\n | AMult e1 e2 =>\n AMult (optimize_0plus e1) (optimize_0plus e2)\n end.\n\n(** To make sure our optimization is doing the right thing we\n can test it on some examples and see if the output looks OK. *)\n\nExample test_optimize_0plus:\n optimize_0plus (APlus (ANum 2)\n (APlus (ANum 0)\n (APlus (ANum 0) (ANum 1))))\n = APlus (ANum 2) (ANum 1).\nProof. reflexivity. Qed.\n\n(** But if we want to be sure the optimization is correct --\n i.e., that evaluating an optimized expression gives the same\n result as the original -- we should prove it. *)\n\nTheorem optimize_0plus_sound: forall a,\n aeval (optimize_0plus a) = aeval a.\nProof.\n intros a. induction a.\n Case \"ANum\". reflexivity.\n Case \"APlus\". destruct a1.\n SCase \"a1 = ANum n\". destruct n.\n SSCase \"n = 0\". simpl. apply IHa2.\n SSCase \"n ≠ 0\". simpl. rewrite IHa2. reflexivity.\n SCase \"a1 = APlus a1_1 a1_2\".\n simpl. simpl in IHa1. rewrite IHa1.\n rewrite IHa2. reflexivity.\n SCase \"a1 = AMinus a1_1 a1_2\".\n simpl. simpl in IHa1. rewrite IHa1.\n rewrite IHa2. reflexivity.\n SCase \"a1 = AMult a1_1 a1_2\".\n simpl. simpl in IHa1. rewrite IHa1.\n rewrite IHa2. reflexivity.\n Case \"AMinus\".\n simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n Case \"AMult\".\n simpl. rewrite IHa1. rewrite IHa2. reflexivity. Qed.\n\n\n(* ####################################################### *)\n(** * Coq Automation *)\n\n(** The repetition in this last proof is starting to be a little\n annoying. If either the language of arithmetic expressions or the\n optimization being proved sound were significantly more complex,\n it would begin to be a real problem.\n\n So far, we've been doing all our proofs using just a small handful\n of Coq's tactics and completely ignoring its powerful facilities\n for constructing parts of proofs automatically. This section\n introduces some of these facilities, and we will see more over the\n next several chapters. Getting used to them will take some\n energy -- Coq's automation is a power tool -- but it will allow us\n to scale up our efforts to more complex definitions and more\n interesting properties without becoming overwhelmed by boring,\n repetitive, low-level details. *)\n\n(* ####################################################### *)\n(** ** Tacticals *)\n\n(** _Tacticals_ is Coq's term for tactics that take other tactics as\n arguments -- \"higher-order tactics,\" if you will. *)\n\n(* ####################################################### *)\n(** *** The [repeat] Tactical *)\n\n(** The [repeat] tactical takes another tactic and keeps applying\n this tactic until the tactic fails. Here is an example showing\n that [100] is even using repeat. *)\n\nTheorem ev100 : ev 100.\nProof.\n repeat (apply ev_SS). (* applies ev_SS 50 times,\n until [apply ev_SS] fails *)\n apply ev_0.\nQed.\n(* Print ev100. *)\n\n(** The [repeat T] tactic never fails; if the tactic [T] doesn't apply\n to the original goal, then repeat still succeeds without changing\n the original goal (it repeats zero times). *)\n\nTheorem ev100' : ev 100.\nProof.\n repeat (apply ev_0). (* doesn't fail, applies ev_0 zero times *)\n repeat (apply ev_SS). apply ev_0. (* we can continue the proof *)\nQed.\n\n(** The [repeat T] tactic does not have any bound on the number of\n times it applies [T]. If [T] is a tactic that always succeeds then\n repeat [T] will loop forever (e.g. [repeat simpl] loops forever\n since [simpl] always succeeds). While Coq's term language is\n guaranteed to terminate, Coq's tactic language is not! *)\n\n(* ####################################################### *)\n(** *** The [try] Tactical *)\n\n(** If [T] is a tactic, then [try T] is a tactic that is just like [T]\n except that, if [T] fails, [try T] _successfully_ does nothing at\n all (instead of failing). *)\n\nTheorem silly1 : forall ae, aeval ae = aeval ae.\nProof. try reflexivity. (* this just does [reflexivity] *) Qed.\n\nTheorem silly2 : forall (P : Prop), P -> P.\nProof.\n intros P HP.\n try reflexivity. (* just [reflexivity] would have failed *)\n apply HP. (* we can still finish the proof in some other way *)\nQed.\n\n(** Using [try] in a completely manual proof is a bit silly, but\n we'll see below that [try] is very useful for doing automated\n proofs in conjunction with the [;] tactical. *)\n\n(* ####################################################### *)\n(** *** The [;] Tactical (Simple Form) *)\n\n(** In its most commonly used form, the [;] tactical takes two tactics\n as argument: [T;T'] first performs the tactic [T] and then\n performs the tactic [T'] on _each subgoal_ generated by [T]. *)\n\n(** For example, consider the following trivial lemma: *)\n\nLemma foo : forall n, ble_nat 0 n = true.\nProof.\n intros.\n destruct n.\n (* Leaves two subgoals, which are discharged identically... *)\n Case \"n=0\". simpl. reflexivity.\n Case \"n=Sn'\". simpl. reflexivity.\nQed.\n\n(** We can simplify this proof using the [;] tactical: *)\n\nLemma foo' : forall n, ble_nat 0 n = true.\nProof.\n intros.\n destruct n; (* [destruct] the current goal *)\n simpl; (* then [simpl] each resulting subgoal *)\n reflexivity. (* and do [reflexivity] on each resulting subgoal *)\nQed.\n\n(** Using [try] and [;] together, we can get rid of the repetition in\n the proof that was bothering us a little while ago. *)\n\nTheorem optimize_0plus_sound': forall a,\n aeval (optimize_0plus a) = aeval a.\nProof.\n intros a.\n induction a;\n (* Most cases follow directly by the IH *)\n try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n (* The remaining cases -- ANum and APlus -- are different *)\n Case \"ANum\". reflexivity.\n Case \"APlus\".\n destruct a1;\n (* Again, most cases follow directly by the IH *)\n try (simpl; simpl in IHa1; rewrite IHa1;\n rewrite IHa2; reflexivity).\n (* The interesting case, on which the [try...] does nothing,\n is when [e1 = ANum n]. In this case, we have to destruct\n [n] (to see whether the optimization applies) and rewrite\n with the induction hypothesis. *)\n SCase \"a1 = ANum n\". destruct n;\n simpl; rewrite IHa2; reflexivity. Qed.\n\n(** Coq experts often use this \"[...; try... ]\" idiom after a tactic\n like [induction] to take care of many similar cases all at once.\n Naturally, this practice has an analog in informal proofs.\n\n Here is an informal proof of this theorem that matches the\n structure of the formal one:\n\n _Theorem_: For all arithmetic expressions [a],\n aeval (optimize_0plus a) = aeval a.\n _Proof_: By induction on [a]. The [AMinus] and [AMult] cases\n follow directly from the IH. The remaining cases are as follows:\n\n - Suppose [a = ANum n] for some [n]. We must show\n aeval (optimize_0plus (ANum n)) = aeval (ANum n).\n This is immediate from the definition of [optimize_0plus].\n\n - Suppose [a = APlus a1 a2] for some [a1] and [a2]. We\n must show\n aeval (optimize_0plus (APlus a1 a2))\n = aeval (APlus a1 a2).\n Consider the possible forms of [a1]. For most of them,\n [optimize_0plus] simply calls itself recursively for the\n subexpressions and rebuilds a new expression of the same form\n as [a1]; in these cases, the result follows directly from the\n IH.\n\n The interesting case is when [a1 = ANum n] for some [n].\n If [n = ANum 0], then\n optimize_0plus (APlus a1 a2) = optimize_0plus a2\n and the IH for [a2] is exactly what we need. On the other\n hand, if [n = S n'] for some [n'], then again [optimize_0plus]\n simply calls itself recursively, and the result follows from\n the IH. [] *)\n\n(** This proof can still be improved: the first case (for [a = ANum\n n]) is very trivial -- even more trivial than the cases that we\n said simply followed from the IH -- yet we have chosen to write it\n out in full. It would be better and clearer to drop it and just\n say, at the top, \"Most cases are either immediate or direct from\n the IH. The only interesting case is the one for [APlus]...\" We\n can make the same improvement in our formal proof too. Here's how\n it looks: *)\n\nTheorem optimize_0plus_sound'': forall a,\n aeval (optimize_0plus a) = aeval a.\nProof.\n intros a.\n induction a;\n (* Most cases follow directly by the IH *)\n try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n (* ... or are immediate by definition *)\n try reflexivity.\n (* The interesting case is when a = APlus a1 a2. *)\n Case \"APlus\".\n destruct a1; try (simpl; simpl in IHa1; rewrite IHa1;\n rewrite IHa2; reflexivity).\n SCase \"a1 = ANum n\". destruct n;\n simpl; rewrite IHa2; reflexivity. Qed.\n\n(* ####################################################### *)\n(** *** The [;] Tactical (General Form) *)\n\n(** The [;] tactical has a more general than the simple [T;T'] we've\n seen above, which is sometimes also useful. If [T], [T1], ...,\n [Tn] are tactics, then\n T; [T1 | T2 | ... | Tn]\n is a tactic that first performs [T] and then performs [T1] on the\n first subgoal generated by [T], performs [T2] on the second\n subgoal, etc.\n\n So [T;T'] is just special notation for the case when all of the\n [Ti]'s are the same tactic; i.e. [T;T'] is just a shorthand for:\n T; [T' | T' | ... | T']\n*)\n\n(* ####################################################### *)\n(** ** Defining New Tactic Notations *)\n\n(** Coq also provides several ways of \"programming\" tactic scripts.\n\n - The [Tactic Notation] idiom illustrated below gives a handy\n way to define \"shorthand tactics\" that bundle several tactics\n into a single command.\n\n - For more sophisticated programming, Coq offers a small\n built-in programming language called [Ltac] with primitives\n that can examine and modify the proof state. The details are\n a bit too complicated to get into here (and it is generally\n agreed that [Ltac] is not the most beautiful part of Coq's\n design!), but they can be found in the reference manual, and\n there are many examples of [Ltac] definitions in the Coq\n standard library that you can use as examples.\n\n - There is also an OCaml API, which can be used to build tactics\n that access Coq's internal structures at a lower level, but\n this is seldom worth the trouble for ordinary Coq users.\n\nThe [Tactic Notation] mechanism is the easiest to come to grips with,\nand it offers plenty of power for many purposes. Here's an example.\n*)\n\nTactic Notation \"simpl_and_try\" tactic(c) :=\n simpl;\n try c.\n\n(** This defines a new tactical called [simpl_and_try] which\n takes one tactic [c] as an argument, and is defined to be\n equivalent to the tactic [simpl; try c]. For example, writing\n \"[simpl_and_try reflexivity.]\" in a proof would be the same as\n writing \"[simpl; try reflexivity.]\" *)\n\n(** The next subsection gives a more sophisticated use of this\n feature... *)\n\n(* ####################################################### *)\n(** *** Bulletproofing Case Analyses *)\n\n(** Being able to deal with most of the cases of an [induction]\n or [destruct] all at the same time is very convenient, but it can\n also be a little confusing. One problem that often comes up is\n that _maintaining_ proofs written in this style can be difficult.\n For example, suppose that, later, we extended the definition of\n [aexp] with another constructor that also required a special\n argument. The above proof might break because Coq generated the\n subgoals for this constructor before the one for [APlus], so that,\n at the point when we start working on the [APlus] case, Coq is\n actually expecting the argument for a completely different\n constructor. What we'd like is to get a sensible error message\n saying \"I was expecting the [AFoo] case at this point, but the\n proof script is talking about [APlus].\" Here's a nice trick (due\n to Aaron Bohannon) that smoothly achieves this. *)\n\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"ANum\" | Case_aux c \"APlus\"\n | Case_aux c \"AMinus\" | Case_aux c \"AMult\" ].\n\n(** ([Case_aux] implements the common functionality of [Case],\n [SCase], [SSCase], etc. For example, [Case \"foo\"] is defined as\n [Case_aux Case \"foo\".) *)\n\n(** For example, if [a] is a variable of type [aexp], then doing\n aexp_cases (induction a) Case\n will perform an induction on [a] (the same as if we had just typed\n [induction a]) and _also_ add a [Case] tag to each subgoal\n generated by the [induction], labeling which constructor it comes\n from. For example, here is yet another proof of\n [optimize_0plus_sound], using [aexp_cases]: *)\n\nTheorem optimize_0plus_sound''': forall a,\n aeval (optimize_0plus a) = aeval a.\nProof.\n intros a.\n aexp_cases (induction a) Case;\n try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n try reflexivity.\n (* At this point, there is already an [\"APlus\"] case name\n in the context. The [Case \"APlus\"] here in the proof\n text has the effect of a sanity check: if the \"Case\"\n string in the context is anything _other_ than [\"APlus\"]\n (for example, because we added a clause to the definition\n of [aexp] and forgot to change the proof) we'll get a\n helpful error at this point telling us that this is now\n the wrong case. *)\n Case \"APlus\".\n aexp_cases (destruct a1) SCase;\n try (simpl; simpl in IHa1;\n rewrite IHa1; rewrite IHa2; reflexivity).\n SCase \"ANum\". destruct n;\n simpl; rewrite IHa2; reflexivity. Qed.\n\n(** **** Exercise: 3 stars (optimize_0plus_b) *)\n(** Since the [optimize_0plus] tranformation doesn't change the value\n of [aexp]s, we should be able to apply it to all the [aexp]s that\n appear in a [bexp] without changing the [bexp]'s value. Write a\n function which performs that transformation on [bexp]s, and prove\n it is sound. Use the tacticals we've just seen to make the proof\n as elegant as possible. *)\n\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\n match b with\n | BTrue => BTrue\n | BFalse => BFalse\n | BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)\n | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n | BNot b1 => BNot b1\n | BAnd b1 b2 => BAnd b1 b2\n end.\n\n\nTheorem optimize_0plus_b_sound : forall b,\n beval (optimize_0plus_b b) = beval b.\nProof.\n intros. induction b.\n Case \"BTrue\". reflexivity.\n Case \"BFalse\". reflexivity.\n Case \"BEq\". simpl. rewrite optimize_0plus_sound. rewrite optimize_0plus_sound. reflexivity.\n Case \"BLe\". simpl. rewrite optimize_0plus_sound. rewrite optimize_0plus_sound. reflexivity.\n Case \"BNot\". simpl. reflexivity.\n Case \"BAnd\". simpl. reflexivity.\nQed.\n\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\"\n | Case_aux c \"BEq\" | Case_aux c \"BLe\" \n | Case_aux c \"BNot\" | Case_aux c \"BAnd\"].\n\nTheorem optimize_0plus_b_sound' : forall b,\n beval (optimize_0plus_b b) = beval b.\nProof.\n intros. induction b; \n try(reflexivity);\n try(simpl; repeat (rewrite optimize_0plus_sound); reflexivity).\nQed.\n \n(** [] *)\n\n(** **** Exercise: 4 stars, optional (optimizer) *)\n(** _Design exercise_: The optimization implemented by our\n [optimize_0plus] function is only one of many imaginable\n optimizations on arithmetic and boolean expressions. Write a more\n sophisticated optimizer and prove it correct.\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ####################################################### *)\n(** ** The [omega] Tactic *)\n\n(** The [omega] tactic implements a decision procedure for a subset of\n first-order logic called _Presburger arithmetic_. It is based on\n the Omega algorithm invented in 1992 by William Pugh.\n\n If the goal is a universally quantified formula made out of\n\n - numeric constants, addition ([+] and [S]), subtraction ([-]\n and [pred]), and multiplication by constants (this is what\n makes it Presburger arithmetic),\n\n - equality ([=] and [<>]) and inequality ([<=]), and\n\n - the logical connectives [/\\], [\\/], [~], and [->],\n\n then invoking [omega] will either solve the goal or tell you that\n it is actually false. *)\n\nExample silly_presburger_example : forall m n o p,\n m + n <= n + o /\\ o + 3 = p + 3 ->\n m <= p.\nProof.\n intros. omega.\nQed.\n\n(** Leibniz wrote, \"It is unworthy of excellent men to lose\n hours like slaves in the labor of calculation which could be\n relegated to anyone else if machines were used.\" We recommend\n using the omega tactic whenever possible. *)\n\n(* ####################################################### *)\n(** ** A Few More Handy Tactics *)\n\n(** Finally, here are some miscellaneous tactics that you may find\n convenient.\n\n - [clear H]: Delete hypothesis [H] from the context.\n\n - [subst x]: Find an assumption [x = e] or [e = x] in the\n context, replace [x] with [e] throughout the context and\n current goal, and clear the assumption.\n\n - [subst]: Substitute away _all_ assumptions of the form [x = e]\n or [e = x].\n\n - [rename... into...]: Change the name of a hypothesis in the\n proof context. For example, if the context includes a variable\n named [x], then [rename x into y] will change all occurrences\n of [x] to [y].\n\n - [assumption]: Try to find a hypothesis [H] in the context that\n exactly matches the goal; if one is found, behave just like\n [apply H].\n\n - [contradiction]: Try to find a hypothesis [H] in the current\n context that is logically equivalent to [False]. If one is\n found, solve the goal.\n\n - [constructor]: Try to find a constructor [c] (from some\n [Inductive] definition in the current environment) that can be\n applied to solve the current goal. If one is found, behave\n like [apply c]. *)\n\n(** We'll see many examples of these in the proofs below. *)\n\n(* ####################################################### *)\n(** * Evaluation as a Relation *)\n\n(** We have presented [aeval] and [beval] as functions defined by\n [Fixpoints]. Another way to think about evaluation -- one that we\n will see is often more flexible -- is as a _relation_ between\n expressions and their values. This leads naturally to [Inductive]\n definitions like the following one for arithmetic\n expressions... *)\n\nModule aevalR_first_try.\n\nInductive aevalR : aexp -> nat -> Prop :=\n | E_ANum : forall (n: nat),\n aevalR (ANum n) n\n | E_APlus : forall (e1 e2: aexp) (n1 n2: nat),\n aevalR e1 n1 ->\n aevalR e2 n2 ->\n aevalR (APlus e1 e2) (n1 + n2)\n | E_AMinus: forall (e1 e2: aexp) (n1 n2: nat),\n aevalR e1 n1 ->\n aevalR e2 n2 ->\n aevalR (AMinus e1 e2) (n1 - n2)\n | E_AMult : forall (e1 e2: aexp) (n1 n2: nat),\n aevalR e1 n1 ->\n aevalR e2 n2 ->\n aevalR (AMult e1 e2) (n1 * n2).\n\n(** As is often the case with relations, we'll find it\n convenient to define infix notation for [aevalR]. We'll write [e\n || n] to mean that arithmetic expression [e] evaluates to value\n [n]. (This notation is one place where the limitation to ASCII\n symbols becomes a little bothersome. The standard notation for\n the evaluation relation is a double down-arrow. We'll typeset it\n like this in the HTML version of the notes and use a double\n vertical bar as the closest approximation in [.v] files.) *)\n\nNotation \"e '||' n\" := (aevalR e n) : type_scope.\n\nEnd aevalR_first_try.\n\n(** In fact, Coq provides a way to use this notation in the definition\n of [aevalR] itself. This avoids situations where we're working on\n a proof involving statements in the form [e || n] but we have to\n refer back to a definition written using the form [aevalR e n].\n\n We do this by first \"reserving\" the notation, then giving the\n definition together with a declaration of what the notation\n means. *)\n\nReserved Notation \"e '||' n\" (at level 50, left associativity).\n\nInductive aevalR : aexp -> nat -> Prop :=\n | E_ANum : forall (n:nat),\n (ANum n) || n\n | E_APlus : forall (e1 e2: aexp) (n1 n2 : nat),\n (e1 || n1) -> (e2 || n2) -> (APlus e1 e2) || (n1 + n2)\n | E_AMinus : forall (e1 e2: aexp) (n1 n2 : nat),\n (e1 || n1) -> (e2 || n2) -> (AMinus e1 e2) || (n1 - n2)\n | E_AMult : forall (e1 e2: aexp) (n1 n2 : nat),\n (e1 || n1) -> (e2 || n2) -> (AMult e1 e2) || (n1 * n2)\n\n where \"e '||' n\" := (aevalR e n) : type_scope.\n\nTactic Notation \"aevalR_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"E_ANum\" | Case_aux c \"E_APlus\"\n | Case_aux c \"E_AMinus\" | Case_aux c \"E_AMult\" ].\n\n(* ####################################################### *)\n(** ** Inference Rule Notation *)\n\n(** In informal discussions, it is convenient to write the rules for\n [aevalR] and similar relations in the more readable graphical form\n of _inference rules_, where the premises above the line justify\n the conclusion below the line (we have already seen them in the\n Prop chapter). *)\n\n(** For example, the constructor [E_APlus]...\n | E_APlus : forall (e1 e2: aexp) (n1 n2: nat),\n aevalR e1 n1 ->\n aevalR e2 n2 ->\n aevalR (APlus e1 e2) (n1 + n2)\n ...would be written like this as an inference rule:\n e1 || n1\n e2 || n2\n -------------------- (E_APlus)\n APlus e1 e2 || n1+n2\n*)\n\n(** Formally, there is nothing very deep about inference rules:\n they are just implications. You can read the rule name on the\n right as the name of the constructor and read each of the\n linebreaks between the premises above the line and the line itself\n as [->]. All the variables mentioned in the rule ([e1], [n1],\n etc.) are implicitly bound by universal quantifiers at the\n beginning. (Such variables are often called _metavariables_ to\n distinguish them from the variables of the language we are\n defining. At the moment, our arithmetic expressions don't include\n variables, but we'll soon be adding them.) The whole collection\n of rules is understood as being wrapped in an [Inductive]\n declaration (informally, this is either elided or else indicated\n by saying something like \"Let [aevalR] be the smallest relation\n closed under the following rules...\"). *)\n\n(** For example, [||] is the smallest relation closed under these\n rules:\n ----------- (E_ANum)\n ANum n || n\n\n e1 || n1\n e2 || n2\n -------------------- (E_APlus)\n APlus e1 e2 || n1+n2\n\n e1 || n1\n e2 || n2\n --------------------- (E_AMinus)\n AMinus e1 e2 || n1-n2\n\n e1 || n1\n e2 || n2\n -------------------- (E_AMult)\n AMult e1 e2 || n1*n2\n*)\n\n\n\n(* ####################################################### *)\n(** ** Equivalence of the Definitions *)\n\n(** It is straightforward to prove that the relational and functional\n definitions of evaluation agree on all possible arithmetic\n expressions... *)\n\nTheorem aeval_iff_aevalR : forall a n,\n (a || n) <-> aeval a = n.\nProof.\n split.\n Case \"->\".\n intros H.\n aevalR_cases (induction H) SCase; simpl.\n SCase \"E_ANum\".\n reflexivity.\n SCase \"E_APlus\".\n rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n SCase \"E_AMinus\".\n rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n SCase \"E_AMult\".\n rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n Case \"<-\".\n generalize dependent n.\n aexp_cases (induction a) SCase;\n simpl; intros; subst.\n SCase \"ANum\".\n apply E_ANum.\n SCase \"APlus\".\n apply E_APlus.\n apply IHa1. reflexivity.\n apply IHa2. reflexivity.\n SCase \"AMinus\".\n apply E_AMinus.\n apply IHa1. reflexivity.\n apply IHa2. reflexivity.\n SCase \"AMult\".\n apply E_AMult.\n apply IHa1. reflexivity.\n apply IHa2. reflexivity.\nQed.\n\n(** Note: if you're reading the HTML file, you'll see an empty square box instead\nof a proof for this theorem. \nYou can click on this box to \"unfold\" the text to see the proof.\nClick on the unfolded to text to \"fold\" it back up to a box. We'll be using\nthis style frequently from now on to help keep the HTML easier to read.\nThe full proofs always appear in the .v files. *)\n\n(** We can make the proof quite a bit shorter by making more\n use of tacticals... *)\n\nTheorem aeval_iff_aevalR' : forall a n,\n (a || n) <-> aeval a = n.\nProof.\n (* WORKED IN CLASS *)\n split.\n Case \"->\".\n intros H; induction H; subst; reflexivity.\n Case \"<-\".\n generalize dependent n.\n induction a; simpl; intros; subst; constructor;\n try apply IHa1; try apply IHa2; reflexivity.\nQed.\n\n(** **** Exercise: 3 stars (bevalR) *)\n(** Write a relation [bevalR] in the same style as\n [aevalR], and prove that it is equivalent to [beval].*)\n\nReserved Notation \"e '|||' b\" (at level 50, left associativity).\n\nInductive bevalR: bexp -> bool -> Prop :=\n | E_BTrue : BTrue ||| true\n | E_BFalse : BFalse ||| false\n | E_BEq : forall (e1 e2: aexp) (n1 n2: nat),\n (e1 || n1) -> (e2 || n2) -> (BEq e1 e2) ||| (beq_nat n1 n2)\n | E_BLe : forall (e1 e2: aexp) (n1 n2: nat),\n (e1 || n1) -> (e2 || n2) -> (BLe e1 e2) ||| (ble_nat n1 n2)\n | E_BNot : forall (e: bexp) (b: bool),\n (e ||| b) -> (BNot e) ||| (negb b)\n | E_BAnd : forall (e1 e2: bexp) (b1 b2: bool),\n (e1 ||| b1) -> (e2 ||| b2) -> (BAnd e1 e2) ||| (andb b1 b2)\n \n where \"e '|||' b\" := (bevalR e b) : type_scope.\n\nTactic Notation \"bevalR_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"E_BTrue\" | Case_aux c \"E_BFalse\"\n | Case_aux c \"E_BEq\" | Case_aux c \"E_BLe\"\n | Case_aux c \"E_BNot\" | Case_aux c \"E_BAnd\"].\n\nTheorem beval_iff_bevalR : forall (e: bexp) (b: bool),\n (e ||| b) <-> beval e = b.\nProof.\n split.\n Case \"->\".\n intros.\n bevalR_cases (induction H) Scase; simpl; \n try reflexivity; \n try (apply aeval_iff_aevalR in H; apply aeval_iff_aevalR in H0;\n rewrite H; rewrite H0; reflexivity).\n SCase \"E_BNot\". \n rewrite IHbevalR. reflexivity.\n SCase \"E_BAnd\".\n rewrite IHbevalR1. rewrite IHbevalR2. reflexivity.\n Case \"<-\".\n generalize dependent b.\n bexp_cases (induction e) SCase; \n simpl; intros; subst; constructor;\n try (apply aeval_iff_aevalR; reflexivity).\n SCase \"BNot\". apply IHe. reflexivity.\n SCase \"BAnd\". apply IHe1. auto. apply IHe2; auto.\nQed.\n\nTheorem beval_iff_bevalR' : forall (e: bexp) (b: bool),\n (e ||| b) <-> beval e = b.\nProof.\n split.\n Case \"->\".\n intros.\n bevalR_cases (induction H) Scase; simpl. \n SCase \"E_BTrue\".\n reflexivity.\n SCase \"E_BFalse\".\n reflexivity.\n SCase \"E_BEq\". \n apply aeval_iff_aevalR in H. apply aeval_iff_aevalR in H0.\n rewrite H. rewrite H0. reflexivity.\n SCase \"E_BLe\".\n apply aeval_iff_aevalR in H. apply aeval_iff_aevalR in H0.\n rewrite H. rewrite H0. reflexivity.\n SCase \"E_BNot\".\n rewrite IHbevalR. reflexivity.\n SCase \"E_BAnd\".\n rewrite IHbevalR1. rewrite IHbevalR2. reflexivity.\n Case \"<-\".\n generalize dependent b.\n bexp_cases (induction e) SCase; \n simpl; intros; subst.\n SCase \"BTrue\".\n apply E_BTrue.\n SCase \"BFalse\".\n apply E_BFalse.\n SCase \"BEq\".\n apply E_BEq. apply aeval_iff_aevalR. reflexivity.\n apply aeval_iff_aevalR. reflexivity.\n SCase \"BLe\".\n apply E_BLe. apply aeval_iff_aevalR. reflexivity.\n apply aeval_iff_aevalR. reflexivity.\n SCase \"BNot\".\n apply E_BNot. apply IHe. reflexivity.\n SCase \"BAnd\".\n apply E_BAnd. apply IHe1. reflexivity.\n apply IHe2. reflexivity.\nQed.\n(** [] *)\nEnd AExp.\n\n(* ####################################################### *)\n(** ** Computational vs. Relational Definitions *)\n\n(** For the definitions of evaluation for arithmetic and boolean\n expressions, the choice of whether to use functional or relational\n definitions is mainly a matter of taste. In general, Coq has\n somewhat better support for working with relations. On the other\n hand, in some sense function definitions carry more information,\n because functions are necessarily deterministic and defined on all\n arguments; for a relation we have to show these properties\n explicitly if we need them. Functions also take advantage of Coq's\n computations mechanism.\n\n However, there are circumstances where relational definitions of\n evaluation are preferable to functional ones. *)\n\nModule aevalR_division.\n\n(** For example, suppose that we wanted to extend the arithmetic\n operations by considering also a division operation:*)\n\nInductive aexp : Type :=\n | ANum : nat -> aexp\n | APlus : aexp -> aexp -> aexp\n | AMinus : aexp -> aexp -> aexp\n | AMult : aexp -> aexp -> aexp\n | ADiv : aexp -> aexp -> aexp. (* <--- new *)\n\n(** Extending the definition of [aeval] to handle this new operation\n would not be straightforward (what should we return as the result\n of [ADiv (ANum 5) (ANum 0)]?). But extending [aevalR] is\n straightforward. *)\n\nInductive aevalR : aexp -> nat -> Prop :=\n | E_ANum : forall (n:nat),\n (ANum n) || n\n | E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),\n (a1 || n1) -> (a2 || n2) -> (APlus a1 a2) || (n1 + n2)\n | E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),\n (a1 || n1) -> (a2 || n2) -> (AMinus a1 a2) || (n1 - n2)\n | E_AMult : forall (a1 a2: aexp) (n1 n2 : nat),\n (a1 || n1) -> (a2 || n2) -> (AMult a1 a2) || (n1 * n2)\n | E_ADiv : forall (a1 a2: aexp) (n1 n2 n3: nat),\n (a1 || n1) -> (a2 || n2) -> (mult n2 n3 = n1) -> (ADiv a1 a2) || n3\n\nwhere \"a '||' n\" := (aevalR a n) : type_scope.\n\nEnd aevalR_division.\nModule aevalR_extended.\n\n\n(** Suppose, instead, that we want to extend the arithmetic operations\n by a nondeterministic number generator [any]:*)\n\nInductive aexp : Type :=\n | AAny : aexp (* <--- NEW *)\n | ANum : nat -> aexp\n | APlus : aexp -> aexp -> aexp\n | AMinus : aexp -> aexp -> aexp\n | AMult : aexp -> aexp -> aexp.\n\n(** Again, extending [aeval] would be tricky (because evaluation is\n _not_ a deterministic function from expressions to numbers), but\n extending [aevalR] is no problem: *)\n\nInductive aevalR : aexp -> nat -> Prop :=\n | E_Any : forall (n:nat),\n AAny || n (* <--- new *)\n | E_ANum : forall (n:nat),\n (ANum n) || n\n | E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),\n (a1 || n1) -> (a2 || n2) -> (APlus a1 a2) || (n1 + n2)\n | E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),\n (a1 || n1) -> (a2 || n2) -> (AMinus a1 a2) || (n1 - n2)\n | E_AMult : forall (a1 a2: aexp) (n1 n2 : nat),\n (a1 || n1) -> (a2 || n2) -> (AMult a1 a2) || (n1 * n2)\n\nwhere \"a '||' n\" := (aevalR a n) : type_scope.\n\nEnd aevalR_extended.\n\n(** * Expressions With Variables *)\n\n(** Let's turn our attention back to defining Imp. The next thing we\n need to do is to enrich our arithmetic and boolean expressions\n with variables. To keep things simple, we'll assume that all\n variables are global and that they only hold numbers. *)\n\n(* ##################################################### *)\n(** ** Identifiers *)\n\n(** To begin, we'll need to formalize _identifiers_ such as program\n variables. We could use strings for this -- or, in a real\n compiler, fancier structures like pointers into a symbol table.\n But for simplicity let's just use natural numbers as identifiers. *)\n\n(** (We hide this section in a module because these definitions are\n actually in [SfLib], but we want to repeat them here so that we\n can explain them.) *)\n\nModule Id. \n\n(** We define a new inductive datatype [Id] so that we won't confuse\n identifiers and numbers. We use [sumbool] to define a computable\n equality operator on [Id]. *)\n\nInductive id : Type :=\n Id : nat -> id.\n\nTheorem eq_id_dec : forall id1 id2 : id, {id1 = id2} + {id1 <> id2}.\nProof.\n intros id1 id2.\n destruct id1 as [n1]. destruct id2 as [n2].\n destruct (eq_nat_dec n1 n2) as [Heq | Hneq].\n Case \"n1 = n2\".\n left. rewrite Heq. reflexivity.\n Case \"n1 <> n2\".\n right. intros contra. inversion contra. apply Hneq. apply H0.\nDefined. \n\n\n(** The following lemmas will be useful for rewriting terms involving [eq_id_dec]. *)\n\nLemma eq_id : forall (T:Type) x (p q:T), \n (if eq_id_dec x x then p else q) = p. \nProof.\n intros. \n destruct (eq_id_dec x x). \n Case \"x = x\". \n reflexivity.\n Case \"x <> x (impossible)\". \n apply ex_falso_quodlibet; apply n; reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (neq_id) *)\nLemma neq_id : forall (T:Type) x y (p q:T), x <> y -> \n (if eq_id_dec x y then p else q) = q. \nProof.\n intros.\n destruct (eq_id_dec x y).\n Case \"x = y\".\n unfold not in H. apply H in e. inversion e.\n Case \"x <> y\".\n reflexivity.\nQed.\n(** [] *)\n\n\nEnd Id. \n\n(* ####################################################### *)\n(** ** States *)\n\n(** A _state_ represents the current values of _all_ the variables at\n some point in the execution of a program. *)\n(** For simplicity (to avoid dealing with partial functions), we\n let the state be defined for _all_ variables, even though any\n given program is only going to mention a finite number of them. \n The state captures all of the information stored in memory. For Imp\n programs, because each variable stores only a natural number, we\n can represent the state as a mapping from identifiers to [nat]. \n For more complex programming languages, the state might have more \n structure. \n*)\n\nDefinition state := id -> nat.\n\nDefinition empty_state : state :=\n fun _ => 0.\n\nDefinition update (st : state) (x : id) (n : nat) : state :=\n fun x' => if eq_id_dec x x' then n else st x'.\n\n(** For proofs involving states, we'll need several simple properties\n of [update]. *)\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq : forall n x st,\n (update st x n) x = n.\nProof.\n intros. unfold update. destruct (eq_id_dec x x).\n Case \"x = x\".\n reflexivity.\n Case \"x <> x\". \n assert(H: x = x -> False -> False).\n intros. apply H0.\n unfold not in n0. apply H in n0. inversion n0. auto. auto.\nQed. \n(** [] *)\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq : forall x2 x1 n st,\n x2 <> x1 -> \n (update st x2 n) x1 = (st x1).\nProof.\n intros. unfold update. destruct (eq_id_dec x2 x1).\n contradiction.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (update_example) *)\n(** Before starting to play with tactics, make sure you understand\n exactly what the theorem is saying! *)\n\nTheorem update_example : forall (n:nat),\n (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n intros. unfold update.\n simpl. compute. auto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (update_shadow) *)\nTheorem update_shadow : forall n1 n2 x1 x2 (st : state),\n (update (update st x2 n1) x2 n2) x1 = (update st x2 n2) x1.\nProof.\n intros. unfold update. destruct (eq_id_dec x2 x1).\n Case \"x2 = x1\".\n reflexivity.\n Case \"x2 <> x1\".\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (update_same) *)\nTheorem update_same : forall n1 x1 x2 (st : state),\n st x1 = n1 ->\n (update st x1 n1) x2 = st x2.\nProof.\n intros. unfold update. destruct (eq_id_dec x1 x2).\n rewrite e in H. rewrite H. auto.\n auto.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (update_permute) *)\nTheorem update_permute : forall n1 n2 x1 x2 x3 st,\n x2 <> x1 -> \n (update (update st x2 n1) x1 n2) x3 = (update (update st x1 n2) x2 n1) x3.\nProof.\n intros. unfold update.\n destruct (eq_id_dec x1 x3).\n Case \"x1 = x3\".\n rewrite e in H. destruct (eq_id_dec x2 x3).\n contradiction.\n auto.\n Case \"x1 <> x3\".\n destruct (eq_id_dec x2 x3). auto. auto.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Syntax *)\n\n(** We can add variables to the arithmetic expressions we had before by\n simply adding one more constructor: *)\n\nInductive aexp : Type :=\n | ANum : nat -> aexp\n | AId : id -> aexp (* <----- NEW *)\n | APlus : aexp -> aexp -> aexp\n | AMinus : aexp -> aexp -> aexp\n | AMult : aexp -> aexp -> aexp.\n\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"ANum\" | Case_aux c \"AId\" | Case_aux c \"APlus\"\n | Case_aux c \"AMinus\" | Case_aux c \"AMult\" ].\n\n(** Defining a few variable names as notational shorthands will make\n examples easier to read: *)\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\n\n(** (This convention for naming program variables ([X], [Y],\n [Z]) clashes a bit with our earlier use of uppercase letters for\n types. Since we're not using polymorphism heavily in this part of\n the course, this overloading should not cause confusion.) *)\n\n(** The definition of [bexp]s is the same as before (using the new\n [aexp]s): *)\n\nInductive bexp : Type :=\n | BTrue : bexp\n | BFalse : bexp\n | BEq : aexp -> aexp -> bexp\n | BLe : aexp -> aexp -> bexp\n | BNot : bexp -> bexp\n | BAnd : bexp -> bexp -> bexp.\n\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\" | Case_aux c \"BEq\"\n | Case_aux c \"BLe\" | Case_aux c \"BNot\" | Case_aux c \"BAnd\" ].\n\n(* ################################################### *)\n(** ** Evaluation *)\n\n(** The arith and boolean evaluators can be extended to handle\n variables in the obvious way: *)\n\nFixpoint aeval (st : state) (a : aexp) : nat :=\n match a with\n | ANum n => n\n | AId x => st x (* <----- NEW *)\n | APlus a1 a2 => (aeval st a1) + (aeval st a2)\n | AMinus a1 a2 => (aeval st a1) - (aeval st a2)\n | AMult a1 a2 => (aeval st a1) * (aeval st a2)\n end.\n\nFixpoint beval (st : state) (b : bexp) : bool :=\n match b with\n | BTrue => true\n | BFalse => false\n | BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)\n | BLe a1 a2 => ble_nat (aeval st a1) (aeval st a2)\n | BNot b1 => negb (beval st b1)\n | BAnd b1 b2 => andb (beval st b1) (beval st b2)\n end.\n\n(*????*)\nExample aexp1 :\n aeval (update empty_state X 5)\n (APlus (ANum 3) (AMult (AId X) (ANum 2)))\n = 13.\nProof. reflexivity. Qed.\n\nExample bexp1 :\n beval (update empty_state X 5)\n (BAnd BTrue (BNot (BLe (AId X) (ANum 4))))\n = true.\nProof. reflexivity. Qed.\n(*????*)\n\n(* ####################################################### *)\n(** * Commands *)\n\n(** Now we are ready define the syntax and behavior of Imp\n _commands_ (often called _statements_). *)\n\n(* ################################################### *)\n(** ** Syntax *)\n\n(** Informally, commands [c] are described by the following BNF\n grammar:\n c ::= SKIP\n | x ::= a\n | c ;; c\n | WHILE b DO c END\n | IFB b THEN c ELSE c FI\n]] \n*)\n(**\n For example, here's the factorial function in Imp.\n Z ::= X;;\n Y ::= 1;;\n WHILE not (Z = 0) DO\n Y ::= Y * Z;;\n Z ::= Z - 1\n END\n When this command terminates, the variable [Y] will contain the\n factorial of the initial value of [X].\n*)\n\n(** Here is the formal definition of the syntax of commands: *)\n\nInductive com : Type :=\n | CSkip : com\n | CAss : id -> aexp -> com\n | CSeq : com -> com -> com\n | CIf : bexp -> com -> com -> com\n | CWhile : bexp -> com -> com.\n\nTactic Notation \"com_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"SKIP\" | Case_aux c \"::=\" | Case_aux c \";;\"\n | Case_aux c \"IFB\" | Case_aux c \"WHILE\" ].\n\n(** As usual, we can use a few [Notation] declarations to make things\n more readable. We need to be a bit careful to avoid conflicts\n with Coq's built-in notations, so we'll keep this light -- in\n particular, we won't introduce any notations for [aexps] and\n [bexps] to avoid confusion with the numerical and boolean\n operators we've already defined. We use the keyword [IFB] for\n conditionals instead of [IF], for similar reasons. *)\n\nNotation \"'SKIP'\" :=\n CSkip.\nNotation \"x '::=' a\" :=\n (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" :=\n (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n (CIf c1 c2 c3) (at level 80, right associativity).\n\n(** For example, here is the factorial function again, written as a\n formal definition to Coq: *)\n\nDefinition fact_in_coq : com :=\n Z ::= AId X;;\n Y ::= ANum 1;;\n WHILE BNot (BEq (AId Z) (ANum 0)) DO\n Y ::= AMult (AId Y) (AId Z);;\n Z ::= AMinus (AId Z) (ANum 1)\n END.\n\n(* ####################################################### *)\n(** ** Examples *)\n\n(** Assignment: *)\n\nDefinition plus2 : com :=\n X ::= (APlus (AId X) (ANum 2)).\n\nDefinition XtimesYinZ : com :=\n Z ::= (AMult (AId X) (AId Y)).\n\nDefinition subtract_slowly_body : com :=\n Z ::= AMinus (AId Z) (ANum 1) ;;\n X ::= AMinus (AId X) (ANum 1).\n\n\n(** *** Loops *)\n\nDefinition subtract_slowly : com :=\n WHILE BNot (BEq (AId X) (ANum 0)) DO\n subtract_slowly_body\n END.\n\nDefinition subtract_3_from_5_slowly : com :=\n X ::= ANum 3 ;;\n Z ::= ANum 5 ;;\n subtract_slowly.\n\n\n(** *** An infinite loop: *)\n\nDefinition loop : com :=\n WHILE BTrue DO\n SKIP\n END.\n\n(* ################################################################ *)\n(** * Evaluation *)\n\n(** Next we need to define what it means to evaluate an Imp command.\n The fact that [WHILE] loops don't necessarily terminate makes defining\n an evaluation function tricky... *)\n\n(* #################################### *)\n(** ** Evaluation as a Function (Failed Attempt) *)\n\n(** Here's an attempt at defining an evaluation function for commands,\n omitting the [WHILE] case. *)\n\nFixpoint ceval_fun_no_while (st : state) (c : com) : state :=\n match c with\n | SKIP =>\n st\n | x ::= a1 =>\n update st x (aeval st a1)\n | c1 ;; c2 =>\n let st' := ceval_fun_no_while st c1 in\n ceval_fun_no_while st' c2\n | IFB b THEN c1 ELSE c2 FI =>\n if (beval st b)\n then ceval_fun_no_while st c1\n else ceval_fun_no_while st c2\n | WHILE b DO c END =>\n st (* bogus *)\n end.\n(** In a traditional functional programming language like ML or\n Haskell we could write the [WHILE] case as follows:\n<<\n Fixpoint ceval_fun (st : state) (c : com) : state :=\n match c with\n ...\n | WHILE b DO c END =>\n if (beval st b1)\n then ceval_fun st (c1; WHILE b DO c END)\n else st\n end.\n>>\n Coq doesn't accept such a definition (\"Error: Cannot guess\n decreasing argument of fix\") because the function we want to\n define is not guaranteed to terminate. Indeed, it doesn't always\n terminate: for example, the full version of the [ceval_fun]\n function applied to the [loop] program above would never\n terminate. Since Coq is not just a functional programming\n language, but also a consistent logic, any potentially\n non-terminating function needs to be rejected. Here is\n an (invalid!) Coq program showing what would go wrong if Coq\n allowed non-terminating recursive functions:\n<<\n Fixpoint loop_false (n : nat) : False := loop_false n.\n>>\n That is, propositions like [False] would become provable\n (e.g. [loop_false 0] would be a proof of [False]), which\n would be a disaster for Coq's logical consistency.\n\n Thus, because it doesn't terminate on all inputs, the full version\n of [ceval_fun] cannot be written in Coq -- at least not without\n additional tricks (see chapter [ImpCEvalFun] if curious). *)\n\n(* #################################### *)\n(** ** Evaluation as a Relation *)\n\n(** Here's a better way: we define [ceval] as a _relation_ rather than\n a _function_ -- i.e., we define it in [Prop] instead of [Type], as\n we did for [aevalR] above. *)\n\n(** This is an important change. Besides freeing us from the awkward\n workarounds that would be needed to define evaluation as a\n function, it gives us a lot more flexibility in the definition.\n For example, if we added concurrency features to the language,\n we'd want the definition of evaluation to be non-deterministic --\n i.e., not only would it not be total, it would not even be a\n partial function! *)\n(** We'll use the notation [c / st || st'] for our [ceval] relation:\n [c / st || st'] means that executing program [c] in a starting\n state [st] results in an ending state [st']. This can be\n pronounced \"[c] takes state [st] to [st']\".\n\n*)\n(** *** Operational Semantics \n ---------------- (E_Skip)\n SKIP / st || st\n\n aeval st a1 = n\n -------------------------------- (E_Ass)\n x := a1 / st || (update st x n)\n\n c1 / st || st'\n c2 / st' || st''\n ------------------- (E_Seq)\n c1;;c2 / st || st''\n\n beval st b1 = true\n c1 / st || st'\n ------------------------------------- (E_IfTrue)\n IF b1 THEN c1 ELSE c2 FI / st || st'\n\n beval st b1 = false\n c2 / st || st'\n ------------------------------------- (E_IfFalse)\n IF b1 THEN c1 ELSE c2 FI / st || st'\n\n beval st b1 = false\n ------------------------------ (E_WhileEnd)\n WHILE b DO c END / st || st\n\n beval st b1 = true\n c / st || st'\n WHILE b DO c END / st' || st''\n --------------------------------- (E_WhileLoop)\n WHILE b DO c END / st || st''\n*)\n\n(** Here is the formal definition. (Make sure you understand\n how it corresponds to the inference rules.) *)\n\nReserved Notation \"c1 '/' st '||' st'\" (at level 40, st at level 39).\n\nInductive ceval : com -> state -> state -> Prop :=\n | E_Skip : forall st,\n SKIP / st || st\n | E_Ass : forall st a1 n x,\n aeval st a1 = n ->\n (x ::= a1) / st || (update st x n)\n | E_Seq : forall c1 c2 st st' st'',\n c1 / st || st' ->\n c2 / st' || st'' ->\n (c1 ;; c2) / st || st''\n | E_IfTrue : forall st st' b c1 c2,\n beval st b = true ->\n c1 / st || st' ->\n (IFB b THEN c1 ELSE c2 FI) / st || st'\n | E_IfFalse : forall st st' b c1 c2,\n beval st b = false ->\n c2 / st || st' ->\n (IFB b THEN c1 ELSE c2 FI) / st || st'\n | E_WhileEnd : forall b st c,\n beval st b = false ->\n (WHILE b DO c END) / st || st\n | E_WhileLoop : forall st st' st'' b c,\n beval st b = true ->\n c / st || st' ->\n (WHILE b DO c END) / st' || st'' ->\n (WHILE b DO c END) / st || st''\n\n where \"c1 '/' st '||' st'\" := (ceval c1 st st').\n\nTactic Notation \"ceval_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"E_Skip\" | Case_aux c \"E_Ass\" | Case_aux c \"E_Seq\"\n | Case_aux c \"E_IfTrue\" | Case_aux c \"E_IfFalse\"\n | Case_aux c \"E_WhileEnd\" | Case_aux c \"E_WhileLoop\" ].\n\n(** *** *)\n(** The cost of defining evaluation as a relation instead of a\n function is that we now need to construct _proofs_ that some\n program evaluates to some result state, rather than just letting\n Coq's computation mechanism do it for us. *)\n\nExample ceval_example1:\n (X ::= ANum 2;;\n IFB BLe (AId X) (ANum 1)\n THEN Y ::= ANum 3\n ELSE Z ::= ANum 4\n FI)\n / empty_state\n || (update (update empty_state X 2) Z 4).\nProof. \n (* We must supply the intermediate state *)\n apply E_Seq with (update empty_state X 2).\n Case \"assignment command\".\n apply E_Ass. reflexivity.\n Case \"if command\".\n apply E_IfFalse.\n reflexivity.\n apply E_Ass. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (ceval_example2) *)\nExample ceval_example2:\n (X ::= ANum 0;; Y ::= ANum 1;; Z ::= ANum 2) / empty_state ||\n (update (update (update empty_state X 0) Y 1) Z 2).\nProof.\n apply E_Seq with (update empty_state X 0).\n apply E_Ass. reflexivity.\n apply E_Seq with (update (update empty_state X 0) Y 1).\n apply E_Ass. reflexivity.\n apply E_Ass. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (pup_to_n) *)\n(** Write an Imp program that sums the numbers from [1] to\n [X] (inclusive: [1 + 2 + ... + X]) in the variable [Y].\n Prove that this program executes as intended for X = 2\n (this latter part is trickier than you might expect). *)\n\nDefinition pup_to_n : com :=\n Y ::= ANum 0 ;;\n WHILE (BLe (ANum 1) (AId X))\n DO \n Y ::= APlus (AId Y) (AId X) ;;\n X ::= AMinus (AId X) (ANum 1)\n END.\n\nTheorem pup_to_2_ceval :\n pup_to_n / (update empty_state X 2) ||\n update (update (update (update (update (update empty_state\n X 2) Y 0) Y 2) X 1) Y 3) X 0.\nProof.\n unfold pup_to_n.\n apply E_Seq with (update (update empty_state X 2) Y 0).\n apply E_Ass. reflexivity.\n apply E_WhileLoop with (update (update (update (update empty_state X 2) Y 0) Y 2) X 1).\n reflexivity.\n apply E_Seq with (update (update (update empty_state X 2) Y 0) Y 2).\n apply E_Ass. reflexivity.\n apply E_Ass. reflexivity.\n apply E_WhileLoop with (update\n (update (update (update (update (update empty_state X 2) Y 0) Y 2) X 1)\n Y 3) X 0).\n reflexivity.\n apply E_Seq with (update (update (update (update (update empty_state X 2) Y 0) Y 2) X 1)\n Y 3).\n apply E_Ass. reflexivity.\n apply E_Ass. reflexivity.\n apply E_WhileEnd. reflexivity.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Determinism of Evaluation *)\n\n(** Changing from a computational to a relational definition of\n evaluation is a good move because it allows us to escape from the\n artificial requirement (imposed by Coq's restrictions on\n [Fixpoint] definitions) that evaluation should be a total\n function. But it also raises a question: Is the second definition\n of evaluation actually a partial function? That is, is it\n possible that, beginning from the same state [st], we could\n evaluate some command [c] in different ways to reach two different\n output states [st'] and [st'']?\n\n In fact, this cannot happen: [ceval] is a partial function.\n Here's the proof: *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2.\n ceval_cases (induction E1) Case;\n intros st2 E2; inversion E2; subst.\n Case \"E_Skip\". reflexivity.\n Case \"E_Ass\". reflexivity.\n Case \"E_Seq\".\n assert (st' = st'0) as EQ1.\n SCase \"Proof of assertion\". apply IHE1_1; assumption.\n subst st'0.\n apply IHE1_2. assumption.\n Case \"E_IfTrue\".\n SCase \"b1 evaluates to true\".\n apply IHE1. assumption.\n SCase \"b1 evaluates to false (contradiction)\".\n rewrite H in H5. inversion H5.\n Case \"E_IfFalse\".\n SCase \"b1 evaluates to true (contradiction)\".\n rewrite H in H5. inversion H5.\n SCase \"b1 evaluates to false\".\n apply IHE1. assumption.\n Case \"E_WhileEnd\".\n SCase \"b1 evaluates to false\".\n reflexivity.\n SCase \"b1 evaluates to true (contradiction)\".\n rewrite H in H2. inversion H2.\n Case \"E_WhileLoop\".\n SCase \"b1 evaluates to false (contradiction)\".\n rewrite H in H4. inversion H4.\n SCase \"b1 evaluates to true\".\n assert (st' = st'0) as EQ1.\n SSCase \"Proof of assertion\". apply IHE1_1; assumption.\n subst st'0.\n apply IHE1_2. assumption. Qed.\n\n\n(* ####################################################### *)\n(** * Reasoning About Imp Programs *)\n\n(** We'll get much deeper into systematic techniques for reasoning\n about Imp programs in the following chapters, but we can do quite\n a bit just working with the bare definitions. *)\n\n(* This section explores some examples. *)\n\nTheorem plus2_spec : forall st n st',\n st X = n ->\n plus2 / st || st' ->\n st' X = n + 2.\nProof.\n intros st n st' HX Heval.\n (* Inverting Heval essentially forces Coq to expand one\n step of the ceval computation - in this case revealing\n that st' must be st extended with the new value of X,\n since plus2 is an assignment *)\n inversion Heval. subst. clear Heval. simpl.\n apply update_eq. Qed.\n\n(** **** Exercise: 3 stars (XtimesYinZ_spec) *)\n(** State and prove a specification of [XtimesYinZ]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars (loop_never_stops) *)\nTheorem loop_never_stops : forall st st',\n ~(loop / st || st').\nProof.\n intros st st' contra. unfold loop in contra.\n remember (WHILE BTrue DO SKIP END) as loopdef eqn:Heqloopdef.\n (* Proceed by induction on the assumed derivation showing that\n [loopdef] terminates. Most of the cases are immediately\n contradictory (and so can be solved in one step with\n [inversion]). *)\n induction contra; inversion Heqloopdef.\n subst. inversion H.\n subst. apply IHcontra2. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (no_whilesR) *)\n(** Consider the definition of the [no_whiles] property below: *)\n\nFixpoint no_whiles (c : com) : bool :=\n match c with\n | SKIP => true\n | _ ::= _ => true\n | c1 ;; c2 => andb (no_whiles c1) (no_whiles c2)\n | IFB _ THEN ct ELSE cf FI => andb (no_whiles ct) (no_whiles cf)\n | WHILE _ DO _ END => false\n end.\n\n(** This property yields [true] just on programs that\n have no while loops. Using [Inductive], write a property\n [no_whilesR] such that [no_whilesR c] is provable exactly when [c]\n is a program with no while loops. Then prove its equivalence\n with [no_whiles]. *)\n\nInductive no_whilesR: com -> Prop :=\n | nw_SKIP: no_whilesR SKIP\n | nw_Ass: forall x a1, no_whilesR (x ::= a1)\n | nw_Seq: forall c1 c2, no_whilesR c1 -> no_whilesR c2 -> no_whilesR (c1 ;; c2)\n | nw_If: forall b c1 c2, no_whilesR c1 -> no_whilesR c2 \n -> no_whilesR (IFB b THEN c1 ELSE c2 FI)\n | nw_while: forall b c, no_whilesR c -> False -> no_whilesR (WHILE b DO c END)\n .\n\nTheorem no_whiles_eqv:\n forall c, no_whiles c = true <-> no_whilesR c.\nProof.\n intros. split; intros.\n Case \"->\".\n induction c; constructor; inversion H; \n apply andb_true_iff in H1; destruct H1;\n try (apply IHc1; apply H0); try (apply IHc2; apply H1).\n Case \"<-\".\n induction c; simpl; \n try (rewrite IHc1); try (rewrite IHc2); try (reflexivity);\n try (inversion H; subst; assumption).\n inversion H. inversion H3.\n(** [] *)\n\n(** **** Exercise: 4 stars (no_whiles_terminating) *)\n(** Imp programs that don't involve while loops always terminate.\n State and prove a theorem [no_whiles_terminating] that says this. *)\n(** (Use either [no_whiles] or [no_whilesR], as you prefer.) *)\n\nTheorem no_whiles_terminate: forall c st\n (NOWHL: no_whiles c = true),\n exists st', c / st || st'.\nProof.\n induction c; intros.\n Case \"SKIP\".\n exists st. constructor.\n Case \"Ass\".\n exists (update st i (aeval st a)). constructor. reflexivity.\n Case \"Seq\".\n inversion NOWHL. apply andb_true_iff in H0. destruct H0.\n specialize (IHc1 (st)). apply IHc1 in H. inversion H. \n specialize (IHc2 (x)). apply IHc2 in H0. inversion H0.\n exists x0. apply E_Seq with (st':=x). assumption. assumption.\n Case \"If\".\n inversion NOWHL. apply andb_true_iff in H0; destruct H0.\n specialize (IHc1 (st)). apply IHc1 in H. inversion H.\n specialize (IHc2 (st)). apply IHc2 in H0. inversion H0.\n destruct (beval st b) eqn:beq. \n exists x. apply E_IfTrue. assumption. assumption.\n exists x0. apply E_IfFalse. assumption. assumption.\n Case \"While\".\n inversion NOWHL.\nQed.\n(** [] *)\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (stack_compiler) *)\n(** HP Calculators, programming languages like Forth and Postscript,\n and abstract machines like the Java Virtual Machine all evaluate\n arithmetic expressions using a stack. For instance, the expression\n<<\n (2*3)+(3*(4-2))\n>>\n would be entered as\n<<\n 2 3 * 3 4 2 - * +\n>>\n and evaluated like this:\n<<\n [] | 2 3 * 3 4 2 - * +\n [2] | 3 * 3 4 2 - * +\n [3, 2] | * 3 4 2 - * +\n [6] | 3 4 2 - * +\n [3, 6] | 4 2 - * +\n [4, 3, 6] | 2 - * +\n [2, 4, 3, 6] | - * +\n [2, 3, 6] | * +\n [6, 6] | +\n [12] |\n>>\n\n The task of this exercise is to write a small compiler that\n translates [aexp]s into stack machine instructions.\n\n The instruction set for our stack language will consist of the\n following instructions:\n - [SPush n]: Push the number [n] on the stack.\n - [SLoad x]: Load the identifier [x] from the store and push it\n on the stack\n - [SPlus]: Pop the two top numbers from the stack, add them, and\n push the result onto the stack.\n - [SMinus]: Similar, but subtract.\n - [SMult]: Similar, but multiply. *)\n\nInductive sinstr : Type :=\n| SPush : nat -> sinstr\n| SLoad : id -> sinstr\n| SPlus : sinstr\n| SMinus : sinstr\n| SMult : sinstr.\n\n(** Write a function to evaluate programs in the stack language. It\n takes as input a state, a stack represented as a list of\n numbers (top stack item is the head of the list), and a program\n represented as a list of instructions, and returns the stack after\n executing the program. Test your function on the examples below.\n\n Note that the specification leaves unspecified what to do when\n encountering an [SPlus], [SMinus], or [SMult] instruction if the\n stack contains less than two elements. In a sense, it is\n immaterial what we do, since our compiler will never emit such a\n malformed program. *)\n\nFixpoint s_execute' (st : state) (stack : list nat)\n (prog : list sinstr)\n : list nat :=\n match prog with\n | [] => stack\n | (SPush n) :: prog' => s_execute' st (n :: stack) prog'\n | (SLoad x) :: prog' => s_execute' st ((st x) :: stack) prog'\n | SPlus :: prog' \n => s_execute' st (((hd 0 stack) + (hd 0 (tl stack))) :: (tl (tl stack))) prog'\n | SMinus :: prog' \n => s_execute' st (((hd 0 (tl stack)) - (hd 0 stack)) :: (tl (tl stack))) prog'\n | SMult :: prog' \n => s_execute' st (((hd 0 stack) * (hd 0 (tl stack))) :: (tl (tl stack))) prog'\n end.\n\nExample s_execute1 :\n s_execute' empty_state []\n [SPush 5; SPush 3; SPush 1; SMinus]\n = [2; 5].\nProof. simpl. reflexivity. Qed.\n\n\nExample s_execute2 :\n s_execute' (update empty_state X 3) [3;4]\n [SPush 4; SLoad X; SMult; SPlus]\n = [15; 4].\nProof. simpl. reflexivity. Qed.\n\n(** Next, write a function which compiles an [aexp] into a stack\n machine program. The effect of running the program should be the\n same as pushing the value of the expression on the stack. *)\n \nFixpoint s_compile (e : aexp) : list sinstr :=\n match e with\n | ANum n => [SPush n]\n | AId x => [SLoad x]\n | APlus a b => (s_compile a) ++ (s_compile b) ++ [SPlus]\n | AMinus a b => (s_compile a) ++ (s_compile b) ++ [SMinus]\n | AMult a b => (s_compile a) ++ (s_compile b) ++ [SMult]\n end.\n\n(** After you've defined [s_compile], prove the following to test\n that it works. *)\n\nExample s_compile1 :\n s_compile (AMinus (AId X) (AMult (ANum 2) (AId Y)))\n = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (stack_compiler_correct) *)\n(** The task of this exercise is to prove the correctness of the\n compiler implemented in the previous exercise. Remember that\n the specification left unspecified what to do when encountering an\n [SPlus], [SMinus], or [SMult] instruction if the stack contains\n less than two elements. (In order to make your correctness proof\n easier you may find it useful to go back and change your\n implementation!)\n\n Prove the following theorem, stating that the [compile] function\n behaves correctly. You will need to start by stating a more\n general lemma to get a usable induction hypothesis; the main\n theorem will then be a simple corollary of this lemma. *)\n\nFixpoint s_execute (st : state) (stack : list nat)\n (prog : list sinstr)\n : list nat :=\n match prog with\n | [] => stack\n | ins :: prog' => \n match ins with\n | SPush n => s_execute st (n :: stack) prog'\n | SLoad x => s_execute st (st x :: stack) prog'\n | SPlus => \n match stack with\n | na :: nb :: stack' => s_execute st (nb+na :: stack') prog'\n | _ => []\n end\n | SMinus => \n match stack with\n | na :: nb :: stack' => s_execute st (nb-na :: stack') prog'\n | _ => []\n end\n | SMult =>\n match stack with\n | na :: nb :: stack' => s_execute st (nb*na :: stack') prog'\n | _ => s_execute st stack prog'\n end\n end\n end.\n\nTheorem app_nil_end : forall (X : Type) (l : list X), \n l ++ [] = l. \nProof.\n intros. induction l as [|n l'].\n (*case l=nil*)\n simpl. auto.\n (*case l=n l'*)\n simpl. rewrite -> IHl'. auto.\nQed.\n(*\nLemma s_compile_app_split : forall (st:state) (l1 l2 :list sinstr) (stack: list nat),\n s_execute st stack (l1 ++ l2)\n = s_execute st (s_execute st stack l1) l2.\nProof.\n intro st.\n induction l2. rewrite app_nil_end. simpl. reflexivity.\n destruct a. \n induction l1. simpl. reflexivity.\n destruct a. simpl.\n simpl.\n simpl.\n \n induction l2. rewrite app_nil_end. reflexivity.\n destruct a.\n*)\n\nTheorem s_compile_correct : forall (st : state) (e : aexp),\n s_execute st [] (s_compile e) = [ aeval st e ].\nProof.\n intros. induction e.\n simpl. reflexivity.\n simpl. reflexivity.\n simpl. rewrite snoc_with_append.\n assert (H: s_execute st [] (s_compile e1 ++ s_compile e2 ++ [SPlus])\n = s_execute st ((s_execute st [] (s_compile e1)) ++ (s_execute st [] (s_compile e2))) [SPlus]).\n simpl. destruct ( s_execute st [] (s_compile e1) ++ s_execute st [] (s_compile e2)).\n simpl.\n rewrite IHe1. rewrite IHe2.\n\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (break_imp) *)\nModule BreakImp.\n\n(** Imperative languages such as C or Java often have a [break] or\n similar statement for interrupting the execution of loops. In this\n exercise we will consider how to add [break] to Imp.\n\n First, we need to enrich the language of commands with an\n additional case. *)\n\nInductive com : Type :=\n | CSkip : com\n | CBreak : com\n | CAss : id -> aexp -> com\n | CSeq : com -> com -> com\n | CIf : bexp -> com -> com -> com\n | CWhile : bexp -> com -> com.\n\nTactic Notation \"com_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"SKIP\" | Case_aux c \"BREAK\" | Case_aux c \"::=\" | Case_aux c \";\"\n | Case_aux c \"IFB\" | Case_aux c \"WHILE\" ].\n\nNotation \"'SKIP'\" :=\n CSkip.\nNotation \"'BREAK'\" :=\n CBreak.\nNotation \"x '::=' a\" :=\n (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" :=\n (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n (CIf c1 c2 c3) (at level 80, right associativity).\n\n(** Next, we need to define the behavior of [BREAK]. Informally,\n whenever [BREAK] is executed in a sequence of commands, it stops\n the execution of that sequence and signals that the innermost\n enclosing loop (if any) should terminate. If there aren't any\n enclosing loops, then the whole program simply terminates. The\n final state should be the same as the one in which the [BREAK]\n statement was executed.\n\n One important point is what to do when there are multiple loops\n enclosing a given [BREAK]. In those cases, [BREAK] should only\n terminate the _innermost_ loop where it occurs. Thus, after\n executing the following piece of code...\n X ::= 0;;\n Y ::= 1;;\n WHILE 0 <> Y DO\n WHILE TRUE DO\n BREAK\n END;;\n X ::= 1;;\n Y ::= Y - 1\n END\n ... the value of [X] should be [1], and not [0].\n\n One way of expressing this behavior is to add another parameter to\n the evaluation relation that specifies whether evaluation of a\n command executes a [BREAK] statement: *)\n\nInductive status : Type :=\n | SContinue : status\n | SBreak : status.\n\nReserved Notation \"c1 '/' st '||' s '/' st'\"\n (at level 40, st, s at level 39).\n\n(** Intuitively, [c / st || s / st'] means that, if [c] is started in\n state [st], then it terminates in state [st'] and either signals\n that any surrounding loop (or the whole program) should exit\n immediately ([s = SBreak]) or that execution should continue\n normally ([s = SContinue]).\n\n The definition of the \"[c / st || s / st']\" relation is very\n similar to the one we gave above for the regular evaluation\n relation ([c / st || s / st']) -- we just need to handle the\n termination signals appropriately:\n\n - If the command is [SKIP], then the state doesn't change, and\n execution of any enclosing loop can continue normally.\n\n - If the command is [BREAK], the state stays unchanged, but we\n signal a [SBreak].\n\n - If the command is an assignment, then we update the binding for\n that variable in the state accordingly and signal that execution\n can continue normally.\n\n - If the command is of the form [IF b THEN c1 ELSE c2 FI], then\n the state is updated as in the original semantics of Imp, except\n that we also propagate the signal from the execution of\n whichever branch was taken.\n\n - If the command is a sequence [c1 ; c2], we first execute\n [c1]. If this yields a [SBreak], we skip the execution of [c2]\n and propagate the [SBreak] signal to the surrounding context;\n the resulting state should be the same as the one obtained by\n executing [c1] alone. Otherwise, we execute [c2] on the state\n obtained after executing [c1], and propagate the signal that was\n generated there.\n\n - Finally, for a loop of the form [WHILE b DO c END], the\n semantics is almost the same as before. The only difference is\n that, when [b] evaluates to true, we execute [c] and check the\n signal that it raises. If that signal is [SContinue], then the\n execution proceeds as in the original semantics. Otherwise, we\n stop the execution of the loop, and the resulting state is the\n same as the one resulting from the execution of the current\n iteration. In either case, since [BREAK] only terminates the\n innermost loop, [WHILE] signals [SContinue]. *)\n\n(** Based on the above description, complete the definition of the\n [ceval] relation. *)\n\nInductive ceval : com -> state -> status -> state -> Prop :=\n | E_Skip : forall st,\n CSkip / st || SContinue / st\n (* FILL IN HERE *)\n\n where \"c1 '/' st '||' s '/' st'\" := (ceval c1 st s st').\n\nTactic Notation \"ceval_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"E_Skip\"\n (* FILL IN HERE *)\n ].\n\n(** Now the following properties of your definition of [ceval]: *)\n\nTheorem break_ignore : forall c st st' s,\n (BREAK;; c) / st || s / st' ->\n st = st'.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem while_continue : forall b c st st' s,\n (WHILE b DO c END) / st || s / st' ->\n s = SContinue.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem while_stops_on_break : forall b c st st',\n beval st b = true ->\n c / st || SBreak / st' ->\n (WHILE b DO c END) / st || SContinue / st'.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 3 stars, advanced, optional (while_break_true) *)\nTheorem while_break_true : forall b c st st',\n (WHILE b DO c END) / st || SContinue / st' ->\n beval st' b = true ->\n exists st'', c / st'' || SBreak / st'.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 4 stars, advanced, optional (ceval_deterministic) *)\nTheorem ceval_deterministic: forall (c:com) st st1 st2 s1 s2,\n c / st || s1 / st1 ->\n c / st || s2 / st2 ->\n st1 = st2 /\\ s1 = s2.\nProof.\n (* FILL IN HERE *) Admitted.\n\nEnd BreakImp.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (short_circuit) *)\n(** Most modern programming languages use a \"short-circuit\" evaluation\n rule for boolean [and]: to evaluate [BAnd b1 b2], first evaluate\n [b1]. If it evaluates to [false], then the entire [BAnd]\n expression evaluates to [false] immediately, without evaluating\n [b2]. Otherwise, [b2] is evaluated to determine the result of the\n [BAnd] expression.\n\n Write an alternate version of [beval] that performs short-circuit\n evaluation of [BAnd] in this manner, and prove that it is\n equivalent to [beval]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (add_for_loop) *)\n(** Add C-style [for] loops to the language of commands, update the\n [ceval] definition to define the semantics of [for] loops, and add\n cases for [for] loops as needed so that all the proofs in this file\n are accepted by Coq.\n\n A [for] loop should be parameterized by (a) a statement executed\n initially, (b) a test that is run on each iteration of the loop to\n determine whether the loop should continue, (c) a statement\n executed at the end of each loop iteration, and (d) a statement\n that makes up the body of the loop. (You don't need to worry\n about making up a concrete Notation for [for] loops, but feel free\n to play with this too if you like.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* <$Date: 2014-12-26 15:20:26 -0500 (Fri, 26 Dec 2014) $ *)\n\n", "meta": {"author": "Sooram", "repo": "Software-Foundations", "sha": "9c668f5c8395919645406855cdc78a214afdafd1", "save_path": "github-repos/coq/Sooram-Software-Foundations", "path": "github-repos/coq/Sooram-Software-Foundations/Software-Foundations-9c668f5c8395919645406855cdc78a214afdafd1/9. Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.18010665968560707, "lm_q1q2_score": 0.07336345806065361}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(** * Basic Extraction *)\n\n(** In its simplest form, program extraction from Coq is completely straightforward. *)\n\n(** First we say what language we want to extract into. Options are OCaml (the\n most mature), Haskell (which mostly works), and Scheme (a bit out\n of date). *)\n\nExtraction Language Ocaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import SfLib.\nRequire Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Have a look at this\n file now. *)\n\n(* ############################################################## *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n Extract Constant minus => \"( - )\".\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ############################################################## *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and somehow\n prints out the result. \n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we need a few\n more declarations to set up the right correspondence between Coq\n strings and lists of OCaml characters. *)\n\nRequire Import Ascii String.\nExtract Inductive ascii => char\n[\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))\"\n]\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))\".\nExtract Constant zero => \"'\\000'\".\nExtract Constant one => \"'\\001'\".\nExtract Constant shift =>\n \"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)\".\nExtract Inlined Constant ascii_dec => \"(=)\".\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nRequire Import Imp.\nRequire Import ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n<<\n\tocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n\t./impdriver\n>>\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ############################################################## *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. (Of\n course, the parser is not certified in any interesting sense,\n since we didn't prove anything about it.) *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "elfi", "repo": "sf", "sha": "169c89f59bec1415ddf8d290a40c533d19f862d5", "save_path": "github-repos/coq/elfi-sf", "path": "github-repos/coq/elfi-sf/sf-169c89f59bec1415ddf8d290a40c533d19f862d5/orig_files/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.1732882037945951, "lm_q1q2_score": 0.07321506926184204}} {"text": "(*|\n####################################################\nHow to define an automatically unfoldable definition\n####################################################\n\n:Link: https://stackoverflow.com/q/47594706\n|*)\n\n(*|\nQuestion\n********\n\nI sometimes want to define some shortcut for existing functions like\nin the following example:\n|*)\n\nParameter T : Set.\nParameter zero one : T.\nParameter f : T -> T -> option T.\nHypothesis f_unit : forall t, f zero t = None.\n\nDefinition g (t : T) := f t one.\n\n(*|\nHowever, this definition seems to be abstract since I cannot use\ntheorems about ``f`` on instances of ``g`` without first unfolding:\n|*)\n\nGoal g zero = None.\n unfold g. rewrite f_unit. reflexivity.\nQed.\n\n(*|\nIs there a way to mark definitions as automatically unfoldable?\n\n----\n\n**A:** Yes, I would like not to have to manually ``unfold``.\n\n**A:** You could allow ``simpl`` to expand the definition of ``g`` by\ndeclaring ``Arguments g t /.``\n\n**A:** Or define ``g`` as a \"parsing-only\" shorthand notation instead\nof a function. Something like: ``Notation \"'g' t\" := (f t one) (at\nlevel 0, parsing only).``\n\n**A:** Or ``Hint Unfold g.`` and then use ``autounfold`` tactic in the\nproof.\n\n**A:** Also, ssreflect can do it with with context patterns: ``Require\nImport ssreflect.`` then your goal can be proved by ``by rewrite [g\n_]f_unit.``. This ``[g _]`` pattern makes ``rewrite`` to unfold the\ndefinition of ``g``.\n|*)\n\n(*|\nAnswer\n******\n\nThere are a couple of ways to accomplish what you ask, and here is an\nexplanation of the ones I know:\n\n----\n\n1. Use an abbreviation. To quote `the reference manual\n `__:\n\n An *abbreviation* is a name, possibly applied to arguments,\n that denotes a (presumably) more complex expression.\n\n [...]\n\n Abbreviations are bound to an absolute name as an ordinary\n definition is, and they can be referred by qualified names too.\n\n Abbreviations are syntactic in the sense that they are bound to\n expressions which are not typed at the time of the definition\n of the abbreviation but at the time it is used.\n\n In your case, this would be\n|*)\n\nReset g. (* .none *)\nNotation g t := (f t one).\n\n(*|\n This is much like Daniel Schepler's suggestion of a ``Notation``,\n except that it does not reserve ``g`` as a global keyword.\n\n----\n\n2. Use ``setoid_rewrite``. Coq's ``setoid_rewrite`` tactic is similar\n to ``rewrite``, except that it looks for occurrences modulo δ\n (unfolding), can rewrite under binders, and a few other minor\n things.\n\n For your example, this is:\n|*)\n\nReset g. (* .none *)\nDefinition g (t : T) := f t one. (* .none *)\nRequire Import Coq.Setoids.Setoid.\nGoal g zero = None.\nProof.\n setoid_rewrite f_unit. reflexivity.\nQed.\n\n(*|\n----\n\n3. In some cases, you can use ``Set Keyed Unification`` and ``Declare\n Equivalent Keys``, though this does not work in your case (I've\n opened an issue `on GitHub here\n `__. This tells ``rewrite``\n to \"unfold\" one head constant to another, though it apparently\n isn't quite good enough to handle your case. There's a bit of\n documentation `on the relevant commit message\n `__,\n and an `open issue to add proper documentation\n `__.\n\n Here is an example this is useful:\n|*)\n\nReset Initial. (* .none *)\nParameter T : Set.\nParameter zero one: T.\nParameter f : T -> T -> option T.\nHypothesis f_unit : forall t, f zero t = None.\n\nDefinition g := f zero zero.\n\nSet Keyed Unification.\nGoal g = None.\nProof.\n Fail rewrite f_unit. (* .fails *)\n Declare Equivalent Keys g f.\n rewrite f_unit. reflexivity.\nQed.\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-to-define-an-automatically-unfoldable-definition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.17781086947804958, "lm_q1q2_score": 0.07242830602961706}} {"text": "(** * ImpParser: Lexing and Parsing in Coq *)\n\n(** The development of the Imp language in [Imp.v] completely ignores\n issues of concrete syntax -- how an ascii string that a programmer\n might write gets translated into abstract syntax trees defined by\n the datatypes [aexp], [bexp], and [com]. In this chapter, we\n illustrate how the rest of the story can be filled in by building\n a simple lexical analyzer and parser using Coq's functional\n programming facilities.\n\n It is not important to understand all the details here (and\n accordingly, the explanations are fairly terse and there are no\n exercises). The main point is simply to demonstrate that it can\n be done. You are invited to look through the code -- most of it\n is not very complicated, though the parser relies on some\n \"monadic\" programming idioms that may require a little work to\n make out -- but most readers will probably want to just skim down\n to the Examples section at the very end to get the punchline. *)\n\n\n(* DROP *)\n\n(* ################################################################# *)\n(** * Internals *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-implicit-arguments\".\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Maps.\nRequire Import Imp.\n\n(* ================================================================= *)\n(** ** Lexical Analysis *)\n\nDefinition isWhite (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (orb (beq_nat n 32) (* space *)\n (beq_nat n 9)) (* tab *)\n (orb (beq_nat n 10) (* linefeed *)\n (beq_nat n 13)). (* Carriage return. *)\n\nNotation \"x '<=?' y\" := (leb x y)\n (at level 70, no associativity) : nat_scope.\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (97 <=? n) (n <=? 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (andb (65 <=? n) (n <=? 90))\n (andb (97 <=? n) (n <=? 122)).\n\nDefinition isDigit (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (48 <=? n) (n <=? 57).\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n if isWhite c then\n white\n else if isAlpha c then\n alpha\n else if isDigit c then\n digit\n else\n other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n match s with\n | EmptyString => []\n | String c s => c :: (list_of_string s)\n end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n fold_right String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii)\n : list (list ascii) :=\n let tk := match acc with [] => [] | _::_ => [rev acc] end in\n match xs with\n | [] => tk\n | (x::xs') =>\n match cls, classifyChar x, x with\n | _, _, \"(\" =>\n tk ++ [\"(\"]::(tokenize_helper other [] xs')\n | _, _, \")\" =>\n tk ++ [\")\"]::(tokenize_helper other [] xs')\n | _, white, _ =>\n tk ++ (tokenize_helper white [] xs')\n | alpha,alpha,x =>\n tokenize_helper alpha (x::acc) xs'\n | digit,digit,x =>\n tokenize_helper digit (x::acc) xs'\n | other,other,x =>\n tokenize_helper other (x::acc) xs'\n | _,tp,x =>\n tk ++ (tokenize_helper tp [x] xs')\n end\n end %char.\n\nDefinition tokenize (s : string) : list string :=\n map string_of_list (tokenize_helper white [] (list_of_string s)).\n\nExample tokenize_ex1 :\n tokenize \"abc12==3 223*(3+(a+c))\" %string\n = [\"abc\"; \"12\"; \"==\"; \"3\"; \"223\";\n \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n \"a\"; \"+\"; \"c\"; \")\"; \")\"]%string.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Parsing *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Options With Errors *)\n\n(** An [option] type with error messages: *)\n\nInductive optionE (X:Type) : Type :=\n | SomeE : X -> optionE X\n | NoneE : string -> optionE X.\n\nImplicit Arguments SomeE [[X]].\nImplicit Arguments NoneE [[X]].\n\n(** Some syntactic sugar to make writing nested match-expressions on\n optionE more convenient. *)\n\nNotation \"'DO' ( x , y ) <== e1 ; e2\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => NoneE err\n end)\n (right associativity, at level 60).\n\nNotation \"'DO' ( x , y ) <-- e1 ; e2 'OR' e3\"\n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => e3\n end)\n (right associativity, at level 60, e2 at next level).\n\n(* ----------------------------------------------------------------- *)\n(** *** Generic Combinators for Building Parsers *)\n\nOpen Scope string_scope.\n\nDefinition parser (T : Type) :=\n list token -> optionE (T * list token).\n\nFixpoint many_helper {T} (p : parser T) acc steps xs :=\n match steps, p xs with\n | 0, _ =>\n NoneE \"Too many recursive calls\"\n | _, NoneE _ =>\n SomeE ((rev acc), xs)\n | S steps', SomeE (t, xs') =>\n many_helper p (t::acc) steps' xs'\n end.\n\n(** A (step-indexed) parser that expects zero or more [p]s: *)\n\nFixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=\n many_helper p [] steps.\n\n(** A parser that expects a given token, followed by [p]: *)\n\nDefinition firstExpect {T} (t : token) (p : parser T)\n : parser T :=\n fun xs => match xs with\n | x::xs' =>\n if string_dec x t\n then p xs'\n else NoneE (\"expected '\" ++ t ++ \"'.\")\n | [] =>\n NoneE (\"expected '\" ++ t ++ \"'.\")\n end.\n\n(** A parser that expects a particular token: *)\n\nDefinition expect (t : token) : parser unit :=\n firstExpect t (fun xs => SomeE(tt, xs)).\n\n(* ----------------------------------------------------------------- *)\n(** *** A Recursive-Descent Parser for Imp *)\n\n(** Identifiers: *)\n\nDefinition parseIdentifier (xs : list token)\n : optionE (id * list token) :=\nmatch xs with\n| [] => NoneE \"Expected identifier\"\n| x::xs' =>\n if forallb isLowerAlpha (list_of_string x) then\n SomeE (Id x, xs')\n else\n NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\nend.\n\n(** Numbers: *)\n\nDefinition parseNumber (xs : list token)\n : optionE (nat * list token) :=\nmatch xs with\n| [] => NoneE \"Expected number\"\n| x::xs' =>\n if forallb isDigit (list_of_string x) then\n SomeE (fold_left\n (fun n d =>\n 10 * n + (nat_of_ascii d -\n nat_of_ascii \"0\"%char))\n (list_of_string x)\n 0,\n xs')\n else\n NoneE \"Expected number\"\nend.\n\n(** Parse arithmetic expressions *)\n\nFixpoint parsePrimaryExp (steps:nat) \n (xs : list token)\n : optionE (aexp * list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (i, rest) <-- parseIdentifier xs ;\n SomeE (AId i, rest)\n OR DO (n, rest) <-- parseNumber xs ;\n SomeE (ANum n, rest)\n OR (DO (e, rest) <== firstExpect \"(\"\n (parseSumExp steps') xs;\n DO (u, rest') <== expect \")\" rest ;\n SomeE(e,rest'))\n end\n\nwith parseProductExp (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parsePrimaryExp steps' xs ;\n DO (es, rest') <==\n many (firstExpect \"*\" (parsePrimaryExp steps'))\n steps' rest;\n SomeE (fold_left AMult es e, rest')\n end\n\nwith parseSumExp (steps:nat) (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseProductExp steps' xs ;\n DO (es, rest') <==\n many (fun xs =>\n DO (e,rest') <--\n firstExpect \"+\"\n (parseProductExp steps') xs;\n SomeE ( (true, e), rest')\n OR DO (e,rest') <==\n firstExpect \"-\"\n (parseProductExp steps') xs;\n SomeE ( (false, e), rest'))\n steps' rest;\n SomeE (fold_left (fun e0 term =>\n match term with\n (true, e) => APlus e0 e\n | (false, e) => AMinus e0 e\n end)\n es e,\n rest')\n end.\n\nDefinition parseAExp := parseSumExp.\n\n(** Parsing boolean expressions: *)\n\nFixpoint parseAtomicExp (steps:nat)\n (xs : list token) :=\nmatch steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u,rest) <-- expect \"true\" xs;\n SomeE (BTrue,rest)\n OR DO (u,rest) <-- expect \"false\" xs;\n SomeE (BFalse,rest)\n OR DO (e,rest) <-- \n firstExpect \"not\" \n (parseAtomicExp steps') \n xs;\n SomeE (BNot e, rest)\n OR DO (e,rest) <-- \n firstExpect \"(\" \n (parseConjunctionExp steps') xs;\n (DO (u,rest') <== expect \")\" rest; \n SomeE (e, rest'))\n OR DO (e, rest) <== parseProductExp steps' xs;\n (DO (e', rest') <--\n firstExpect \"==\" \n (parseAExp steps') rest;\n SomeE (BEq e e', rest')\n OR DO (e', rest') <--\n firstExpect \"<=\" \n (parseAExp steps') rest;\n SomeE (BLe e e', rest')\n OR\n NoneE \n \"Expected '==' or '<=' after arithmetic expression\")\nend\n\nwith parseConjunctionExp (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <==\n parseAtomicExp steps' xs ;\n DO (es, rest') <==\n many (firstExpect \"&&\"\n (parseAtomicExp steps'))\n steps' rest;\n SomeE (fold_left BAnd es e, rest')\n end.\n\nDefinition parseBExp := parseConjunctionExp.\n\nCheck parseConjunctionExp.\n\nDefinition testParsing {X : Type}\n (p : nat -> \n list token ->\n optionE (X * list token))\n (s : string) :=\n let t := tokenize s in \n p 100 t.\n\n(*\nEval compute in \n testParsing parseProductExp \"x*y*(x*x)*x\".\n\nEval compute in \n testParsing parseConjunctionExp \"not((x==x||x*x<=(x*x)*x)&&x==x\". \n*)\n\n(** Parsing commands: *)\n\nFixpoint parseSimpleCommand (steps:nat) \n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u, rest) <-- expect \"SKIP\" xs;\n SomeE (SKIP, rest)\n OR DO (e,rest) <--\n firstExpect \"IF\" (parseBExp steps') xs;\n DO (c,rest') <==\n firstExpect \"THEN\" \n (parseSequencedCommand steps') rest;\n DO (c',rest'') <==\n firstExpect \"ELSE\" \n (parseSequencedCommand steps') rest';\n DO (u,rest''') <==\n expect \"END\" rest'';\n SomeE(IFB e THEN c ELSE c' FI, rest''')\n OR DO (e,rest) <--\n firstExpect \"WHILE\" \n (parseBExp steps') xs;\n DO (c,rest') <==\n firstExpect \"DO\" \n (parseSequencedCommand steps') rest;\n DO (u,rest'') <==\n expect \"END\" rest';\n SomeE(WHILE e DO c END, rest'')\n OR DO (i, rest) <==\n parseIdentifier xs;\n DO (e, rest') <==\n firstExpect \":=\" (parseAExp steps') rest;\n SomeE(i ::= e, rest')\n end\n\nwith parseSequencedCommand (steps:nat)\n (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (c, rest) <==\n parseSimpleCommand steps' xs;\n DO (c', rest') <--\n firstExpect \";\" \n (parseSequencedCommand steps') rest;\n SomeE(c ;; c', rest')\n OR\n SomeE(c, rest)\n end.\n\nDefinition bignumber := 1000.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n let tokens := tokenize str in\n parseSequencedCommand bignumber tokens.\n\n(* ################################################################# *)\n(** * Examples *)\n\n(*\nCompute parse \"\n IF x == y + 1 + 2 - y * 6 + 3 THEN\n x := x * 1;;\n y := 0\n ELSE\n SKIP\n END \".\n====>\n SomeE\n (IFB BEq (AId (Id 0))\n (APlus\n (AMinus (APlus (APlus (AId (Id 1)) (ANum 1)) (ANum 2))\n (AMult (AId (Id 1)) (ANum 6)))\n (ANum 3))\n THEN Id 0 ::= AMult (AId (Id 0)) (ANum 1);; Id 1 ::= ANum 0\n ELSE SKIP FI, [])\n*)\n\n(*\nCompute parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n====>\n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0)\n ELSE SKIP FI;;\n SKIP\n END;;\n Id 1 ::= AId (Id 0),\n [])\n*)\n\n(*\nCompute parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n=====>\n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);;\n Id 2 ::= AId (Id 0)\n ELSE SKIP\n FI;;\n SKIP\n END;;\n Id 1 ::= AId (Id 0),\n []).\n*)\n\n(* /DROP *)\n\n(** $Date: 2017-04-26 17:33:43 -0400 (Wed, 26 Apr 2017) $ *)\n", "meta": {"author": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/sf-experiment/ImpParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.15203224162217427, "lm_q1q2_score": 0.071863128528367}} {"text": "(** * Induction: Proof by Induction *)\n \n\n(** The next line imports all of our definitions from the\n previous chapter. *)\n\nRequire Export Basics.\n\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n into [Basics.vo]. (This is like making a .class file from a .java\n file, or a .o file from a .c file.)\n \n Here are two ways to compile your code:\n \n - CoqIDE:\n \n Open [Basics.v].\n In the \"Compile\" menu, click on \"Compile Buffer\".\n \n - Command line:\n \n Run [coqc Basics.v]\n\n *)\n\n(* ###################################################################### *)\n(** * Naming Cases *)\n\n(** The fact that there is no explicit command for moving from\n one branch of a case analysis to the next can make proof scripts\n rather hard to read. In larger proofs, with nested case analyses,\n it can even become hard to stay oriented when you're sitting with\n Coq and stepping through the proof. (Imagine trying to remember\n that the first five subgoals belong to the inner case analysis and\n the remaining seven cases are what remains of the outer one...)\n Disciplined use of indentation and comments can help, but a better\n way is to use the [Case] tactic. *)\n\n(* [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- you can just skip\n over the definition to the example that follows. It uses some\n facilities of Coq that we have not discussed -- the string\n library (just for the concrete syntax of quoted strings) and the\n [Ltac] command, which allows us to declare custom tactics. Kudos\n to Aaron Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n(** Here's an example of how [Case] is used. Step through the\n following proof and observe how the context changes. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\". (* <----- here *)\n reflexivity.\n Case \"b = false\". (* <---- and here *)\n rewrite <- H. \n reflexivity. \nQed.\n\n(** [Case] does something very straightforward: It simply adds a\n string that we choose (tagged with the identifier \"Case\") to the\n context for the current goal. When subgoals are generated, this\n string is carried over into their contexts. When the last of\n these subgoals is finally proved and the next top-level goal\n becomes active, this string will no longer appear in the context\n and we will be able to see that the case where we introduced it is\n complete. Also, as a sanity check, if we try to execute a new\n [Case] tactic while the string left by the previous one is still\n in the context, we get a nice clear error message.\n\n For nested case analyses (e.g., when we want to use a [destruct]\n to solve a goal that has itself been generated by a [destruct]),\n there is an [SCase] (\"subcase\") tactic. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2) *)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c H.\n destruct c.\n Case \"c = true\".\n reflexivity.\n Case \"c = false\".\n rewrite <- H.\n destruct b.\n SCase \"b = false\".\n reflexivity.\n reflexivity.\n Qed.\n\n(** There are no hard and fast rules for how proofs should be\n formatted in Coq -- in particular, where lines should be broken\n and how sections of the proof should be indented to indicate their\n nested structure. However, if the places where multiple subgoals\n are generated are marked with explicit [Case] tactics placed at\n the beginning of lines, then the proof will be readable almost no\n matter what choices are made about other aspects of layout.\n\n This is a good place to mention one other piece of (possibly\n obvious) advice about line lengths. Beginning Coq users sometimes\n tend to the extremes, either writing each tactic on its own line\n or entire proofs on one line. Good style lies somewhere in the\n middle. In particular, one reasonable convention is to limit\n yourself to 80-character lines. Lines longer than this are hard\n to read and can be inconvenient to display and print. Many\n editors have features that help enforce this. *)\n\n(* ###################################################################### *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left using a simple argument. The fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... cannot be proved in the same simple way. Just applying\n [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. We could use [destruct n'] to\n get one step further, but since [n] can be arbitrarily large, if we\n try to keep on like this we'll never be done. *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* so far so good... *)\n Case \"n = S n'\".\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** To prove such facts -- indeed, to prove most interesting\n facts about numbers, lists, and other inductively defined sets --\n we need a more powerful reasoning principle: _induction_.\n\n Recall (from high school) the principle of induction over natural\n numbers: If [P(n)] is some proposition involving a natural number\n [n] and we want to show that P holds for _all_ numbers [n], we can\n reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same but the order is backwards: we\n begin with the goal of proving [P(n)] for all [n] and break it\n down (by applying the [induction] tactic) into two separate\n subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n n')]. Here's how this works for the theorem we are trying to\n prove at the moment: *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. In the first branch, [n] is replaced by [0] and\n the goal becomes [0 + 0 = 0], which follows by simplification. In\n the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n n'] is added to the context (with the name [IHn'], i.e., the\n Induction Hypothesis for [n']). The goal in this case becomes [(S\n n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in\n turn follows from the induction hypothesis. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (basic_induction) *)\n\n(** Prove the following lemmas using induction. You might need\n previously proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [|n'].\n Case \"n' = 0\".\n reflexivity.\n Case \"n' = S n'\".\n simpl. rewrite -> IHn'.\n reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat, \n S (n + m) = n + (S m).\nProof. \n intros n m.\n induction n as [|n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity.\n Qed.\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m.\n induction n as [|n'].\n Case \"n = 0\".\n simpl. rewrite -> plus_0_r. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm.\n reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p.\n induction n as [|n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity.\n Qed.\n\n\n(** **** Exercise: 2 stars (double_plus) *)\n\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof. \n intros n.\n induction n as [|n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm.\n reflexivity. Qed.\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics\n [destruct] and [induction]. \n\n(* destruct performs case analysis, where as induction also provides us with \n an induction hypothesis that we can use for rewriting.*)\n\n*)\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Proofs Within Proofs *)\n\n\n(** In Coq, as in informal mathematics, large proofs are very\n often broken into a sequence of theorems, with later proofs\n referring to earlier theorems. Occasionally, however, a proof\n will need some miscellaneous fact that is too trivial (and of too\n little general interest) to bother giving it its own top-level\n name. In such cases, it is convenient to be able to simply state\n and prove the needed \"sub-theorem\" right at the point where it is\n used. The [assert] tactic allows us to do this. For example, our\n earlier proof of the [mult_0_plus] theorem referred to a previous\n theorem named [plus_O_n]. We can also use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). \n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (Note that we could also name the assertion with\n [as] just as we did above with [destruct] and [induction], i.e.,\n [assert (0 + n = n) as H]. Also note that we mark the proof of\n this assertion with a [Case], both for readability and so that,\n when using Coq interactively, we can see when we're finished\n proving the assertion by observing when the [\"Proof of assertion\"]\n string disappears from the context.) The second goal is the same\n as the one at the point where we invoke [assert], except that, in\n the context, we have the assumption [H] that [0 + n = n]. That\n is, [assert] generates one subgoal where we must prove the\n asserted fact and a second subgoal where we can use the asserted\n fact to make progress on whatever we were trying to prove in the\n first place. *)\n\n(** Actually, [assert] will turn out to be handy in many sorts of\n situations. For example, suppose we want to prove that [(n + m)\n + (p + q) = (m + n) + (p + q)]. The only difference between the\n two sides of the [=] is that the arguments [m] and [n] to the\n first inner [+] are swapped, so it seems we should be able to\n use the commutativity of addition ([plus_comm]) to rewrite one\n into the other. However, the [rewrite] tactic is a little stupid\n about _where_ it applies the rewrite. There are three uses of\n [+] here, and it turns out that doing [rewrite -> plus_comm]\n will affect only the _outer_ one. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)...\n it seems like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To get [plus_comm] to apply at the point where we want it, we can\n introduce a local lemma stating that [n + m = m + n] (for\n the particular [m] and [n] that we are talking about here), prove\n this lemma using [plus_comm], and then use this lemma to do the\n desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Exercise: 4 stars (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction. *)\n\nTheorem plus_swap : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n assert(H : m + (n + p) = (m + n) + p).\n Case \"Assertion\".\n rewrite -> plus_assoc. reflexivity.\n rewrite -> H. rewrite -> plus_assoc.\n assert(H2 : n + m = m + n). rewrite -> plus_comm. reflexivity.\n rewrite -> H2. reflexivity. Qed.\n\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one.) You may find that [plus_swap] comes in\n handy. *)\n\nTheorem multZero : forall n : nat, n * 0 = 0.\nProof.\n intros n.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity.\n Qed.\n \nLemma mult_comm_helper : forall m n : nat, m * S n = m + m * n.\nProof.\n intros m n.\n induction m as [| m'].\n Case \"m = 0\". reflexivity.\n Case \"m = S m'\".\n simpl. rewrite -> IHm'. \n rewrite -> plus_swap. reflexivity.\n Qed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros m n.\n induction m as [ | m'].\n Case \"m = 0\". simpl. rewrite -> multZero. reflexivity.\n Case \"m = S m'\". simpl.\n rewrite -> mult_comm_helper. rewrite -> IHm'.\n reflexivity.\n Qed.\n\n\n(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)\n(** Prove the following simple fact: *)\n(*TODO: discuss this in class*)\nTheorem evenb_n_oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n intros n.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". \n assert(H:evenb(S(S(n'))) = evenb n'). reflexivity.\n rewrite -> H. rewrite -> IHn'. \n assert(H2: forall x, negb(negb(x)) = x).\n intros x. destruct x as []. reflexivity. reflexivity.\n rewrite -> H2. reflexivity.\n Qed.\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before hacking!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\nProof.\n intros n.\n induction n as [|n']. reflexivity.\n simpl. rewrite <- IHn'. reflexivity.\n Qed.\n \n\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n intros n. simpl. reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n intros b.\n destruct b as [|b']. reflexivity.\n reflexivity. Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat, \n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n intros n m p H.\n induction p as [|p'].\n Case \"p = 0\". simpl. rewrite -> H. reflexivity.\n Case \"p = S p'\".\n simpl. rewrite -> IHp'. reflexivity.\n Qed.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n intros n.\n simpl. reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros n. simpl. rewrite -> plus_0_r.\n reflexivity. Qed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros b c.\n destruct b as [|b'].\n destruct c as [|c'].\n simpl. reflexivity.\n simpl. reflexivity.\n simpl. reflexivity.\n Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros n m p.\n induction n as [|n'].\n simpl. reflexivity.\n simpl. rewrite -> IHn'. rewrite -> plus_assoc.\n reflexivity.\n Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p.\n induction n as [|n'].\n simpl. reflexivity.\n simpl. rewrite -> IHn'.\n rewrite -> mult_plus_distr_r.\n reflexivity. \n Qed.\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\n(** Prove the following theorem. Putting [true] on the left-hand side\nof the equality may seem odd, but this is how the theorem is stated in\nthe standard library, so we follow suit. Since rewriting \nworks equally well in either direction, we will have no \nproblem using the theorem no matter which way we state it. *)\n\nTheorem beq_nat_refl : forall n : nat, \n true = beq_nat n n.\nProof.\n intros n.\n induction n as [|n']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity.\n Qed.\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to. More precisely,\n [replace (t) with (u)] replaces (all copies of) expression [t] in\n the goal by expression [u], and generates [t = u] as an additional\n subgoal. This is often useful when a plain [rewrite] acts on the wrong\n part of the goal. \n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. \n*)\n\nTheorem plus_swap' : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n replace (m + (n + p)) with ((m + n) + p).\n rewrite -> plus_assoc. \n replace (n+m) with (m+n). reflexivity.\n rewrite -> plus_comm. reflexivity.\n rewrite -> plus_assoc. reflexivity.\n Qed.\n\n(** **** Exercise: 3 stars (binary_commute) *)\n(** Recall the [increment] and [binary-to-unary] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that these functions commute -- that is, incrementing a binary\n number and then converting it to unary yields the same result as\n first converting it to unary and then incrementing.\n\n (Before you start working on this exercise, please copy the\n definitions from your solution to the [binary] exercise here so\n that this file can be graded on its own. If you find yourself\n wanting to change your original definitions to make the property\n easier to prove, feel free to do so.) *)\n\nInductive bin : Type := \n | BinO : bin\n | Odd : bin -> bin\n | Even : bin -> bin.\n(** [] *)\n\nFixpoint inc (n : bin) : bin := \n match n with\n |BinO => Odd BinO\n |Even n => Odd n\n |Odd n => Even(inc n)\n end.\n\nFixpoint binToUnary(n : bin) : nat := \n match n with\n |BinO => 0\n |Even n => 2 * (binToUnary n) \n |Odd n => 1 + 2 * binToUnary n \n end. \nLemma succXPlusOne : forall x : nat, S x = x + 1.\nProof.\n intros x. rewrite -> plus_comm. simpl.\n reflexivity.\n Qed.\n\n(*TODO: discuss this in class*)\nTheorem BinToUnaryCorrect : forall n : bin, binToUnary(inc n) = binToUnary(n) + 1.\nProof.\n intros n.\n induction n as [|n' | n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = Even n'\". \n simpl. rewrite -> plus_n_Sm. rewrite -> plus_0_r. rewrite -> plus_0_r.\n rewrite -> IHn'. rewrite -> plus_swap. rewrite -> plus_assoc. rewrite -> plus_assoc.\n assert(H: forall x, x + 1 + 1 = x + 2).\n intros x. rewrite -> plus_comm. rewrite -> plus_swap. simpl. reflexivity.\n rewrite -> H. reflexivity.\n simpl. rewrite -> plus_n_Sm. rewrite -> plus_0_r. \n rewrite -> succXPlusOne. rewrite -> plus_assoc. reflexivity.\n Qed.\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n the previous exercise to complete this one.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, it is not true!\n Explain what the problem is.\n\n (c) Define a function [normalize] from binary numbers to binary\n numbers such that for any binary number b, converting to a\n natural and then back to binary yields [(normalize b)]. Prove\n it.\n\n Again, feel free to change your earlier definitions if this helps\n here. \n*)\n\nFixpoint natToBin(n : nat) : bin :=\nmatch n with\n |O => BinO\n |S n' => inc(natToBin n')\nend.\n \nTheorem natToBinCorrect : forall n : nat, binToUnary(natToBin n) = n.\nProof.\n intros n.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> BinToUnaryCorrect. rewrite -> IHn'. rewrite -> plus_comm.\n reflexivity.\n Qed.\n\n\nFixpoint normalize (b : bin) : bin := \nmatch b with\n |BinO => BinO\n |Even(b') => match normalize b' with\n |BinO => BinO\n |n => Even(Even n)\n end\n |Odd(b') => Odd(normalize b')\nend.\n\nTheorem L : forall n, natToBin(n + n) = normalize(Even (natToBin n)).\nProof.\n intros. induction n as [|n'].\n simpl. reflexivity.\n simpl. destruct (normalize(inc(natToBin n'))).\n\nTheorem binToNatCorrect : forall b : bin, natToBin(binToUnary b) = normalize b.\nProof.\n intros b.\n induction b as [|n|n].\n reflexivity.\n Case \"b = Odd n\". simpl. rewrite -> plus_0_r.\n rewrite -> L. simpl. rewrite -> IHn. reflexivity.\n Case \"b = Odd n\". simpl. rewrite -> plus_0_r.\n rewrite -> L. rewrite -> IHn. reflexivity.\n Qed.\n\n(*\nTheorem NPlusNEven : forall n, natToBin(n + n) = Even (natToBin n).\nProof.\n intros. induction n as [|n'].\n Admitted.\n\nTheorem binToNatCorrect : forall b : bin, natToBin(binToUnary b) = b.\nProof.\n intros b.\n induction b as [|n|n].\n reflexivity.\n Case \"b = Odd n\". simpl. rewrite -> plus_0_r.\n rewrite -> NPlusNEven. simpl. rewrite -> IHn. reflexivity.\n Case \"b = Odd n\". simpl. rewrite -> plus_0_r.\n rewrite -> NPlusNEven. rewrite -> IHn. reflexivity.\n Qed.*)\n\n(* ###################################################################### *)\n(** * Advanced Material *)\n\n(** ** Formal vs. Informal Proof *)\n\n(** \"Informal proofs are algorithms; formal proofs are code.\" *)\n\n(** The question of what, exactly, constitutes a \"proof\" of a\n mathematical claim has challenged philosophers for millenia. A\n rough and ready definition, though, could be this: a proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true.\n That is, a proof is an act of communication.\n\n Now, acts of communication may involve different sorts of readers.\n On one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is a simple mechanical check that\n [P] can be derived from a certain set of formal logical rules, and\n the proof is a recipe that guides the program in performing this\n check. Such recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n thus necessarily _informal_. Here, the criteria for success are\n less clearly specified. A \"good\" proof is one that makes the\n reader believe [P]. But the same proof may be read by many\n different readers, some of whom may be convinced by a particular\n way of phrasing the argument, while others may not be. One reader\n may be particularly pedantic, inexperienced, or just plain\n thick-headed; the only way to convince them will be to make the\n argument in painstaking detail. But another reader, more familiar\n in the area, may find all this detail so overwhelming that they\n lose the overall thread. All they want is to be told the main\n ideas, because it is easier to fill in the details for themselves.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader. In practice, however,\n mathematicians have developed a rich set of conventions and idioms\n for writing about complex mathematical objects that, within a\n certain community, make communication fairly reliable. The\n conventions of this stylized form of communication give a fairly\n clear standard for judging proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can ignore\n the informal ones! Formal proofs are useful in many ways, but\n they are _not_ very efficient ways of communicating ideas between\n human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity. \n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this as a proof. For a human,\n however, it is difficult to make much sense of it. If you're used\n to Coq you can probably step through the tactics one after the\n other in your mind and imagine the state of the context and goal\n stack at each point, but if the proof were even a little bit more\n complicated this would be next to impossible. Instead, a\n mathematician might write it something like this: *)\n(** - _Theorem_: For any [n], [m] and [p],\n n + (m + p) = (n + m) + p.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show \n 0 + (m + p) = (0 + m) + p. \n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n n' + (m + p) = (n' + m) + p.\n We must show\n (S n') + (m + p) = ((S n') + m) + p.\n By the definition of [+], this follows from\n S (n' + (m + p)) = S ((n' + m) + p),\n which is immediate from the induction hypothesis. [] *)\n\n(** The overall form of the proof is basically similar. This is\n no accident: Coq has been designed so that its [induction] tactic\n generates the same sub-goals, in the same order, as the bullet\n points that a mathematician would write. But there are\n significant differences of detail: the formal proof is much more\n explicit in some ways (e.g., the use of [reflexivity]) but much\n less explicit in others (in particular, the \"proof state\" at any\n given point in the Coq proof is completely implicit, whereas the\n informal proof reminds the reader several times where things\n stand). *)\n\n(** Here is a formal proof that shows the structure more\n clearly: *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n']. \n Case \"n = 0\".\n reflexivity. \n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, advanced (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative.\n \n Proof: Proof by induction on n:\n Case (n = 0): We have \"0 + m = m + 0\", which simplifies to \"m = m\"\n Case (n = n' + 1): We have \"(n' + 1) + m = m + (n' + 1)\"\n By the definition of plus, we have \"S(n' + m) = m + S n'\" \n By the induction hypothesis, we have \"S(m + n') = m + S n'\"\n By Theorem plus_n_Sm, we have \"m + S n' = m + S n'\"\n\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n \n Theorem: [true = beq_nat n n] for any [n].\n \n Proof: (* FILL IN HERE *)\n[]\n *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/software_foundations/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.19682619657611936, "lm_q1q2_score": 0.07073227787769132}} {"text": "(*|\n########################################################\nHow to import the library ``Coq.Arith.PeanoNat`` in Coq?\n########################################################\n\n:Link: https://stackoverflow.com/q/36621752\n|*)\n\n(*|\nQuestion\n********\n\nI need to use the part of the standard library called\n``Coq.Arith.PeanoNat``\n(https://coq.inria.fr/library/Coq.Arith.PeanoNat.html).\n\nI've tried either importing the entire Arith library or just this\nmodule, but I can't use it either way.\n\nEvery other library I've tried works just fine. When I do ``Require\nImport Bool.`` I compile and I can use it correctly. Upon ``Print\nBool.`` I can take a look at all the functions inside in the next\nformat:\n\n.. code-block::\n\n Module\n Bool\n := Struct\n Definition...\n .\n .\n .\n End\n\nWhen I do either ``Require Import Arith.PeanoNat.`` or ``Require\nImport Arith.`` I get this as immediate output:\n\n.. code-block::\n\n [Loading ML file z_syntax_plugin.cmxs ... done]\n [Loading ML file quote_plugin.cmxs ... done]\n [Loading ML file newring_plugin.cmxs ... done]\n Grammar extension: in [tactic:simple_tactic], some rule has been masked\n Grammar extension: in [tactic:simple_tactic], some rule has been masked\n Grammar extension: in [tactic:simple_tactic], some rule has been masked\n Grammar extension: in [tactic:simple_tactic], some rule has been masked\n Grammar extension: in [tactic:simple_tactic], some rule has been masked\n\nWhen I ask Coq ``Print Arith.PeanoNat`` it outputs: ``Module Arith :=\nStruct End``, it seems to be empty. When I try to use anything from\nthe library, for example ``le_le`` under boolean comparisons, I get\nthe standard ``Error: leb_le not a defined object.`` I have updated\nCoq and the libraries, and I have no idea of what might be going on\nhere. I'd appreciate your input in fixing this library problem.\n|*)\n\n(*|\nAnswer\n******\n\nIf I am not mistaken, ``Require`` is the keyword to load a file.\n``Import`` has to do with managing name spaces. Often they are used\ntogether, as in ``Require Import PeanoNat.``, but they are really\ndoing two different things.\n\nWhen coq files (``DirName/FileName.vo``) are loaded with ``Require``,\nit is as if the contents of ``FileName.vo`` is wrapped in ``Module\nDirName.FileName ... End.`` Everyting defined in the file is then\naccessed with ``DirName.FileName.Name``.\n\nThe file can itself have modules ``M`` inside of it, and to get to\n``M``'s contents, one has to type\n``DirName.FileName.ModuleName.Name1`` etc.\n\n``Import`` is used to get all the definitions up to the top level. By\ndoing ``Import DirName.FileName.ModuleName`` the module ``Name1`` is\nnow imported to the top level, and can be referenced without the long\npath.\n\nIn your example above, the file ``Arith/PeanoNat.vo`` defines the\nmodule ``Nat``. Actually, that is all it defines. So if you do\n``Require Import Arith.PeanoNat`` you get ``PeanoNat.Nat`` at the top\nlevel. And then ``Import PeanoNat.Nat`` will bring ``Nat`` to the top\nlevel. Note that you can't do ``Require Import PeanoNat.Nat`` because\nit is no ``.vo`` file.\n\nCoq can sometimes find a ``.vo`` file without you having to specify\nthe whole path, so you can also do ``Require Import PeanoNat.`` and\ncoq will find the file. If you wonder where it found it, do ``Locate\nPeanoNat``.\n|*)\n\nRequire Import PeanoNat.\nLocate PeanoNat. (* .unfold *)\n\n(*|\nAnother ``Nat`` is also available from another place than\n``PeanoNat``.\n|*)\n\nReset Initial. (* .none *)\nRequire Import Nat.\nLocate Nat. (* .unfold *)\n\n(*|\nSo, you don't ``Import`` a library, you ``Require`` it. You use\n``Import`` to not have to use the full path name. I hope this helps\nyou debug what is happening.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-to-import-the-library-coq-arith-peanonat-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.14223190046381007, "lm_q1q2_score": 0.07056036817401819}} {"text": "(** **** Exercise: 3 stars, standard (binary)\n\n Après la représentation unaire des nombres naturels, nous proposons\n une représentation Binaire plus efficace en traitant un nombre Binaire\n comme une séquence de constructeurs [zero] et [un] (représentant 0 et 1),\n terminée par un [zeroFinal] ou un [unFinal]. En comparaison, dans la\n représentation unaire, un nombre est une séquence de [S] terminée par un [O].\n\n décimal binaire unaire\n 0 0 O\n 1 1 S O\n 2 (0 1) S (S O)\n 3 (1 1) S (S (S O))\n 4 0 (0 1) S (S (S (S O)))\n 5 1 (0 1) S (S (S (S (S O))))\n 6 0 (1 1) S (S (S (S (S (S O)))))\n 7 1 (1 1) S (S (S (S (S (S (S O))))))\n 8 0 (0 (0 1)) S (S (S (S (S (S (S (S O)))))))\n\n Notez que le bit d'ordre inférieur est à gauche et le bit d'ordre supérieur\n est à droite -- à l'opposé de la façon dont les nombres binaires\n sont habituellement écrits. Ce choix facilite leur manipulation.\n\n Enfin, il peut exister plusieurs représentations binaires d'un entier naturel :\n il suffit d'ajouter des zéros à droite.\n**)\n\n(* Préambule *)\n(* Quelques lemmes et définitions utiles, certaines donnant lieu à des tactiques standards. \n * Ces tactiques standards traitent de l'absurdité et de l'égalité. Elle sont à connaître :\n * - exfalso,\n * - f_equal\n * - discriminate.\n * On s'aperçoit que toutes ces tactiques peuvent s'exprimer en utilisant la tactique primitive\n * case, et quelques lemmes pratiques (appliqués avec apply ou refine).\n *)\n\n(* Arguments implicites.\n * Il est possible de déclarer des paramètres entre accolades au lieu de parenthèses.\n * Ces paramètres donnent des arguments implicites : Coq les devine par lui-même.\n * Si on veut utiliser tous les arguments d'une fonction f, écrire l'appel ainsi :\n * - (@f args).\n *)\n\n(* Lors de définitions par cas, il arrive que certains cas soient absurdes.\n On utilise alors la fonction casImpossible. *) \nDefinition casImpossible{T : Type}(H : False) : T.\n case H. (* voir le principe récursif False_rect. *)\nDefined.\n\nPrint False_ind.\nPrint False_rect.\n\nPrint casImpossible.\n\n(* alternative utilisant exfalso et False_rect. *)\nDefinition casImpossible'{T : Type}(H : False) : T.\n exfalso.\n exact H.\nDefined.\n\nPrint casImpossible'.\n\n(* Cette notation permet de masquer la preuve de l'absurdité (du Faux). *)\nNotation \"'Impossible'\" := (casImpossible _) : type_scope.\n\n(* Très souvent, l'absurdité vient d'une égalité impossible \n * entre deux termes de structures différentes. *) \n\nLtac egaliteImpossible eg := (apply casImpossible; discriminate eg).\n\n(* discriminate est une tactique élaborée. Elle utilise la préservation \n * de l'égalité par les fonctions pour déduire le Faux, à partir d'une égalité impossible.\n * La préservation de l'égalité est exploitée par la tactique f_equal.\n *)\n\nLemma preservationFonctionnelleEgalite :\n forall {A B : Type}{F : A -> B},\n forall x y, x = y -> F x = F y.\nProof.\n intros A B F x y eg.\n case eg.\n reflexivity.\nQed.\n\n(* Plutôt que \"case eg\", on peut utiliser \"rewrite eg\".\n * rewrite est une tactique plus élaborée fondée sur l'égalité et sa décomposition via case.\n *)\nLemma preservationFonctionnelleEgalite' :\n forall {A B : Type}{F : A -> B},\n forall x y, x = y -> F x = F y.\nProof.\n intros A B F x y eg.\n (* rewrite eg. (* équivalent à case (eq_sym eg) \n (où eq_sym est le lemme de symmétrie / égalité *) \n *)\n rewrite <- eg. (* équivalent à case eg *) \n reflexivity.\nQed.\n\n(* Tactique f_equal := apply preservationFonctionnelleEgalite *)\n\nLtac egaliteFctn := apply preservationFonctionnelleEgalite.\n\n(* Vers la discrimination :\n * si x = y, (P x) et non (P y), alors on a une contradiction. \n * On utilise la préservation de l'égalité par un prédicat (une fonction vers Prop).\n *)\n\nLemma discrimination :\n forall {A : Type},\n forall x y,\n x = y -> (exists (P : A -> Prop), (P x) /\\ (P y -> False)) -> False.\nProof.\n intros A x y eg.\n case eg.\n intro H.\n case H as [P [Px abs]].\n apply (abs Px).\nQed.\n\n(* Tactique pour discriminer une égalité fausse :\n * - appliquer discrimination\n * - définir (P n) par : si n vaut x alors True sinon False. \n * Le test relativement à x se fait par filtrage, sans utiliser l'égalité.\n * eg : x = y\n * discriminant := \n * (fun n => match n with (filtrage étendu)\n | x => True (x à remplacer par la valeur)\n | _ => False\n end) \n *)\nLtac discriminer eg discriminant :=\n apply (discrimination _ _ eg); \n simple refine (ex_intro _ _ _);\n [ exact discriminant\n | simpl; tauto].\n\nExample disc_5_6 : 5 = 6 -> False.\nintro eg.\ndiscriminer eg (fun n => match n with \n | 5 => True \n | _ => False\n end). \nQed.\n\nPrint disc_5_6. (* Noter que le filtrage est plus élémentaire que dans l'écriture au-dessus. \n * Il décrit tous les sous-termes de 5. \n *)\n\n(* discriminate produit automatiquement le discriminant. *)\n\nExample disc_5_6' : 5 = 6 -> False.\nintro eg.\ndiscriminate eg. \nQed.\n\nPrint disc_5_6'. (* discriminate a effectivement produit automatiquement le discriminant. *)\n\n(* Fin du préambule *)\n\n(* Définition permettant d'obtenir une correspondance bi-univoque *)\nInductive SorteBinaire : Type\n := T1 | N.\n\n(* N ::= 0 | T1 (N = forme normale)\n T1 ::= 1 | 0.T1 | 1 T1 (T1 = se termine par un 1)\n *)\nInductive Binaire : SorteBinaire -> Type :=\n | zeroFinal : Binaire N\n | unFinal : Binaire T1\n | double : Binaire T1 -> Binaire T1\n | successeurDouble : Binaire T1 -> Binaire T1\n | formeNormale : Binaire T1 -> Binaire N.\n\n(** nat comme Binaire forment des algèbres initiales.\n * - nat : signature Nat := (0 : nat), (S : nat -> nat)\n * - Binaire : signature Bin avec deux sortes N et T1\n * - cinq opérations := (OF : Binaire N), (1F : Binaire T1), \n * (double : Binaire T1 -> Binaire T1), (successeurDouble: Binaire T1 -> Binaire T1), \n * (fn : Binaire T1 -> Binaire N)\n *\n * Propriété importante des algèbres initiales :\n - il existe un unique morphisme d'une algèbre initiale vers une algèbre sur la même signature.\n *\n * Une algèbre est donnée par des ensembles (un par sorte) et des fonctions sur ces ensembles\n * (une par opération de la sorte, en respectant le type).\n *\n * L'algèbre initiale est formée des termes, soit les arbres formés à partir des opérations, \n * en respectant le typage.\n * \n * Signature Bin\n * On interprète N par nat et T1 par nat* (nat - 0). Comme nat* est isomorphe à nat,\n * on simplifie : on interprète T1 par nat.\n * (nat/N, nat/T1) est une algèbre sur Bin.\n * Signature Nat\n * Binaire N est une algèbre sur Nat, Binaire T1 est une algèbre sur Nat.\n *\n * La propriété d'initialité permet de relier nat et Binaire.\n * - si (nat/N, nat/T1) est une algèbre sur Bin, \n * alors il existe un unique morphisme BN := (BN N, BN T1) \n * sur Bin de Binaire vers (nat/N, nat/T1).\n * - si (Binaire s) est une algèbre sur Nat, \n * alors il existe un unique morphisme (NB s) sur Nat de nat vers (Binaire s).\n *\n * Pour montrer qu'il s'agit d'isomorphismes, il suffit de montrer que \n * - chaque composante (BN s) est aussi un morphisme sur Nat de (Binaire s) vers nat/s,\n * - (NB N, NB T1) est aussi un morphisme sur Bin de (nat/N, nat/T1) vers Bin.\n * NB o BN est alors un morphisme sur Bin de Binaire vers Binaire : \n * par unicité, il est égal à l'identité.\n * De même (BN s) o (NB s) est un morphisme sur Nat de nat vers nat : \n * par unicité, il est égal à l'identité. \n*)\n\nLocal Notation \"'BO'\" := zeroFinal : type_scope.\nLocal Notation \"'I'\" := (unFinal) : type_scope.\nLocal Notation \"'O,' x\" := (double x) (at level 30, right associativity) : type_scope.\nLocal Notation \"'I,' x\" := (successeurDouble x) (at level 30, right associativity) : type_scope.\nLocal Notation \"'B' x\" := (formeNormale x) (at level 30, right associativity) : type_scope.\n\nCheck (B O,I,O,I).\nCheck (O,I,O,I).\nCheck (BO).\n\n(* On cherche à définir les opérations de la signature Bin dans (nat/N, nat/T1) \n * et celles de la signature Nat dans (Binaire s) (s : sorte). \n * Rappel\n * Comme il y a deux sortes, on associe deux ensembles, côté nat :\n * - sorte N : nat\n * - sorte T1 : nat pour représenter nat* (nat - 0) (0 pour représenter 1, 1 pour représenter 2, etc.)\n * Attention : bien penser au décalage dans nat/T1.\n *)\n\n(* Cette fonction correspond à la notation nat/s, utilisée en commentaire. *)\nDefinition natBinaire(e : SorteBinaire) : Type := nat.\n\n(* natBinaire comme algèbre sur B *)\n\nDefinition zeroFinalNat : natBinaire N := 0. \n\nDefinition unFinalNat : natBinaire T1 := 0. (* Rappel : décalage\n * car représentation de T1 par nat au lieu de nat* *)\n\n(* Fonction qui à n associe (n + 1) * 2 - 1. \n * (à cause du décalage)\n * Pour simplifier les calculs, il est préférable d'utiliser seulement \n * la fonction S (successeur).\n *)\nDefinition doubleNat : natBinaire T1 -> natBinaire T1. (* +1 -> * 2 -> -1 *)\n intro n.\n induction n as [ | n'].\n - exact 1.\n - exact (S (S IHn')).\nDefined.\n\n(* Fonction qui à n associe (n + 1) * 2. \n * (à cause du décalage)\n * Pour simplifier les calculs, il est préférable d'utiliser seulement \n * la fonction S (successeur).\n *)\nDefinition successeurDoubleNat(n : natBinaire T1) : natBinaire T1. (* -> +1 -> *2 *)\n exact (S (doubleNat n)).\nDefined.\n\nDefinition formeNormaleNat(n : natBinaire T1) : natBinaire N := S n. (* Rappel : décalage *)\n\n(* (Binaire s) comme algèbre sur Nat *)\n\n(* Interprétation de zéro dans (Binaire N) et (Binaire T1).\n * Prise en compte du décalge.\n *) \nDefinition zeroBinaire(s : SorteBinaire) : Binaire s.\n case s.\n - exact unFinal.\n - exact zeroFinal.\nDefined.\n\n(* interprétation de successeur dans (Binaire N) et (Binaire T1).\n * prise en compte du décalge.\n *) \nFixpoint successeurBinaire {e : SorteBinaire}(b : Binaire e) : Binaire e.\n case b as [ | | sb | sb | bn ].\n - exact (formeNormale (unFinal)).\n - exact (double unFinal).\n - exact (successeurDouble sb).\n - exact (double (successeurBinaire T1 sb)).\n - exact (formeNormale (successeurBinaire T1 bn)).\nDefined.\n(* Ou avec les notations :\n case b as [ | | sb | sb | bn].\n - exact (B I).\n - exact (O,I).\n - exact (I, sb).\n - exact (O, (successeurBin _ sb)).\n - exact (B (successeurBin _ bn)).\n *)\n\n(** Conversion de [natBinaire] vers [Binaire] *)\nFixpoint valeurNatEnBinaire(s : SorteBinaire)(n : natBinaire s) : Binaire s.\n case n as [ | n'].\n - exact (zeroBinaire s).\n - exact (successeurBinaire (valeurNatEnBinaire _ n')).\nDefined.\n\n(* La conversion est un morphisme d'algèbre sur Nat.\n * Par définition - simple vérification.\n *) \nLemma morphismeNat_valeurNatEnBinaire :\n forall s,\n valeurNatEnBinaire s 0 = zeroBinaire s\n /\\\n forall n,\n valeurNatEnBinaire s (S n) = successeurBinaire (valeurNatEnBinaire s n). \nProof.\n split; reflexivity.\nQed.\n\n(* La conversion valeurNatEnBinaire est aussi un morphisme d'algèbre sur Bin. \n * Cinq lemmes, un par opération de la signature.\n *)\nLemma morphismeZeroFinal_valeurNatEnBinaire :\n valeurNatEnBinaire _ zeroFinalNat = zeroFinal.\nProof.\n reflexivity.\nQed.\n\nLemma morphismeUnFinal_valeurNatEnBinaire :\n valeurNatEnBinaire _ unFinalNat = unFinal.\nProof.\n reflexivity.\nQed.\n\nLemma morphismeDouble_valeurNatEnBinaire :\n forall n : natBinaire T1,\n valeurNatEnBinaire _ (doubleNat n) = double (valeurNatEnBinaire _ n).\nProof.\n induction n.\n - simpl. reflexivity.\n - simpl. rewrite IHn. simpl. reflexivity.\nQed.\n\nLemma morphismeSuccesseurDouble_valeurNatEnBinaire :\n forall n : natBinaire T1,\n valeurNatEnBinaire _ (successeurDoubleNat n) = successeurDouble (valeurNatEnBinaire _ n).\nProof.\n intro n. simpl. rewrite morphismeDouble_valeurNatEnBinaire.\n reflexivity.\nQed.\n\nLemma morphismeFormeNormale_valeurNatEnBinaire :\n forall n : natBinaire T1,\n valeurNatEnBinaire _ (formeNormaleNat n) = formeNormale (valeurNatEnBinaire _ n).\nProof.\n induction n.\n - simpl. reflexivity.\n - simpl. simpl in IHn. rewrite IHn.\n simpl. reflexivity.\nQed.\n\n(** Conversion de [Binaire] vers [natBinaire] \n *)\n\nFixpoint valeurBinaireEnNat{s : SorteBinaire}(b : Binaire s) : natBinaire s.\n case b as [ | | b' | b' | b'].\n - exact zeroFinalNat.\n - exact unFinalNat.\n - exact (doubleNat (valeurBinaireEnNat _ b')).\n - exact (successeurDoubleNat (valeurBinaireEnNat _ b')).\n - exact (formeNormaleNat (valeurBinaireEnNat _ b')).\nDefined.\n\nCompute valeurBinaireEnNat (B O,I,O,I).\n(* Le paramètre s entre accolades est implicite.\n Il est déterminé automatiquement à partir du type de b. *)\n\n(* La conversion est un morphisme d'algèbre sur Bin.\n * Par définition - simple vérification \n *)\nLemma morphismeBin_valeurBinaireEnNat :\n valeurBinaireEnNat zeroFinal = zeroFinalNat\n /\\\n valeurBinaireEnNat unFinal = unFinalNat\n /\\\n (forall b : Binaire T1,\n valeurBinaireEnNat (double b) = doubleNat (valeurBinaireEnNat b))\n /\\\n (forall b : Binaire T1,\n valeurBinaireEnNat (successeurDouble b) = successeurDoubleNat (valeurBinaireEnNat b))\n /\\\n forall b : Binaire T1,\n valeurBinaireEnNat (formeNormale b) = formeNormaleNat (valeurBinaireEnNat b).\nProof.\n repeat split; reflexivity.\nQed.\n\n(* Chaque composante de la conversion est aussi un morphisme d'algèbre sur Nat. \n * Deux lemmes, un par opération.\n *)\nLemma morphismeZero_valeurBinaireEnNat :\n forall s, \n valeurBinaireEnNat (zeroBinaire s) = 0.\nProof.\n intro s. case s; reflexivity.\nQed.\n\nLemma morphismeSuccesseur_valeurBinaireEnNat :\n forall s, forall b : Binaire s,\n valeurBinaireEnNat (successeurBinaire b) = S (valeurBinaireEnNat b).\nProof.\n induction b as [ | | b' | b' | b'].\n - reflexivity.\n - reflexivity.\n - simpl. reflexivity.\n - simpl. rewrite IHb'. reflexivity.\n - simpl. rewrite IHb'. reflexivity.\nQed.\n\n(* Les isomorphismes *)\n\n(** (valeurBinaireEnNat s) o (valeurNatEnBinaire s) : natBinaire s -> natBinaire s \n * est un morphisme d'algèbre sur N.\n * Par initialité, c'est l'identité.\n * Démonstration directe ci-dessous.\n *)\nProposition isomorphisme_natBinNat :\n forall s, forall n : natBinaire s, valeurBinaireEnNat (valeurNatEnBinaire s n) = n.\nProof.\n induction n.\n - simpl. rewrite morphismeZero_valeurBinaireEnNat. reflexivity.\n - simpl. rewrite morphismeSuccesseur_valeurBinaireEnNat. rewrite IHn. reflexivity.\nQed.\n\n(** valeurNatEnBinaire o valeurBinaireEnNat : Binaire -> Binaire \n * est un morphisme d'algèbre sur B.\n * Par initialité, c'est l'identité.\n * Démonstration directe ci-dessous.\n *)\nProposition isomorphisme_binNatBin :\n forall e, forall b : Binaire e, (valeurNatEnBinaire e (valeurBinaireEnNat b)) = b.\nProof.\n induction b as [ | | b' | b' | b'].\n - simpl. reflexivity.\n - simpl. reflexivity.\n - simpl. rewrite morphismeDouble_valeurNatEnBinaire. rewrite IHb'. reflexivity.\n - simpl. rewrite morphismeDouble_valeurNatEnBinaire. rewrite IHb'. simpl. reflexivity.\n - simpl valeurBinaireEnNat. rewrite morphismeFormeNormale_valeurNatEnBinaire. rewrite IHb'. reflexivity.\nQed. \n\n(* tests *)\n\nCompute (valeurNatEnBinaire N 17).\nCompute (valeurBinaireEnNat (B I,I,O,I)).\nCompute (valeurBinaireEnNat (I,I,O,I)).\nCompute (valeurNatEnBinaire N (valeurBinaireEnNat (B I,I,O,I))).\n\n(* TODO - Quelques exemples à faire *)\n\n(* \n * On montre que Binaire N est un ensemble quotient de SuiteBinaire (cf. le TP Binaire).\n * projection : SuiteBinaire -> Binaire N := forme normale\n * représentant : Binaire N -> SuiteBinaire := plongement \n *)\n\nInductive SuiteBinaire : Type :=\n | dernierZero : SuiteBinaire\n | dernierUn : SuiteBinaire\n | zero : forall n : SuiteBinaire, SuiteBinaire\n | un : forall n : SuiteBinaire, SuiteBinaire.\n\nDefinition representant : forall {s}, (Binaire s) -> SuiteBinaire.\n fix REC 2.\n intros s b.\n case b as [ | | sb | sb | bn].\n - exact dernierZero.\n - exact dernierUn.\n - exact (zero (REC _ sb)).\n - exact (un (REC _ sb)).\n - exact (REC _ bn).\nDefined.\n\n(* Pour faciliter l'inversion, on définit la version paramétrée de Bianire. *)\nInductive BinaireP(s : SorteBinaire) : Type :=\n | zeroFinalP : N = s -> BinaireP s\n | unFinalP : T1 = s -> BinaireP s\n | doubleP : T1 = s -> BinaireP T1 -> BinaireP s\n | successeurDoubleP : T1 = s -> BinaireP T1 -> BinaireP s\n | formeNormaleP : N = s -> BinaireP T1 -> BinaireP s.\n\n(* On définit les morphismes entre les deux versions, indexée et paramétrée respectivement. *)\nDefinition binaireP :\n forall {s}, Binaire s -> BinaireP s.\n fix REC 2.\n intros s b.\n case b as [ | | sb | sb | bn].\n - exact (zeroFinalP N eq_refl).\n - exact (unFinalP T1 eq_refl).\n - exact (doubleP T1 eq_refl (REC _ sb)).\n - exact (successeurDoubleP T1 eq_refl (REC _ sb)).\n - exact (formeNormaleP N eq_refl (REC _ bn)).\nDefined.\n\nPrint binaireP.\n\nDefinition binaireI :\n forall {s}, BinaireP s -> Binaire s.\n fix REC 2.\n intros s b.\n case b as [ eg | eg| eg sb | eg sb | eg bn]; case eg.\n - exact zeroFinal.\n - exact unFinal.\n - exact (double (REC _ sb)).\n - exact (successeurDouble (REC _ sb)).\n - exact (formeNormale (REC _ bn)).\nDefined.\n\nPrint binaireI.\n\n(* Ces morphismes sont des isomorphismes *)\nLemma isomorphisme_binaireIPI :\n forall s, forall b : Binaire s,\n binaireI (binaireP b) = b.\n (* TODO *)\n admit.\nAdmitted.\n\nLemma isomorphisme_binairePIP :\n forall s, forall b : BinaireP s,\n binaireP (binaireI b) = b.\n (* TODO *)\n admit.\nAdmitted.\n\n(* La projection réalise le calcul de la fome normale, sans zéro inutile à droite.\n * Noter la conversion en BinaireP. Sans celle-ci, l'inversion échoue. \n *)\nDefinition projection : SuiteBinaire -> Binaire N.\n fix REC 1.\n intro b.\n case b as [ | | sb | sb].\n - exact BO.\n - exact (B I).\n - case (binaireP (REC sb)) as [ eg| eg | eg sx | eg sx | eg nx];\n try (egaliteImpossible eg).\n + exact BO.\n + pose (y := nx).\n case y as [ eg1| eg1 | eg1 sx1 | eg1 sx1 | eg1 nx1];\n try (egaliteImpossible eg1); exact (B O, (binaireI nx)).\n - case (binaireP (REC sb)) as [ eg| eg | eg sx | eg sx | eg nx];\n try (egaliteImpossible eg).\n + exact (B I).\n + pose (y := nx).\n case y as [ eg1| eg1 | eg1 sx1 | eg1 sx1 | eg1 nx1];\n try (egaliteImpossible eg1); exact (B I, (binaireI nx)). \nDefined.\n\nPrint projection.\n\n(* La fonction de normalisation est l'identité ou formeNormale, suivant la sorte. *)\nDefinition normalisation : forall {s}, Binaire s -> Binaire N.\n intro s.\n case s.\n - intro b.\n exact (formeNormale b).\n - intro b. exact b.\nDefined.\n\nPrint normalisation.\n\n(* Les deux propositions suivantes établissent la propriété fondamentale d'un ensemble quotient. \n * Le premier lemme utilise la version paramétrée pour permettre une inversion sans perte \n * d'informations. \n *)\nLemma quotient_BinaireP :\n forall e, forall b : BinaireP e,\n projection (representant (binaireI b)) = normalisation (binaireI b).\nProof.\n (* TODO *)\n admit.\nAdmitted.\n\n\nProposition quotient_Binaire :\n forall s, forall b : Binaire s,\n projection (representant b) = normalisation b.\n (* TODO *)\n admit.\nAdmitted.\n\nPrint quotient_Binaire.\n\n(* On déduit la propriété souhaitée pour la sorte N. *)\nCorollary quotient_BinaireN :\n forall b : Binaire N,\n projection (representant b) = b.\nProof.\n (* TODO *)\n admit.\nAdmitted.\n", "meta": {"author": "RobinCar", "repo": "Coq", "sha": "8c3cc4f3aeda7af8adab4172cf99470a37480a75", "save_path": "github-repos/coq/RobinCar-Coq", "path": "github-repos/coq/RobinCar-Coq/Coq-8c3cc4f3aeda7af8adab4172cf99470a37480a75/tp3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.144148856709452, "lm_q1q2_score": 0.07038549318210398}} {"text": "(** * Preface *)\n\n(* ################################################################# *)\n(** * Welcome *)\n\n(** This is the entry point in a series of electronic textbooks on\n various aspects of _Software Foundations_ -- the mathematical\n underpinnings of reliable software. Topics in the series include\n basic concepts of logic, computer-assisted theorem proving, the\n Coq proof assistant, functional programming, operational\n semantics, logics for reasoning about programs, and static type\n systems. The exposition is intended for a broad range of readers,\n from advanced undergraduates to PhD students and researchers. No\n specific background in logic or programming languages is assumed,\n though a degree of mathematical maturity will be helpful.\n\n The principal novelty of the series is that it is one hundred\n percent formalized and machine-checked: each text is literally a\n script for Coq. The books are intended to be read alongside (or\n inside) an interactive session with Coq. All the details in the\n text are fully formalized in Coq, and most of the exercises are\n designed to be worked using Coq.\n\n The files in each book are organized into a sequence of core\n chapters, covering about one semester's worth of material and\n organized into a coherent linear narrative, plus a number of\n \"offshoot\" chapters covering additional topics. All the core\n chapters are suitable for both upper-level undergraduate and\n graduate students.\n\n This book, _Logical Foundations_, lays groundwork for the others,\n introducing the reader to the basic ideas of functional\n programming, constructive logic, and the Coq proof assistant. *)\n\n(* ################################################################# *)\n(** * Overview *)\n\n(** Building reliable software is really hard. The scale and\n complexity of modern systems, the number of people involved, and\n the range of demands placed on them make it extremely difficult to\n build software that is even more-or-less correct, much less 100%%\n correct. At the same time, the increasing degree to which\n information processing is woven into every aspect of society\n greatly amplifies the cost of bugs and insecurities.\n\n Computer scientists and software engineers have responded to these\n challenges by developing a whole host of techniques for improving\n software reliability, ranging from recommendations about managing\n software projects teams (e.g., extreme programming) to design\n philosophies for libraries (e.g., model-view-controller,\n publish-subscribe, etc.) and programming languages (e.g.,\n object-oriented programming, aspect-oriented programming,\n functional programming, ...) to mathematical techniques for\n specifying and reasoning about properties of software and tools\n for helping validate these properties. The _Software Foundations_\n series is focused on this last set of techniques.\n\n The text is constructed around three conceptual threads:\n\n (1) basic tools from _logic_ for making and justifying precise\n claims about programs;\n\n (2) the use of _proof assistants_ to construct rigorous logical\n arguments;\n\n (3) _functional programming_, both as a method of programming that\n simplifies reasoning about programs and as a bridge between\n programming and logic.\n\n Some suggestions for further reading can be found in the\n [Postscript] chapter. Bibliographic information for all\n cited works can be found in the file [Bib]. *)\n\n(* ================================================================= *)\n(** ** Logic *)\n\n(** Logic is the field of study whose subject matter is _proofs_ --\n unassailable arguments for the truth of particular propositions.\n Volumes have been written about the central role of logic in\n computer science. Manna and Waldinger called it \"the calculus of\n computer science,\" while Halpern et al.'s paper _On the Unusual\n Effectiveness of Logic in Computer Science_ catalogs scores of\n ways in which logic offers critical tools and insights. Indeed,\n they observe that, \"As a matter of fact, logic has turned out to\n be significantly more effective in computer science than it has\n been in mathematics. This is quite remarkable, especially since\n much of the impetus for the development of logic during the past\n one hundred years came from mathematics.\"\n\n In particular, the fundamental tools of _inductive proof_ are\n ubiquitous in all of computer science. You have surely seen them\n before, perhaps in a course on discrete math or analysis of\n algorithms, but in this course we will examine them more deeply\n than you have probably done so far. *)\n\n(* ================================================================= *)\n(** ** Proof Assistants *)\n\n(** The flow of ideas between logic and computer science has not been\n unidirectional: CS has also made important contributions to logic.\n One of these has been the development of software tools for\n helping construct proofs of logical propositions. These tools\n fall into two broad categories:\n\n - _Automated theorem provers_ provide \"push-button\" operation:\n you give them a proposition and they return either _true_ or\n _false_ (or, sometimes, _don't know: ran out of time_).\n Although their capabilities are still limited to specific\n domains, they have matured tremendously in recent years and\n are used now in a multitude of settings. Examples of such\n tools include SAT solvers, SMT solvers, and model checkers.\n\n - _Proof assistants_ are hybrid tools that automate the more\n routine aspects of building proofs while depending on human\n guidance for more difficult aspects. Widely used proof\n assistants include Isabelle, Agda, Twelf, ACL2, PVS, and Coq,\n among many others.\n\n This course is based around Coq, a proof assistant that has been\n under development since 1983 and that in recent years has\n attracted a large community of users in both research and\n industry. Coq provides a rich environment for interactive\n development of machine-checked formal reasoning. The kernel of\n the Coq system is a simple proof-checker, which guarantees that\n only correct deduction steps are ever performed. On top of this\n kernel, the Coq environment provides high-level facilities for\n proof development, including a large library of common definitions\n and lemmas, powerful tactics for constructing complex proofs\n semi-automatically, and a special-purpose programming language for\n defining new proof-automation tactics for specific situations.\n\n Coq has been a critical enabler for a huge variety of work across\n computer science and mathematics:\n\n - As a _platform for modeling programming languages_, it has\n become a standard tool for researchers who need to describe and\n reason about complex language definitions. It has been used,\n for example, to check the security of the JavaCard platform,\n obtaining the highest level of common criteria certification,\n and for formal specifications of the x86 and LLVM instruction\n sets and programming languages such as C.\n\n - As an _environment for developing formally certified software\n and hardware_, Coq has been used, for example, to build\n CompCert, a fully-verified optimizing compiler for C, and\n CertiKos, a fully verified hypervisor, for proving the\n correctness of subtle algorithms involving floating point\n numbers, and as the basis for CertiCrypt, an environment for\n reasoning about the security of cryptographic algorithms. It is\n also being used to build verified implementations of the\n open-source RISC-V processor.\n\n - As a _realistic environment for functional programming with\n dependent types_, it has inspired numerous innovations. For\n example, the Ynot system embeds \"relational Hoare reasoning\" (an\n extension of the _Hoare Logic_ we will see later in this course)\n in Coq.\n\n - As a _proof assistant for higher-order logic_, it has been used\n to validate a number of important results in mathematics. For\n example, its ability to include complex computations inside\n proofs made it possible to develop the first formally verified\n proof of the 4-color theorem. This proof had previously been\n controversial among mathematicians because part of it included\n checking a large number of configurations using a program. In\n the Coq formalization, everything is checked, including the\n correctness of the computational part. More recently, an even\n more massive effort led to a Coq formalization of the\n Feit-Thompson Theorem -- the first major step in the\n classification of finite simple groups.\n\n By the way, in case you're wondering about the name, here's what\n the official Coq web site at INRIA (the French national research\n lab where Coq has mostly been developed) says about it: \"Some\n French computer scientists have a tradition of naming their\n software as animal species: Caml, Elan, Foc or Phox are examples of\n this tacit convention. In French, 'coq' means rooster, and it\n sounds like the initials of the Calculus of Constructions (CoC) on\n which it is based.\" The rooster is also the national symbol of\n France, and C-o-q are the first three letters of the name of\n Thierry Coquand, one of Coq's early developers. *)\n\n(* ================================================================= *)\n(** ** Functional Programming *)\n\n(** The term _functional programming_ refers both to a collection of\n programming idioms that can be used in almost any programming\n language and to a family of programming languages designed to\n emphasize these idioms, including Haskell, OCaml, Standard ML,\n F##, Scala, Scheme, Racket, Common Lisp, Clojure, Erlang, and Coq.\n\n Functional programming has been developed over many decades --\n indeed, its roots go back to Church's lambda-calculus, which was\n invented in the 1930s, well before the first computers (at least\n the first electronic ones)! But since the early '90s it has\n enjoyed a surge of interest among industrial engineers and\n language designers, playing a key role in high-value systems at\n companies like Jane St. Capital, Microsoft, Facebook, and\n Ericsson.\n\n The most basic tenet of functional programming is that, as much as\n possible, computation should be _pure_, in the sense that the only\n effect of execution should be to produce a result: it should be\n free from _side effects_ such as I/O, assignments to mutable\n variables, redirecting pointers, etc. For example, whereas an\n _imperative_ sorting function might take a list of numbers and\n rearrange its pointers to put the list in order, a pure sorting\n function would take the original list and return a _new_ list\n containing the same numbers in sorted order.\n\n A significant benefit of this style of programming is that it\n makes programs easier to understand and reason about. If every\n operation on a data structure yields a new data structure, leaving\n the old one intact, then there is no need to worry about how that\n structure is being shared and whether a change by one part of the\n program might break an invariant that another part of the program\n relies on. These considerations are particularly critical in\n concurrent systems, where every piece of mutable state that is\n shared between threads is a potential source of pernicious bugs.\n Indeed, a large part of the recent interest in functional\n programming in industry is due to its simpler behavior in the\n presence of concurrency.\n\n Another reason for the current excitement about functional\n programming is related to the first: functional programs are often\n much easier to parallelize than their imperative counterparts. If\n running a computation has no effect other than producing a result,\n then it does not matter _where_ it is run. Similarly, if a data\n structure is never modified destructively, then it can be copied\n freely, across cores or across the network. Indeed, the\n \"Map-Reduce\" idiom, which lies at the heart of massively\n distributed query processors like Hadoop and is used by Google to\n index the entire web is a classic example of functional\n programming.\n\n For purposes of this course, functional programming has yet\n another significant attraction: it serves as a bridge between\n logic and computer science. Indeed, Coq itself can be viewed as a\n combination of a small but extremely expressive functional\n programming language plus a set of tools for stating and proving\n logical assertions. Moreover, when we come to look more closely,\n we find that these two sides of Coq are actually aspects of the\n very same underlying machinery -- i.e., _proofs are programs_. *)\n\n(* ================================================================= *)\n(** ** Further Reading *)\n\n(** This text is intended to be self contained, but readers looking\n for a deeper treatment of particular topics will find some\n suggestions for further reading in the [Postscript]\n chapter. *)\n\n(* ################################################################# *)\n(** * Practicalities *)\n\n(* ================================================================= *)\n(** ** Chapter Dependencies *)\n\n(** A diagram of the dependencies between chapters and some suggested\n paths through the material can be found in the file [deps.html]. *)\n\n(* ================================================================= *)\n(** ** System Requirements *)\n\n(** Coq runs on Windows, Linux, and macOS. You will need:\n\n - A current installation of Coq, available from the Coq home page.\n These files have been tested with Coq 8.8.1.\n\n - An IDE for interacting with Coq. Currently, there are two\n choices:\n\n - Proof General is an Emacs-based IDE. It tends to be\n preferred by users who are already comfortable with Emacs.\n It requires a separate installation (google \"Proof\n General\").\n\n Adventurous users of Coq within Emacs may also want to check\n out extensions such as [company-coq] and [control-lock].\n\n - CoqIDE is a simpler stand-alone IDE. It is distributed with\n Coq, so it should be available once you have Coq installed.\n It can also be compiled from scratch, but on some platforms\n this may involve installing additional packages for GUI\n libraries and such.\n\n Users who like CoqIDE should consider running it with the\n \"asynchronous\" and \"error resilience\" modes disabled:\n\n coqide -async-proofs off -async-proofs-command-error-resilience off Foo.v &\n*)\n\n(* ================================================================= *)\n(** ** Exercises *)\n\n(** Each chapter includes numerous exercises. Each is marked with a\n \"star rating,\" which can be interpreted as follows:\n\n - One star: easy exercises that underscore points in the text\n and that, for most readers, should take only a minute or two.\n Get in the habit of working these as you reach them.\n\n - Two stars: straightforward exercises (five or ten minutes).\n\n - Three stars: exercises requiring a bit of thought (ten\n minutes to half an hour).\n\n - Four and five stars: more difficult exercises (half an hour\n and up).\n\n Also, some exercises are marked \"advanced,\" and some are marked\n \"optional.\" Doing just the non-optional, non-advanced exercises\n should provide good coverage of the core material. Optional\n exercises provide a bit of extra practice with key concepts and\n introduce secondary themes that may be of interest to some\n readers. Advanced exercises are for readers who want an extra\n challenge and a deeper cut at the material.\n\n _Please do not post solutions to the exercises in a public place_. \n Software Foundations is widely used both for self-study and for\n university courses. Having solutions easily available makes it\n much less useful for courses, which typically have graded homework\n assignments. We especially request that readers not post\n solutions to the exercises anyplace where they can be found by\n search engines. *)\n\n(* ================================================================= *)\n(** ** Downloading the Coq Files *)\n\n(** A tar file containing the full sources for the \"release version\"\n of this book (as a collection of Coq scripts and HTML files) is\n available at http://softwarefoundations.cis.upenn.edu.\n\n If you are using the book as part of a class, your professor may\n give you access to a locally modified version of the files; you\n should use this one instead of the public release version, so that\n you get any local updates during the semester. *)\n\n(* ################################################################# *)\n(** * Resources *)\n\n(* ================================================================= *)\n(** ** Sample Exams *)\n\n(** A large compendium of exams from many offerings of\n CIS500 (\"Software Foundations\") at the University of Pennsylvania\n can be found at\n https://www.seas.upenn.edu/~cis500/current/exams/index.html.\n There has been some drift of notations over the years, but most of\n the problems are still relevant to the current text. *)\n\n(* ================================================================= *)\n(** ** Lecture Videos *)\n\n(** Lectures for two intensive summer courses based on _Logical\n Foundations_ (part of the DeepSpec summer school series) can be\n found at https://deepspec.org/event/dsss17 and\n https://deepspec.org/event/dsss18/. The video quality in the\n 2017 lectures is poor at the beginning but gets better in the\n later lectures. *)\n\n(* ################################################################# *)\n(** * Note for Instructors *)\n\n(** If you plan to use these materials in your own course, you will\n undoubtedly find things you'd like to change, improve, or add.\n Your contributions are welcome!\n\n In order to keep the legalities simple and to have a single point\n of responsibility in case the need should ever arise to adjust the\n license terms, sublicense, etc., we ask all contributors (i.e.,\n everyone with access to the developers' repository) to assign\n copyright in their contributions to the appropriate \"author of\n record,\" as follows:\n\n - I hereby assign copyright in my past and future contributions\n to the Software Foundations project to the Author of Record of\n each volume or component, to be licensed under the same terms\n as the rest of Software Foundations. I understand that, at\n present, the Authors of Record are as follows: For Volumes 1\n and 2, known until 2016 as \"Software Foundations\" and from\n 2016 as (respectively) \"Logical Foundations\" and \"Programming\n Foundations,\" and for Volume 4, \"QuickChick: Property-Based\n Testing in Coq,\" the Author of Record is Benjamin C. Pierce.\n For Volume 3, \"Verified Functional Algorithms\", the Author of\n Record is Andrew W. Appel. For components outside of\n designated volumes (e.g., typesetting and grading tools and\n other software infrastructure), the Author of Record is\n Benjamin Pierce.\n\n To get started, please send an email to Benjamin Pierce,\n describing yourself and how you plan to use the materials and\n including (1) the above copyright transfer text and (2) your\n github username.\n\n We'll set you up with access to the git repository and developers'\n mailing lists. In the repository you'll find a file [INSTRUCTORS]\n with further instructions. *)\n\n(* ################################################################# *)\n(** * Translations *)\n\n(** Thanks to the efforts of a team of volunteer translators,\n _Software Foundations_ can be enjoyed in Japanese at\n http://proofcafe.org/sf. A Chinese translation is also underway;\n you can preview it at https://coq-zh.github.io/SF-zh/. *)\n\n(* ################################################################# *)\n(** * Thanks *)\n\n(** Development of the _Software Foundations_ series has been\n supported, in part, by the National Science Foundation under the\n NSF Expeditions grant 1521523, _The Science of Deep\n Specification_. *)\n\n(* Wed Jan 9 12:02:43 EST 2019 *)\n", "meta": {"author": "carliros", "repo": "software-foundations-book", "sha": "fea3e774d18d2434c7296cedbf52756c5ab8dbdd", "save_path": "github-repos/coq/carliros-software-foundations-book", "path": "github-repos/coq/carliros-software-foundations-book/software-foundations-book-fea3e774d18d2434c7296cedbf52756c5ab8dbdd/logical-foundations-2019/dotv/Preface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.16451646289656316, "lm_q1q2_score": 0.0701369204623429}} {"text": "(*|\n####################################################\nDifference between parameters and members of a class\n####################################################\n\n:Link: https://stackoverflow.com/q/70112873\n|*)\n\n(*|\nQuestion\n********\n\nI am new to Coq and was wondering what is the difference between the\nfollowing things:\n|*)\n\nClass test (f g : nat -> nat) := {\n init : f 0 = 0 /\\ g 0 = 0;\n }.\n\n(*| and |*)\n\nReset Initial. (* .none *)\nClass test := {\n f : nat -> nat;\n g : nat -> nat;\n init : f 0 = 0 /\\ g 0 = 0;\n }.\n\n(*|\nCould anyone provide an explanation?\n|*)\n\n(*|\nAnswer (Ana Borges)\n*******************\n\nThe difference between them is referred to as bundling.\n|*)\n\nReset Initial. (* .none *)\nClass test (f g : nat -> nat) := {\n init: f 0 = 0 /\\ g 0 = 0;\n }.\n\n(*| is unbundled, and |*)\n\nReset Initial. (* .none *)\nClass test := {\n f : nat -> nat;\n g : nat -> nat;\n init : f 0 = 0 /\\ g 0 = 0;\n }.\n\n(*|\nis bundled.\n\nThe advantage of bundling is that you don't need to always provide\n``f`` and ``g``. The advantage of unbundling is that you can have\ndifferent instances of the same class sharing the same ``f`` and\n``g``. If you bundle them, Coq will not be easily convinced that\ndifferent instances share parameters.\n\nYou can read more about this in `Type Classes for Mathematics in Type\nTheory\n`__.\n|*)\n\n(*|\nAnswer (Maëlan)\n***************\n\nTo complement Ana's excellent answer, here is a practical difference:\n\n- the unbundled version (call it ``utest``) allows you to write the\n logical statement ``utest f g`` about a specific pair of functions\n ``f`` and ``g``,\n- whereas the bundled version (call it ``btest``) allows you to state\n that there exists a pair of functions which satisfies the\n properties; you can later refer to these functions by the projection\n names ``f`` and ``g``.\n\nSo, roughly speaking:\n\n- ``btest`` is \"equivalent\" to ``∃ f g, utest f g``;\n- ``utest f' g'`` is \"equivalent\" to ``btest`` ∧ \"the ``f`` (resp.\n ``g``) in the aforementioned proof of btest is equal to ``f'``\n (resp. ``g'``)\".\n\nMore formally, here are the equivalences for a minimal example (in\nthis code, the notation ``{ x : A | B }`` is a **dependent pair**\ntype, i.e. the type of ``(x, y)`` where ``x : A`` and ``y : B`` and\nthe type ``B`` depends on the value ``x``):\n|*)\n\nReset Initial. (* .none *)\n(* unbundled: *)\nClass utest (x : nat) : Prop := {\n uprop : x = 0;\n }.\n\n(* bundled: *)\nClass btest : Type := {\n bx : nat;\n bprop : bx = 0;\n }.\n\n(* [btest] is equivalent to: *)\n\nGoal { x : nat | utest x } -> btest.\nProof.\n intros [x u]. econstructor. exact (@uprop x u).\nQed.\n\nGoal btest -> { x : nat | utest x }.\nProof.\n intros b. exists (@bx b). constructor. exact (@bprop b).\nQed.\n\n(* [utest x] is equivalent to: *)\n\nGoal forall x, { b : btest | @bx b = x } -> utest x.\nProof.\n intros x [b <-]. constructor. exact (@bprop b).\nQed.\n\nGoal forall x, utest x -> { b : btest | @bx b = x }.\nProof.\n intros x u. exists {| bx := x ; bprop := @uprop x u |}. reflexivity.\nQed.\n\n(* NOTE: Here I've explicited all implicit arguments; in fact, you\n can let Coq infer them, and write just [bx], [bprop], [uprop]\n instead of [@bx b], [@bprop b], [@uprop x u]. *)\n\n(*|\nIn this example, we can also observe a difference with respect to\ncomputational relevance: ``utest`` can live in ``Prop``, because its\nonly member, ``uprop``, is a proposition. On the other hand, I cannot\nreally put ``btest`` in ``Prop``, because that would mean that *both*\n``bx`` and ``bprop`` would live in ``Prop`` but ``bf`` is\ncomputationally relevant. In other words, Coq gives you this warning:\n|*)\n\nReset Initial. (* .none *)\nClass btest : Prop := {\n bx : nat;\n bprop : bx = 0;\n }.\n(* WARNING:\n bx cannot be defined because it is informative and btest is not.\n bprop cannot be defined because the projection bx was not defined.\n*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/difference-between-parameters-and-members-of-a-class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.15405756074950905, "lm_q1q2_score": 0.0686371934100595}} {"text": "(* Copyright (c) 2009-2012, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n * http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import Arith.\n\nRequire Import CpdtTactics.\n\nSet Implicit Arguments.\n(* end hide *)\n\n\n(** %\\part{The Big Picture}\n\n \\chapter{Proving in the Large}% *)\n\n(** It is somewhat unfortunate that the term \"theorem proving\" looks so much like the word \"theory.\" Most researchers and practitioners in software assume that mechanized theorem proving is profoundly impractical. Indeed, until recently, most advances in theorem proving for higher-order logics have been largely theoretical. However, starting around the beginning of the 21st century, there was a surge in the use of proof assistants in serious verification efforts. That line of work is still quite new, but I believe it is not too soon to distill some lessons on how to work effectively with large formal proofs.\n\n Thus, this chapter gives some tips for structuring and maintaining large Coq developments. *)\n\n\n(** * Ltac Anti-Patterns *)\n\n(** In this book, I have been following an unusual style, where proofs are not considered finished until they are %\\index{fully automated proofs}%\"fully automated,\" in a certain sense. Each such theorem is proved by a single tactic. Since Ltac is a Turing-complete programming language, it is not hard to squeeze arbitrary heuristics into single tactics, using operators like the semicolon to combine steps. In contrast, most Ltac proofs \"in the wild\" consist of many steps, performed by individual tactics followed by periods. Is it really worth drawing a distinction between proof steps terminated by semicolons and steps terminated by periods?\n\n I argue that this is, in fact, a very important distinction, with serious consequences for a majority of important verification domains. The more uninteresting drudge work a proof domain involves, the more important it is to work to prove theorems with single tactics. From an automation standpoint, single-tactic proofs can be extremely effective, and automation becomes more and more critical as proofs are populated by more uninteresting detail. In this section, I will give some examples of the consequences of more common proof styles.\n\n As a running example, consider a basic language of arithmetic expressions, an interpreter for it, and a transformation that scales up every constant in an expression. *)\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Plus : exp -> exp -> exp.\n\nFixpoint eval (e : exp) : nat :=\n match e with\n | Const n => n\n | Plus e1 e2 => eval e1 + eval e2\n end.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n end.\n\n(** We can write a very manual proof that [times] really implements multiplication. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e.\n\n trivial.\n\n simpl.\n rewrite IHe1.\n rewrite IHe2.\n rewrite mult_plus_distr_l.\n trivial.\nQed.\n\n(* begin thide *)\n(** We use spaces to separate the two inductive cases, but note that these spaces have no real semantic content; Coq does not enforce that our spacing matches the real case structure of a proof. The second case mentions automatically generated hypothesis names explicitly. As a result, innocuous changes to the theorem statement can invalidate the proof. *)\n\nReset eval_times.\n\nTheorem eval_times : forall k x,\n eval (times k x) = k * eval x.\n induction x.\n\n trivial.\n\n simpl.\n(** %\\vspace{-.15in}%[[\n rewrite IHe1.\n]]\n\n<<\nError: The reference IHe1 was not found in the current environment.\n>>\n\n The inductive hypotheses are named [IHx1] and [IHx2] now, not [IHe1] and [IHe2]. *)\n\nAbort.\n\n(** We might decide to use a more explicit invocation of [induction] to give explicit binders for all of the names that we will reference later in the proof. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 ].\n\n trivial.\n\n simpl.\n rewrite IHe1.\n rewrite IHe2.\n rewrite mult_plus_distr_l.\n trivial.\nQed.\n\n(** We pass %\\index{tactics!induction}%[induction] an%\\index{intro pattern}% _intro pattern_, using a [|] character to separate instructions for the different inductive cases. Within a case, we write [?] to ask Coq to generate a name automatically, and we write an explicit name to assign that name to the corresponding new variable. It is apparent that, to use intro patterns to avoid proof brittleness, one needs to keep track of the seemingly unimportant facts of the orders in which variables are introduced. Thus, the script keeps working if we replace [e] by [x], but it has become more cluttered. Arguably, neither proof is particularly easy to follow.\n\n That category of complaint has to do with understanding proofs as static artifacts. As with programming in general, with serious projects, it tends to be much more important to be able to support evolution of proofs as specifications change. Unstructured proofs like the above examples can be very hard to update in concert with theorem statements. For instance, consider how the last proof script plays out when we modify [times] to introduce a bug. *)\n\nReset times.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (1 + k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n end.\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 ].\n\n trivial.\n\n simpl.\n(** %\\vspace{-.15in}%[[\n rewrite IHe1.\n]]\n\n<<\nError: The reference IHe1 was not found in the current environment.\n>>\n *)\n\nAbort.\n\n(** Can you spot what went wrong, without stepping through the script step-by-step? The problem is that [trivial] never fails. Originally, [trivial] had been succeeding in proving an equality that follows by reflexivity. Our change to [times] leads to a case where that equality is no longer true. The invocation [trivial] happily leaves the false equality in place, and we continue on to the span of tactics intended for the second inductive case. Unfortunately, those tactics end up being applied to the _first_ case instead.\n\n The problem with [trivial] could be \"solved\" by writing, e.g., [solve [ trivial ]] instead, so that an error is signaled early on if something unexpected happens. However, the root problem is that the syntax of a tactic invocation does not imply how many subgoals it produces. Much more confusing instances of this problem are possible. For example, if a lemma [L] is modified to take an extra hypothesis, then uses of [apply L] will generate more subgoals than before. Old unstructured proof scripts will become hopelessly jumbled, with tactics applied to inappropriate subgoals. Because of the lack of structure, there is usually relatively little to be gleaned from knowledge of the precise point in a proof script where an error is raised. *)\n\nReset times.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n end.\n\n(** Many real developments try to make essentially unstructured proofs look structured by applying careful indentation conventions, idempotent case-marker tactics included solely to serve as documentation, and so on. All of these strategies suffer from the same kind of failure of abstraction that was just demonstrated. I like to say that if you find yourself caring about indentation in a proof script, it is a sign that the script is structured poorly.\n\n We can rewrite the current proof with a single tactic. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 ]; [\n trivial\n | simpl; rewrite IHe1; rewrite IHe2; rewrite mult_plus_distr_l; trivial ].\nQed.\n\n(** We use the form of the semicolon operator that allows a different tactic to be specified for each generated subgoal. This change improves the robustness of the script: we no longer need to worry about tactics from one case being applied to a different case. Still, the proof script is not especially readable. Probably most readers would not find it helpful in explaining why the theorem is true. The same could be said for scripts using the%\\index{bullets}% _bullets_ or curly braces provided by Coq 8.4, which allow code like the above to be stepped through interactively, with periods in place of the semicolons, while representing proof structure in a way that is enforced by Coq. Interactive replay of scripts becomes easier, but readability is not really helped.\n\n The situation gets worse in considering extensions to the theorem we want to prove. Let us add multiplication nodes to our [exp] type and see how the proof fares. *)\n\nReset exp.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Plus : exp -> exp -> exp\n| Mult : exp -> exp -> exp.\n\nFixpoint eval (e : exp) : nat :=\n match e with\n | Const n => n\n | Plus e1 e2 => eval e1 + eval e2\n | Mult e1 e2 => eval e1 * eval e2\n end.\n\nFixpoint times (k : nat) (e : exp) : exp :=\n match e with\n | Const n => Const (k * n)\n | Plus e1 e2 => Plus (times k e1) (times k e2)\n | Mult e1 e2 => Mult (times k e1) e2\n end.\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n(** %\\vspace{-.25in}%[[\n induction e as [ | ? IHe1 ? IHe2 ]; [\n trivial\n | simpl; rewrite IHe1; rewrite IHe2; rewrite mult_plus_distr_l; trivial ].\n]]\n\n<<\nError: Expects a disjunctive pattern with 3 branches.\n>>\n *)\nAbort.\n\n(** Unsurprisingly, the old proof fails, because it explicitly says that there are two inductive cases. To update the script, we must, at a minimum, remember the order in which the inductive cases are generated, so that we can insert the new case in the appropriate place. Even then, it will be painful to add the case, because we cannot walk through proof steps interactively when they occur inside an explicit set of cases. *)\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e as [ | ? IHe1 ? IHe2 | ? IHe1 ? IHe2 ]; [\n trivial\n | simpl; rewrite IHe1; rewrite IHe2; rewrite mult_plus_distr_l; trivial\n | simpl; rewrite IHe1; rewrite mult_assoc; trivial ].\nQed.\n\n(** Now we are in a position to see how much nicer is the style of proof that we have followed in most of this book. *)\n\nReset eval_times.\n\nHint Rewrite mult_plus_distr_l.\n\nTheorem eval_times : forall k e,\n eval (times k e) = k * eval e.\n induction e; crush.\nQed.\n(* end thide *)\n\n(** This style is motivated by a hard truth: one person's manual proof script is almost always mostly inscrutable to most everyone else. I claim that step-by-step formal proofs are a poor way of conveying information. Thus, we might as well cut out the steps and automate as much as possible.\n\n What about the illustrative value of proofs? Most informal proofs are read to convey the big ideas of proofs. How can reading [induction e; crush] convey any big ideas? My position is that any ideas that standard automation can find are not very big after all, and the _real_ big ideas should be expressed through lemmas that are added as hints.\n\n An example should help illustrate what I mean. Consider this function, which rewrites an expression using associativity of addition and multiplication. *)\n\nFixpoint reassoc (e : exp) : exp :=\n match e with\n | Const _ => e\n | Plus e1 e2 =>\n let e1' := reassoc e1 in\n let e2' := reassoc e2 in\n match e2' with\n | Plus e21 e22 => Plus (Plus e1' e21) e22\n | _ => Plus e1' e2'\n end\n | Mult e1 e2 =>\n let e1' := reassoc e1 in\n let e2' := reassoc e2 in\n match e2' with\n | Mult e21 e22 => Mult (Mult e1' e21) e22\n | _ => Mult e1' e2'\n end\n end.\n\nTheorem reassoc_correct : forall e, eval (reassoc e) = eval e.\n(* begin thide *)\n induction e; crush;\n match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\n\n (** One subgoal remains:\n [[\n IHe2 : eval e3 * eval e4 = eval e2\n ============================\n eval e1 * eval e3 * eval e4 = eval e1 * eval e2\n ]]\n\n The [crush] tactic does not know how to finish this goal. We could finish the proof manually. *)\n\n rewrite <- IHe2; crush.\n\n (** However, the proof would be easier to understand and maintain if we separated this insight into a separate lemma. *)\n\nAbort.\n\nLemma rewr : forall a b c d, b * c = d -> a * b * c = a * d.\n crush.\nQed.\n\nHint Resolve rewr.\n\nTheorem reassoc_correct : forall e, eval (reassoc e) = eval e.\n induction e; crush;\n match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\nQed.\n(* end thide *)\n\n(** In the limit, a complicated inductive proof might rely on one hint for each inductive case. The lemma for each hint could restate the associated case. Compared to manual proof scripts, we arrive at more readable results. Scripts no longer need to depend on the order in which cases are generated. The lemmas are easier to digest separately than are fragments of tactic code, since lemma statements include complete proof contexts. Such contexts can only be extracted from monolithic manual proofs by stepping through scripts interactively.\n\n The more common situation is that a large induction has several easy cases that automation makes short work of. In the remaining cases, automation performs some standard simplification. Among these cases, some may require quite involved proofs; such a case may deserve a hint lemma of its own, where the lemma statement may copy the simplified version of the case. Alternatively, the proof script for the main theorem may be extended with some automation code targeted at the specific case. Even such targeted scripting is more desirable than manual proving, because it may be read and understood without knowledge of a proof's hierarchical structure, case ordering, or name binding structure.\n\n A competing alternative to the common style of Coq tactics is the%\\index{declarative proof scripts}% _declarative_ style, most frequently associated today with the %\\index{Isar}%Isar%~\\cite{Isar}% language. A declarative proof script is very explicit about subgoal structure and introduction of local names, aiming for human readability. The coding of proof automation is taken to be outside the scope of the proof language, an assumption related to the idea that it is not worth building new automation for each serious theorem. I have shown in this book many examples of theorem-specific automation, which I believe is crucial for scaling to significant results. Declarative proof scripts make it easier to read scripts to modify them for theorem statement changes, but the alternate%\\index{adaptive proof scripts}% _adaptive_ style from this book allows use of the _same_ scripts for many versions of a theorem.\n\n Perhaps I am a pessimist for thinking that fully formal proofs will inevitably consist of details that are uninteresting to people, but it is my preference to focus on conveying proof-specific details through choice of lemmas. Additionally, adaptive Ltac scripts contain bits of automation that can be understood in isolation. For instance, in a big [repeat match] loop, each case can generally be digested separately, which is a big contrast from trying to understand the hierarchical structure of a script in a more common style. Adaptive scripts rely on variable binding, but generally only over very small scopes, whereas understanding a traditional script requires tracking the identities of local variables potentially across pages of code.\n\n One might also wonder why it makes sense to prove all theorems automatically (in the sense of adaptive proof scripts) but not construct all programs automatically. My view there is that _program synthesis_ is a very useful idea that deserves broader application! In practice, there are difficult obstacles in the way of finding a program automatically from its specification. A typical specification is not exhaustive in its description of program properties. For instance, details of performance on particular machine architectures are often omitted. As a result, a synthesized program may be correct in some sense while suffering from deficiencies in other senses. Program synthesis research will continue to come up with ways of dealing with this problem, but the situation for theorem proving is fundamentally different. Following mathematical practice, the only property of a formal proof that we care about is which theorem it proves, and it is trivial to check this property automatically. In other words, with a simple criterion for what makes a proof acceptable, automatic search is straightforward. Of course, in practice we also care about understandability of proofs to facilitate long-term maintenance, which is just what motivates the techniques outlined above, and the next section gives some related advice. *)\n\n\n(** * Debugging and Maintaining Automation *)\n\n(** Fully automated proofs are desirable because they open up possibilities for automatic adaptation to changes of specification. A well-engineered script within a narrow domain can survive many changes to the formulation of the problem it solves. Still, as we are working with higher-order logic, most theorems fall within no obvious decidable theories. It is inevitable that most long-lived automated proofs will need updating.\n\n Before we are ready to update our proofs, we need to write them in the first place. While fully automated scripts are most robust to changes of specification, it is hard to write every new proof directly in that form. Instead, it is useful to begin a theorem with exploratory proving and then gradually refine it into a suitable automated form.\n\n Consider this theorem from Chapter 8, which we begin by proving in a mostly manual way, invoking [crush] after each step to discharge any low-hanging fruit. Our manual effort involves choosing which expressions to case-analyze on. *)\n\n(* begin hide *)\nRequire Import MoreDep.\n(* end hide *)\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n(* begin thide *)\n induction e; crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (cfold e2); crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (cfold e2); crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (cfold e2); crush.\n\n dep_destruct (cfold e1); crush.\n dep_destruct (expDenote e1); crush.\n\n dep_destruct (cfold e); crush.\n\n dep_destruct (cfold e); crush.\nQed.\n\n(** In this complete proof, it is hard to avoid noticing a pattern. We rework the proof, abstracting over the patterns we find. *)\n\nReset cfold_correct.\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n induction e; crush.\n\n (** The expression we want to destruct here turns out to be the discriminee of a [match], and we can easily enough write a tactic that destructs all such expressions. *)\n\n Ltac t :=\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n end; crush).\n\n t.\n\n (** This tactic invocation discharges the whole case. It does the same on the next two cases, but it gets stuck on the fourth case. *)\n\n t.\n\n t.\n\n t.\n\n (** The subgoal's conclusion is:\n [[\n ============================\n (if expDenote e1 then expDenote (cfold e2) else expDenote (cfold e3)) =\n expDenote (if expDenote e1 then cfold e2 else cfold e3)\n ]]\n\n We need to expand our [t] tactic to handle this case. *)\n\n Ltac t' :=\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n | [ |- (if ?E then _ else _) = _ ] => destruct E\n end; crush).\n\n t'.\n\n (** Now the goal is discharged, but [t'] has no effect on the next subgoal. *)\n\n t'.\n\n (** A final revision of [t] finishes the proof. *)\n\n Ltac t'' :=\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n | [ |- (if ?E then _ else _) = _ ] => destruct E\n | [ |- context[match pairOut ?E with Some _ => _\n | None => _ end] ] =>\n dep_destruct E\n end; crush).\n\n t''.\n\n t''.\nQed.\n\n(** We can take the final tactic and move it into the initial part of the proof script, arriving at a nicely automated proof. *)\n\nReset t.\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n induction e; crush;\n repeat (match goal with\n | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n dep_destruct E\n | [ |- (if ?E then _ else _) = _ ] => destruct E\n | [ |- context[match pairOut ?E with Some _ => _\n | None => _ end] ] =>\n dep_destruct E\n end; crush).\nQed.\n(* end thide *)\n\n(** Even after we put together nice automated proofs, we must deal with specification changes that can invalidate them. It is not generally possible to step through single-tactic proofs interactively. There is a command %\\index{Vernacular commands!Debug On}%[Debug On] that lets us step through points in tactic execution, but the debugger tends to make counterintuitive choices of which points we would like to stop at, and per-point output is quite verbose, so most Coq users do not find this debugging mode very helpful. How are we to understand what has broken in a script that used to work?\n\n An example helps demonstrate a useful approach. Consider what would have happened in our proof of [reassoc_correct] if we had first added an unfortunate rewriting hint. *)\n\nReset reassoc_correct.\n\nTheorem confounder : forall e1 e2 e3,\n eval e1 * eval e2 * eval e3 = eval e1 * (eval e2 + 1 - 1) * eval e3.\n crush.\nQed.\n\nHint Rewrite confounder.\n\nTheorem reassoc_correct : forall e, eval (reassoc e) = eval e.\n(* begin thide *)\n induction e; crush;\n match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\n\n (** One subgoal remains:\n \n [[\n ============================\n eval e1 * (eval e3 + 1 - 1) * eval e4 = eval e1 * eval e2\n ]]\n\n The poorly chosen rewrite rule fired, changing the goal to a form where another hint no longer applies. Imagine that we are in the middle of a large development with many hints. How would we diagnose the problem? First, we might not be sure which case of the inductive proof has gone wrong. It is useful to separate out our automation procedure and apply it manually. *)\n\n Restart.\n\n Ltac t := crush; match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] =>\n destruct E; crush\n end.\n\n induction e.\n\n (** Since we see the subgoals before any simplification occurs, it is clear that we are looking at the case for constants. Our [t] makes short work of it. *)\n \n t.\n\n (** The next subgoal, for addition, is also discharged without trouble. *)\n\n t.\n\n (** The final subgoal is for multiplication, and it is here that we get stuck in the proof state summarized above. *)\n\n t.\n\n (** What is [t] doing to get us to this point? The %\\index{tactics!info}%[info] command can help us answer this kind of question. (As of this writing, [info] is no longer functioning in the most recent Coq release, but I hope it returns.) *)\n\n Undo.\n info t.\n\n (* begin hide *)\n (* begin thide *)\n Definition eir := eq_ind_r.\n (* end thide *)\n (* end hide *)\n\n (** %\\vspace{-.15in}%[[\n == simpl in *; intuition; subst; autorewrite with core in *; \n simpl in *; intuition; subst; autorewrite with core in *; \n simpl in *; intuition; subst; destruct (reassoc e2).\n simpl in *; intuition.\n \n simpl in *; intuition.\n \n simpl in *; intuition; subst; autorewrite with core in *;\n refine (eq_ind_r\n (fun n : nat =>\n n * (eval e3 + 1 - 1) * eval e4 = eval e1 * eval e2) _ IHe1);\n autorewrite with core in *; simpl in *; intuition; \n subst; autorewrite with core in *; simpl in *; \n intuition; subst.\n \n ]]\n\n A detailed trace of [t]'s execution appears. Since we are using the very general [crush] tactic, many of these steps have no effect and only occur as instances of a more general strategy. We can copy-and-paste the details to see where things go wrong. *)\n\n Undo.\n\n (** We arbitrarily split the script into chunks. The first few seem not to do any harm. *)\n\n simpl in *; intuition; subst; autorewrite with core in *.\n simpl in *; intuition; subst; autorewrite with core in *.\n simpl in *; intuition; subst; destruct (reassoc e2).\n simpl in *; intuition.\n simpl in *; intuition.\n\n (** The next step is revealed as the culprit, bringing us to the final unproved subgoal. *)\n\n simpl in *; intuition; subst; autorewrite with core in *.\n\n (** We can split the steps further to assign blame. *)\n\n Undo.\n\n simpl in *.\n intuition.\n subst.\n autorewrite with core in *.\n\n (** It was the final of these four tactics that made the rewrite. We can find out exactly what happened. The [info] command presents hierarchical views of proof steps, and we can zoom down to a lower level of detail by applying [info] to one of the steps that appeared in the original trace. *)\n\n Undo.\n\n info autorewrite with core in *.\n (** %\\vspace{-.15in}%[[\n == refine (eq_ind_r (fun n : nat => n = eval e1 * eval e2) _\n (confounder (reassoc e1) e3 e4)).\n ]]\n\n The way a rewrite is displayed is somewhat baroque, but we can see that theorem [confounder] is the final culprit. At this point, we could remove that hint, prove an alternate version of the key lemma [rewr], or come up with some other remedy. Fixing this kind of problem tends to be relatively easy once the problem is revealed. *)\n\nAbort.\n(* end thide *)\n\n(** Sometimes a change to a development has undesirable performance consequences, even if it does not prevent any old proof scripts from completing. If the performance consequences are severe enough, the proof scripts can be considered broken for practical purposes.\n\n Here is one example of a performance surprise. *)\n\nSection slow.\n Hint Resolve trans_eq.\n\n (** The central element of the problem is the addition of transitivity as a hint. With transitivity available, it is easy for proof search to wind up exploring exponential search spaces. We also add a few other arbitrary variables and hypotheses, designed to lead to trouble later. *)\n\n Variable A : Set.\n Variables P Q R S : A -> A -> Prop.\n Variable f : A -> A.\n\n Hypothesis H1 : forall x y, P x y -> Q x y -> R x y -> f x = f y.\n Hypothesis H2 : forall x y, S x y -> R x y.\n\n (** We prove a simple lemma very quickly, using the %\\index{Vernacular commands!Time}%[Time] command to measure exactly how quickly. *)\n\n Lemma slow : forall x y, P x y -> Q x y -> S x y -> f x = f y.\n Time eauto 6.\n(** <<\nFinished transaction in 0. secs (0.068004u,0.s)\n>>\n*)\n\n Qed.\n\n (** Now we add a different hypothesis, which is innocent enough; in fact, it is even provable as a theorem. *)\n\n Hypothesis H3 : forall x y, x = y -> f x = f y.\n\n Lemma slow' : forall x y, P x y -> Q x y -> S x y -> f x = f y.\n Time eauto 6.\n (** <<\nFinished transaction in 2. secs (1.264079u,0.s)\n >>\n %\\vspace{-.15in}%Why has the search time gone up so much? The [info] command is not much help, since it only shows the result of search, not all of the paths that turned out to be worthless. *)\n\n(* begin thide *)\n Restart.\n info eauto 6.\n (** %\\vspace{-.15in}%[[\n == intro x; intro y; intro H; intro H0; intro H4;\n simple eapply trans_eq.\n simple apply eq_refl.\n \n simple eapply trans_eq.\n simple apply eq_refl.\n \n simple eapply trans_eq.\n simple apply eq_refl.\n \n simple apply H1.\n eexact H.\n \n eexact H0.\n \n simple apply H2; eexact H4.\n ]]\n\n This output does not tell us why proof search takes so long, but it does provide a clue that would be useful if we had forgotten that we added transitivity as a hint. The [eauto] tactic is applying depth-first search, and the proof script where the real action is ends up buried inside a chain of pointless invocations of transitivity, where each invocation uses reflexivity to discharge one subgoal. Each increment to the depth argument to [eauto] adds another silly use of transitivity. This wasted proof effort only adds linear time overhead, as long as proof search never makes false steps. No false steps were made before we added the new hypothesis, but somehow the addition made possible a new faulty path. To understand which paths we enabled, we can use the %\\index{tactics!debug}%[debug] command. *)\n\n Restart.\n debug eauto 6.\n\n (* begin hide *)\n (* begin thide *)\n Definition deeeebug := (@eq_refl, @sym_eq).\n (* end thide *)\n (* end hide *)\n\n (** The output is a large proof tree. The beginning of the tree is enough to reveal what is happening:\n [[\n1 depth=6 \n1.1 depth=6 intro\n1.1.1 depth=6 intro\n1.1.1.1 depth=6 intro\n1.1.1.1.1 depth=6 intro\n1.1.1.1.1.1 depth=6 intro\n1.1.1.1.1.1.1 depth=5 apply H3\n1.1.1.1.1.1.1.1 depth=4 eapply trans_eq\n1.1.1.1.1.1.1.1.1 depth=4 apply eq_refl\n1.1.1.1.1.1.1.1.1.1 depth=3 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1 depth=3 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1 depth=2 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1 depth=2 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1.1.1 depth=1 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.1 depth=1 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.2 depth=1 apply sym_eq ; trivial\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.2.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.3 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2 depth=2 apply sym_eq ; trivial\n1.1.1.1.1.1.1.1.1.1.1.1.2.1 depth=1 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.1 depth=1 apply eq_refl\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.1.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.2 depth=1 apply sym_eq ; trivial\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.2.1 depth=0 eapply trans_eq\n1.1.1.1.1.1.1.1.1.1.1.1.2.1.3 depth=0 eapply trans_eq\n ]]\n\n The first choice [eauto] makes is to apply [H3], since [H3] has the fewest hypotheses of all of the hypotheses and hints that match. However, it turns out that the single hypothesis generated is unprovable. That does not stop [eauto] from trying to prove it with an exponentially sized tree of applications of transitivity, reflexivity, and symmetry of equality. It is the children of the initial [apply H3] that account for all of the noticeable time in proof execution. In a more realistic development, we might use this output of [debug] to realize that adding transitivity as a hint was a bad idea. *)\n\n Qed.\n(* end thide *)\nEnd slow.\n\n(** As aggravating as the above situation may be, there is greater aggravation to be had from importing library modules with commands like %\\index{Vernacular commands!Require Import}%[Require Import]. Such a command imports not just the Gallina terms from a module, but also all the hints for [auto], [eauto], and [autorewrite]. Some very recent versions of Coq include mechanisms for removing hints from databases, but the proper solution is to be very conservative in exporting hints from modules. Consider putting hints in named databases, so that they may be used only when called upon explicitly, as demonstrated in Chapter 13.\n\nIt is also easy to end up with a proof script that uses too much memory. As tactics run, they avoid generating proof terms, since serious proof search will consider many possible avenues, and we do not want to build proof terms for subproofs that end up unused. Instead, tactic execution maintains%\\index{thunks}% _thunks_ (suspended computations, represented with closures), such that a tactic's proof-producing thunk is only executed when we run %\\index{Vernacular commands!Qed}%[Qed]. These thunks can use up large amounts of space, such that a proof script exhausts available memory, even when we know that we could have used much less memory by forcing some thunks earlier.\n\n The %\\index{tactics!abstract}%[abstract] tactical helps us force thunks by proving some subgoals as their own lemmas. For instance, a proof [induction x; crush] can in many cases be made to use significantly less peak memory by changing it to [induction x; abstract crush]. The main limitation of [abstract] is that it can only be applied to subgoals that are proved completely, with no undetermined unification variables in their initial states. Still, many large automated proofs can realize vast memory savings via [abstract]. *)\n\n\n(** * Modules *)\n\n(** Last chapter's examples of proof by reflection demonstrate opportunities for implementing abstract proof strategies with stronger formal guarantees than can be had with Ltac scripting. Coq's _module system_ provides another tool for more rigorous development of generic theorems. This feature is inspired by the module systems found in Standard ML%~\\cite{modules}% and OCaml, and the discussion that follows assumes familiarity with the basics of one of those systems.\n\n ML modules facilitate the grouping of %\\index{abstract type}%abstract types with operations over those types. Moreover, there is support for%\\index{functor}% _functors_, which are functions from modules to modules. A canonical example of a functor is one that builds a data structure implementation from a module that describes a domain of keys and its associated comparison operations.\n\n When we add modules to a base language with dependent types, it becomes possible to use modules and functors to formalize kinds of reasoning that are common in algebra. For instance, the following module signature captures the essence of the algebraic structure known as a group. A group consists of a carrier set [G], an associative binary operation [f], a left identity element [id] for [f], and an operation [i] that is a left inverse for [f].%\\index{Vernacular commands!Module Type}% *)\n\nModule Type GROUP.\n Parameter G : Set.\n Parameter f : G -> G -> G.\n Parameter id : G.\n Parameter i : G -> G.\n\n Axiom assoc : forall a b c, f (f a b) c = f a (f b c).\n Axiom ident : forall a, f id a = a.\n Axiom inverse : forall a, f (i a) a = id.\nEnd GROUP.\n\n(** Many useful theorems hold of arbitrary groups. We capture some such theorem statements in another module signature.%\\index{Vernacular commands!Declare Module}% *)\n\nModule Type GROUP_THEOREMS.\n Declare Module M : GROUP.\n\n Axiom ident' : forall a, M.f a M.id = a.\n\n Axiom inverse' : forall a, M.f a (M.i a) = M.id.\n\n Axiom unique_ident : forall id', (forall a, M.f id' a = a) -> id' = M.id.\nEnd GROUP_THEOREMS.\n\n(** We implement generic proofs of these theorems with a functor, whose input is an arbitrary group [M]. %\\index{Vernacular commands!Module}% *)\n\nModule GroupProofs (M : GROUP) : GROUP_THEOREMS with Module M := M.\n\n (** As in ML, Coq provides multiple options for ascribing signatures to modules. Here we use just the colon operator, which implements%\\index{opaque ascription}% _opaque ascription_, hiding all details of the module not exposed by the signature. Another option is%\\index{transparent ascription}% _transparent ascription_ via the [<:] operator, which checks for signature compatibility without hiding implementation details. Here we stick with opaque ascription but employ the [with] operation to add more detail to a signature, exposing just those implementation details that we need to. For instance, here we expose the underlying group representation set and operator definitions. Without such a refinement, we would get an output module proving theorems about some unknown group, which is not very useful. Also note that opaque ascription can in Coq have some undesirable consequences without analogues in ML, since not just the types but also the _definitions_ of identifiers have significance in type checking and theorem proving. *)\n\n Module M := M.\n (** To ensure that the module we are building meets the [GROUP_THEOREMS] signature, we add an extra local name for [M], the functor argument. *)\n\n Import M.\n (** It would be inconvenient to repeat the prefix [M.] everywhere in our theorem statements and proofs, so we bring all the identifiers of [M] into the local scope unqualified.\n\n Now we are ready to prove the three theorems. The proofs are completely manual, which may seem ironic given the content of the previous sections! This illustrates another lesson, which is that short proof scripts that change infrequently may be worth leaving unautomated. It would take some effort to build suitable generic automation for these theorems about groups, so I stick with manual proof scripts to avoid distracting us from the main message of the section. We take the proofs from the Wikipedia page on elementary group theory. *)\n\n Theorem inverse' : forall a, f a (i a) = id.\n intro.\n rewrite <- (ident (f a (i a))).\n rewrite <- (inverse (f a (i a))) at 1.\n rewrite assoc.\n rewrite assoc.\n rewrite <- (assoc (i a) a (i a)).\n rewrite inverse.\n rewrite ident.\n apply inverse.\n Qed.\n\n Theorem ident' : forall a, f a id = a.\n intro.\n rewrite <- (inverse a).\n rewrite <- assoc.\n rewrite inverse'.\n apply ident.\n Qed.\n\n Theorem unique_ident : forall id', (forall a, M.f id' a = a) -> id' = M.id.\n intros.\n rewrite <- (H id).\n symmetry.\n apply ident'.\n Qed.\nEnd GroupProofs.\n\n(** We can show that the integers with [+] form a group. *)\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nModule Int.\n Definition G := Z.\n Definition f x y := x + y.\n Definition id := 0.\n Definition i x := -x.\n\n Theorem assoc : forall a b c, f (f a b) c = f a (f b c).\n unfold f; crush.\n Qed.\n Theorem ident : forall a, f id a = a.\n unfold f, id; crush.\n Qed.\n Theorem inverse : forall a, f (i a) a = id.\n unfold f, i, id; crush.\n Qed.\nEnd Int.\n\n(** Next, we can produce integer-specific versions of the generic group theorems. *)\n\nModule IntProofs := GroupProofs(Int).\n\nCheck IntProofs.unique_ident.\n(** %\\vspace{-.15in}% [[\n IntProofs.unique_ident\n : forall e' : Int.G, (forall a : Int.G, Int.f e' a = a) -> e' = Int.e\n ]]\n\nProjections like [Int.G] are known to be definitionally equal to the concrete values we have assigned to them, so the above theorem yields as a trivial corollary the following more natural restatement: *)\n\nTheorem unique_ident : forall id', (forall a, id' + a = a) -> id' = 0.\n(* begin thide *)\n exact IntProofs.unique_ident.\nQed.\n(* end thide *)\n\n(** As in ML, the module system provides an effective way to structure large developments. Unlike in ML, Coq modules add no expressiveness; we can implement any module as an inhabitant of a dependent record type. It is the second-class nature of modules that makes them easier to use than dependent records in many cases. Because modules may only be used in quite restricted ways, it is easier to support convenient module coding through special commands and editing modes, as the above example demonstrates. An isomorphic implementation with records would have suffered from lack of such conveniences as module subtyping and importation of the fields of a module. On the other hand, all module values must be determined statically, so modules may not be computed, e.g., within the definitions of normal functions, based on particular function parameters. *)\n\n\n(** * Build Processes *)\n\n(* begin hide *)\n(* begin thide *)\nModule Lib.\n Module A.\n End A.\n Module B.\n End B.\n Module C.\n End C.\nEnd Lib.\nModule Client.\n Module D.\n End D.\n Module E.\n End E.\nEnd Client.\n(* end thide *)\n(* end hide *)\n\n(** As in software development, large Coq projects are much more manageable when split across multiple files and when decomposed into libraries. Coq and Proof General provide very good support for these activities.\n\n Consider a library that we will name [Lib], housed in directory <> and split between files <>, <>, and <>. A simple %\\index{Makefile}%Makefile will compile the library, relying on the standard Coq tool %\\index{coq\\_makefile}%<> to do the hard work.\n\n<<\nMODULES := A B C\nVS := $(MODULES:%=%.v)\n\n.PHONY: coq clean\n\ncoq: Makefile.coq\n $(MAKE) -f Makefile.coq\n\nMakefile.coq: Makefile $(VS)\n coq_makefile -R . Lib $(VS) -o Makefile.coq\n\nclean:: Makefile.coq\n $(MAKE) -f Makefile.coq clean\n rm -f Makefile.coq\n>>\n\n The Makefile begins by defining a variable <> holding the list of filenames to be included in the project. The primary target is <>, which depends on the construction of an auxiliary Makefile called <>. Another rule explains how to build that file. We call <>, using the <<-R>> flag to specify that files in the current directory should be considered to belong to the library [Lib]. This Makefile will build a compiled version of each module, such that <> is compiled into <>.\n\n Now code in <> may refer to definitions in <> after running\n [[\nRequire Import Lib.A.\n ]]\n %\\vspace{-.15in}%Library [Lib] is presented as a module, containing a submodule [A], which contains the definitions from <>. These are genuine modules in the sense of Coq's module system, and they may be passed to functors and so on.\n\n The command [Require Import] is a convenient combination of two more primitive commands. The %\\index{Vernacular commands!Require}%[Require] command finds the <<.vo>> file containing the named module, ensuring that the module is loaded into memory. The %\\index{Vernacular commands!Import}%[Import] command loads all top-level definitions of the named module into the current namespace, and it may be used with local modules that do not have corresponding <<.vo>> files. Another command, %\\index{Vernacular commands!Load}%[Load], is for inserting the contents of a named file verbatim. It is generally better to use the module-based commands, since they avoid rerunning proof scripts, and they facilitate reorganization of directory structure without the need to change code.\n\n Now we would like to use our library from a different development, called [Client] and found in directory <>, which has its own Makefile.\n\n<<\nMODULES := D E\nVS := $(MODULES:%=%.v)\n\n.PHONY: coq clean\n\ncoq: Makefile.coq\n $(MAKE) -f Makefile.coq\n\nMakefile.coq: Makefile $(VS)\n coq_makefile -R LIB Lib -R . Client $(VS) -o Makefile.coq\n\nclean:: Makefile.coq\n $(MAKE) -f Makefile.coq clean\n rm -f Makefile.coq\n>>\n\n We change the <> call to indicate where the library [Lib] is found. Now <> and <> can refer to definitions from [Lib] module [A] after running\n [[\nRequire Import Lib.A.\n ]]\n %\\vspace{-.15in}\\noindent{}%and <> can refer to definitions from <> by running\n [[\nRequire Import Client.D.\n ]]\n %\\vspace{-.15in}%It can be useful to split a library into several files, but it is also inconvenient for client code to import library modules individually. We can get the best of both worlds by, for example, adding an extra source file <> to [Lib]'s directory and Makefile, where that file contains just this line:%\\index{Vernacular commands!Require Export}%\n [[\nRequire Export Lib.A Lib.B Lib.C.\n ]]\n %\\vspace{-.15in}%Now client code can import all definitions from all of [Lib]'s modules simply by running\n [[\nRequire Import Lib.\n ]]\n %\\vspace{-.15in}%The two Makefiles above share a lot of code, so, in practice, it is useful to define a common Makefile that is included by multiple library-specific Makefiles.\n\n %\\medskip%\n\n The remaining ingredient is the proper way of editing library code files in Proof General. Recall this snippet of <<.emacs>> code from Chapter 2, which tells Proof General where to find the library associated with this book.\n\n<<\n(custom-set-variables\n ...\n '(coq-prog-args '(\"-I\" \"/path/to/cpdt/src\"))\n ...\n)\n>>\n\n To do interactive editing of our current example, we just need to change the flags to point to the right places.\n\n<<\n(custom-set-variables\n ...\n; '(coq-prog-args '(\"-I\" \"/path/to/cpdt/src\"))\n '(coq-prog-args '(\"-R\" \"LIB\" \"Lib\" \"-R\" \"CLIENT\" \"Client\"))\n ...\n)\n>>\n\n When working on multiple projects, it is useful to leave multiple versions of this setting in your <<.emacs>> file, commenting out all but one of them at any moment in time. To switch between projects, change the commenting structure and restart Emacs.\n\n Alternatively, we can revisit the directory-local settings approach and write the following into a file <<.dir-locals.el>> in <>:\n\n<<\n((coq-mode . ((coq-prog-args .\n (\"-emacs-U\" \"-R\" \"LIB\" \"Lib\" \"-R\" \"CLIENT\" \"Client\")))))\n>>\n\n A downside of this approach is that users of your code may not want to trust the arbitrary Emacs Lisp programs that you are allowed to place in such files, so that they prefer to add mappings manually.\n*)\n", "meta": {"author": "relrod", "repo": "coq-playground", "sha": "b6e5538ef9fce09a4169169c78a5bc2da5951e8a", "save_path": "github-repos/coq/relrod-coq-playground", "path": "github-repos/coq/relrod-coq-playground/coq-playground-b6e5538ef9fce09a4169169c78a5bc2da5951e8a/cpdt/Large.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.14608724147172555, "lm_q1q2_score": 0.0684843294716296}} {"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\n\nRequire Export Coq.Program.Tactics.\nRequire Export Coq.Program.Equality.\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Coq.Logic.ProofIrrelevance.\n\nDefinition equal_f : ∀ {A B : Type} {f g : A → B}, f = g → ∀ x : A, f x = g x.\nProof.\n intros A B f g H x.\n destruct H; reflexivity.\nDefined.\n\nDefinition f_equal : ∀ (A B : Type) (f : A → B) (x y : A), x = y → f x = f y.\nProof.\n intros A B f x y H.\n destruct H; reflexivity.\nDefined.\n\nArguments f_equal [_ _] _ [_ _] _.\n\nLtac basic_simpl :=\n let simpl_prod _ :=\n match goal with\n [H : prod _ _ |- _] =>\n let H1 := fresh H \"1\" in\n let H2 := fresh H \"2\" in\n destruct H as [H1 H2]\n end\n in\n let simpl_sig _ :=\n match goal with\n [H : @sig _ _ |- _] =>\n let H1 := fresh H \"1\" in\n let H2 := fresh H \"2\" in\n destruct H as [H1 H2]\n end\n in\n let basic_simpl_helper _ :=\n cbn in *; intros;\n repeat simpl_prod tt;\n repeat simpl_sig tt\n in\n repeat basic_simpl_helper tt\n.\n\nGlobal Obligation Tactic := basic_simpl; auto.\n\n(** A tactic to apply proof irrelevance on all proofs of the same type in the\n context. *)\nLtac PIR :=\n let pir_helper _ :=\n match goal with\n |[H : ?A, H' : ?A|- _] =>\n match type of A with\n | Prop =>\n destruct (proof_irrelevance _ H H')\n end\n end\n in\n repeat pir_helper tt\n.\n\n(** A tactic to eliminate equalities in the context. *)\nLtac ElimEq := repeat match goal with [H : _ = _|- _] => destruct H end.\n\nHint Extern 1 => progress ElimEq.\n\n(** A tactic to simplify terms before rewriting them. *)\n\nLtac cbn_rewrite W :=\n let H := fresh \"H\" in\n set (H := W); cbn in H; rewrite H; clear H\n.\n\nLtac cbn_rewrite_in W V :=\n let H := fresh \"H\" in\n set (H := W); cbn in H; rewrite H in V; clear H\n.\n\nLtac cbn_rewrite_back W :=\n let H := fresh \"H\" in\n set (H := W); cbn in H; rewrite <- H; clear H\n.\n\nLtac cbn_rewrite_back_in W V :=\n let H := fresh \"H\" in\n set (H := W); cbn in H; rewrite <- H in V; clear H\n.\n\nTactic Notation \"cbn_rewrite\" constr(W) := cbn_rewrite W.\nTactic Notation \"cbn_rewrite\" constr(W) \"in\" hyp_list(V) := cbn_rewrite_in W V.\nTactic Notation \"cbn_rewrite\" \"<-\" constr(W) := cbn_rewrite_back W.\nTactic Notation \"cbn_rewrite\" \"<-\" constr(W) \"in\" hyp_list(V) := cbn_rewrite_back_in W V.\n\n(** Equality on sigma type under proof irrelevance *)\n\nLemma sig_proof_irrelevance {A : Type} (P : A → Prop) (X Y : sig P) : proj1_sig X = proj1_sig Y → X = Y.\nProof.\n basic_simpl.\n ElimEq.\n PIR.\n trivial.\nQed.\n\nHint Extern 2 (exist ?A _ _ = exist ?A _ _) => apply sig_proof_irrelevance.\n\n(* Automating use of functional_extensionality *)\nLtac FunExt :=\nprogress (\n repeat (\n match goal with\n [|- _ = _] =>\n let x := fresh \"x\" in\n extensionality x\n end\n )\n )\n.\n\nHint Extern 1 => FunExt.\n\nLemma pair_eq (A B : Type) (a b : A * B) : fst a = fst b → snd a = snd b → a = b.\nProof.\n intros H1 H2.\n destruct a; destruct b.\n cbn in *.\n repeat match goal with [H : _ = _|-_] => destruct H end.\n trivial.\nQed.\n\nHint Resolve pair_eq.\n\n(** Tactics to apply a tactic to all hypothesis in an efficient way.\nThis is due to Jonathan's (jonikelee@gmail.com) message on coq-club *)\n\nLtac revert_clearbody_all :=\n repeat lazymatch goal with H:_ |- _ => try clearbody H; revert H end.\n\nLtac hyp_stack :=\n constr:(ltac:(revert_clearbody_all;constructor) : True).\n\nLtac next_hyp hs step last :=\n lazymatch hs with (?hs' ?H) => step H hs' | _ => last end.\n\nTactic Notation \"dohyps\" tactic3(tac) :=\n let hs := hyp_stack in\n let rec step H hs := tac H; next_hyp hs step idtac in\n next_hyp hs step idtac.\n\nTactic Notation \"dohyps\" \"reverse\" tactic3(tac) :=\n let hs := hyp_stack in\n let rec step H hs := next_hyp hs step idtac; tac H in\n next_hyp hs step idtac.\n\nTactic Notation \"do1hyp\" tactic3(tac) :=\n let hs := hyp_stack in\n let rec step H hs := tac H + next_hyp hs step fail in\n next_hyp hs step fail.\n\nTactic Notation \"do1hyp\" \"reverse\" tactic3(tac) :=\n let hs := hyp_stack in\n let rec step H hs := next_hyp hs step fail + tac H in\n next_hyp hs step fail.\n\n(** End of tactics for applying a tactic to all hypothesis. *)", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Essentials/Facts_Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.0683041985281905}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward. \n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (which mostly works), and\n Scheme (a bit out of date). *)\n\nExtraction Language Ocaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import SF.SfLib.\nRequire Import SF.ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ############################################################## *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ############################################################## *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we need a few\n magic declarations to set up the right correspondence between Coq\n strings and lists of OCaml characters. *)\n\nRequire Import Ascii String.\nExtract Inductive ascii => char\n[\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))\"\n]\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))\".\nExtract Constant zero => \"'\\000'\".\nExtract Constant one => \"'\\001'\".\nExtract Constant shift =>\n \"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)\".\nExtract Inlined Constant ascii_dec => \"(=)\".\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nRequire Import SF.Imp.\nRequire Import SF.ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ############################################################## *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(** $Date: 2016-05-26 12:03:56 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "erikmd", "repo": "tryjscoq", "sha": "b5636d1b7bc6616fe7f136678e30bc4030484f22", "save_path": "github-repos/coq/erikmd-tryjscoq", "path": "github-repos/coq/erikmd-tryjscoq/tryjscoq-b5636d1b7bc6616fe7f136678e30bc4030484f22/jscoq/examples/sf/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.1422318986458388, "lm_q1q2_score": 0.06667698089242315}} {"text": "(** * ImpParser: Lexing and Parsing in Coq *)\n\n(* $Date: 2013-07-01 18:48:47 -0400 (Mon, 01 Jul 2013) $ *)\n\n(** The development of the [Imp] language in Imp.v completely ignores\n issues of concrete syntax -- how an ascii string that a programmer\n might write gets translated into the abstract syntax trees defined\n by the datatypes [aexp], [bexp], and [com]. In this file we\n illustrate how the rest of the story can be filled in by building\n a simple lexical analyzer and parser using Coq's functional\n programming facilities.\n\n This development is not intended to be understood in detail: the\n explanations are fairly terse and there are no exercises. The\n main point is simply to demonstrate that it can be done. You are\n invited to look through the code -- most of it is not very\n complicated, though the parser relies on some \"monadic\"\n programming idioms that may require a little work to make out --\n but most readers will probably want to just skip down to the\n Examples section at the very end to get the punchline. *)\n\n(* ####################################################### *)\n(** * Internals *)\n\nRequire Import SfLib.\nRequire Import Imp.\n\nRequire Import String.\nRequire Import Ascii.\n\nOpen Scope list_scope.\n\n(* ####################################################### *)\n(** ** Lexical Analysis *)\n\nDefinition isWhite (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (orb (beq_nat n 32) (* space *)\n (beq_nat n 9)) (* tab *)\n (orb (beq_nat n 10) (* linefeed *)\n (beq_nat n 13)). (* Carriage return. *)\n\nNotation \"x '<=?' y\" := (ble_nat x y)\n (at level 70, no associativity) : nat_scope.\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n andb (97 <=? n) (n <=? 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n let n := nat_of_ascii c in\n orb (andb (65 <=? n) (n <=? 90))\n (andb (97 <=? n) (n <=? 122)).\n\nDefinition isDigit (c : ascii) : bool :=\n let n := nat_of_ascii c in \n andb (48 <=? n) (n <=? 57).\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n if isWhite c then \n white\n else if isAlpha c then\n alpha\n else if isDigit c then\n digit\n else\n other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n match s with\n | EmptyString => []\n | String c s => c :: (list_of_string s)\n end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n fold_right String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii) \n : list (list ascii) :=\n let tk := match acc with [] => [] | _::_ => [rev acc] end in\n match xs with\n | [] => tk\n | (x::xs') =>\n match cls, classifyChar x, x with\n | _, _, \"(\" => tk ++ [\"(\"]::(tokenize_helper other [] xs') \n | _, _, \")\" => tk ++ [\")\"]::(tokenize_helper other [] xs') \n | _, white, _ => tk ++ (tokenize_helper white [] xs')\n | alpha,alpha,x => tokenize_helper alpha (x::acc) xs'\n | digit,digit,x => tokenize_helper digit (x::acc) xs'\n | other,other,x => tokenize_helper other (x::acc) xs'\n | _,tp,x => tk ++ (tokenize_helper tp [x] xs')\n end\n end %char.\n\nDefinition tokenize (s : string) : list string :=\n map string_of_list (tokenize_helper white [] (list_of_string s)).\n\nExample tokenize_ex1 : \n tokenize \"abc12==3 223*(3+(a+c))\" %string\n = [\"abc\"; \"12\"; \"==\"; \"3\"; \"223\";\n \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n \"a\"; \"+\"; \"c\"; \")\"; \")\"]%string.\nProof. reflexivity. Qed.\n\n(* ####################################################### *)\n(** ** Parsing *)\n\n(* ####################################################### *)\n(** *** Options with Errors *)\n\n(* An option with error messages. *)\nInductive optionE (X:Type) : Type :=\n | SomeE : X -> optionE X\n | NoneE : string -> optionE X.\n\nImplicit Arguments SomeE [[X]].\nImplicit Arguments NoneE [[X]].\n\n(* Some syntactic sugar to make writing nested match-expressions on\n optionE more convenient. *)\n\nNotation \"'DO' ( x , y ) <== e1 ; e2\" \n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => NoneE err\n end)\n (right associativity, at level 60).\n\nNotation \"'DO' ( x , y ) <-- e1 ; e2 'OR' e3\" \n := (match e1 with\n | SomeE (x,y) => e2\n | NoneE err => e3\n end)\n (right associativity, at level 60, e2 at next level). \n\n(* ####################################################### *)\n(** *** Symbol Table *)\n\n(* Build a mapping from [tokens] to [nats]. A real parser would do\n this incrementally as it encountered new symbols, but passing\n around the symbol table inside the parsing functions is a bit\n inconvenient, so instead we do it as a first pass. *)\nFixpoint build_symtable (xs : list token) (n : nat) : (token -> nat) :=\n match xs with\n | [] => (fun s => n)\n | x::xs =>\n if (forallb isLowerAlpha (list_of_string x))\n then (fun s => if string_dec s x then n else (build_symtable xs (S n) s))\n else build_symtable xs n\n end.\n\n(* ####################################################### *)\n(** *** Generic Combinators for Building Parsers *)\n\nOpen Scope string_scope.\n\nDefinition parser (T : Type) := \n list token -> optionE (T * list token).\n\nFixpoint many_helper {T} (p : parser T) acc steps xs :=\nmatch steps, p xs with\n| 0, _ => NoneE \"Too many recursive calls\"\n| _, NoneE _ => SomeE ((rev acc), xs)\n| S steps', SomeE (t, xs') => many_helper p (t::acc) steps' xs'\nend.\n\n(* A (step-indexed) parser which expects zero or more [p]s *)\nFixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=\n many_helper p [] steps.\n\n(* A parser which expects a given token, followed by p *)\nDefinition firstExpect {T} (t : token) (p : parser T) : parser T :=\n fun xs => match xs with\n | x::xs' => if string_dec x t \n then p xs' \n else NoneE (\"expected '\" ++ t ++ \"'.\")\n | [] => NoneE (\"expected '\" ++ t ++ \"'.\")\n end. \n\n(* A parser which expects a particular token *)\nDefinition expect (t : token) : parser unit :=\n firstExpect t (fun xs => SomeE(tt, xs)).\n\n(* ####################################################### *)\n(** *** A Recursive-Descent Parser for Imp *)\n\n(* Identifiers *)\nDefinition parseIdentifier (symtable :string->nat) (xs : list token) \n : optionE (id * list token) :=\nmatch xs with\n| [] => NoneE \"Expected identifier\"\n| x::xs' => \n if forallb isLowerAlpha (list_of_string x) then\n SomeE (Id (symtable x), xs')\n else\n NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\nend.\n\n(* Numbers *)\nDefinition parseNumber (xs : list token) : optionE (nat * list token) :=\nmatch xs with \n| [] => NoneE \"Expected number\"\n| x::xs' => \n if forallb isDigit (list_of_string x) then\n SomeE (fold_left (fun n d =>\n 10 * n + (nat_of_ascii d - nat_of_ascii \"0\"%char))\n (list_of_string x)\n 0,\n xs')\n else \n NoneE \"Expected number\"\nend.\n\n(* Parse arithmetic expressions *)\nFixpoint parsePrimaryExp (steps:nat) symtable (xs : list token) \n : optionE (aexp * list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (i, rest) <-- parseIdentifier symtable xs ;\n SomeE (AId i, rest)\n OR DO (n, rest) <-- parseNumber xs ;\n SomeE (ANum n, rest)\n OR (DO (e, rest) <== firstExpect \"(\" (parseSumExp steps' symtable) xs;\n DO (u, rest') <== expect \")\" rest ;\n SomeE(e,rest'))\n end\nwith parseProductExp (steps:nat) symtable (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' => \n DO (e, rest) <== \n parsePrimaryExp steps' symtable xs ;\n DO (es, rest') <== \n many (firstExpect \"*\" (parsePrimaryExp steps' symtable)) steps' rest;\n SomeE (fold_left AMult es e, rest')\n end\nwith parseSumExp (steps:nat) symtable (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' => \n DO (e, rest) <== \n parseProductExp steps' symtable xs ;\n DO (es, rest') <== \n many (fun xs =>\n DO (e,rest') <-- \n firstExpect \"+\" (parseProductExp steps' symtable) xs;\n SomeE ( (true, e), rest')\n OR DO (e,rest') <== \n firstExpect \"-\" (parseProductExp steps' symtable) xs;\n SomeE ( (false, e), rest'))\n steps' rest;\n SomeE (fold_left (fun e0 term => \n match term with \n (true, e) => APlus e0 e\n | (false, e) => AMinus e0 e\n end)\n es e, \n rest') \n end.\n\nDefinition parseAExp := parseSumExp.\n\n(* Parsing boolean expressions. *)\nFixpoint parseAtomicExp (steps:nat) (symtable : string->nat) (xs : list token) :=\nmatch steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (u,rest) <-- expect \"true\" xs;\n SomeE (BTrue,rest)\n OR DO (u,rest) <-- expect \"false\" xs;\n SomeE (BFalse,rest)\n OR DO (e,rest) <-- firstExpect \"not\" (parseAtomicExp steps' symtable) xs;\n SomeE (BNot e, rest)\n OR DO (e,rest) <-- firstExpect \"(\" (parseConjunctionExp steps' symtable) xs;\n (DO (u,rest') <== expect \")\" rest; SomeE (e, rest'))\n OR DO (e, rest) <== parseProductExp steps' symtable xs ;\n (DO (e', rest') <-- \n firstExpect \"==\" (parseAExp steps' symtable) rest ;\n SomeE (BEq e e', rest')\n OR DO (e', rest') <-- \n firstExpect \"<=\" (parseAExp steps' symtable) rest ;\n SomeE (BLe e e', rest')\n OR\n NoneE \"Expected '==' or '<=' after arithmetic expression\")\nend\nwith parseConjunctionExp (steps:nat) (symtable : string->nat) (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' =>\n DO (e, rest) <== \n parseAtomicExp steps' symtable xs ;\n DO (es, rest') <== \n many (firstExpect \"&&\" (parseAtomicExp steps' symtable)) steps' rest;\n SomeE (fold_left BAnd es e, rest')\n end.\n\nDefinition parseBExp := parseConjunctionExp.\n\n(* \nEval compute in \n (parseProductExp 100 (tokenize \"x*y*(x*x)*x\")).\n\nEval compute in \n (parseDisjunctionExp 100 (tokenize \"not((x==x||x*x<=(x*x)*x)&&x==x)\")). \n*)\n\n(* Parsing commands *)\nFixpoint parseSimpleCommand (steps:nat) (symtable:string->nat) (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' => \n DO (u, rest) <-- expect \"SKIP\" xs;\n SomeE (SKIP, rest)\n OR DO (e,rest) <-- \n firstExpect \"IF\" (parseBExp steps' symtable) xs;\n DO (c,rest') <== \n firstExpect \"THEN\" (parseSequencedCommand steps' symtable) rest;\n DO (c',rest'') <== \n firstExpect \"ELSE\" (parseSequencedCommand steps' symtable) rest';\n DO (u,rest''') <== \n expect \"END\" rest'';\n SomeE(IFB e THEN c ELSE c' FI, rest''')\n OR DO (e,rest) <-- \n firstExpect \"WHILE\" (parseBExp steps' symtable) xs;\n DO (c,rest') <== \n firstExpect \"DO\" (parseSequencedCommand steps' symtable) rest;\n DO (u,rest'') <== \n expect \"END\" rest';\n SomeE(WHILE e DO c END, rest'')\n OR DO (i, rest) <== \n parseIdentifier symtable xs;\n DO (e, rest') <== \n firstExpect \":=\" (parseAExp steps' symtable) rest;\n SomeE(i ::= e, rest')\n end\n\nwith parseSequencedCommand (steps:nat) (symtable:string->nat) (xs : list token) :=\n match steps with\n | 0 => NoneE \"Too many recursive calls\"\n | S steps' => \n DO (c, rest) <== \n parseSimpleCommand steps' symtable xs;\n DO (c', rest') <-- \n firstExpect \";;\" (parseSequencedCommand steps' symtable) rest;\n SomeE(c ;; c', rest')\n OR\n SomeE(c, rest)\n end.\n\nDefinition bignumber := 1000.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n let tokens := tokenize str in\n parseSequencedCommand bignumber (build_symtable tokens 0) tokens.\n\n(* ####################################################### *)\n(** * Examples *)\n\n\n(*\nEval compute in parse \"\n IF x == y + 1 + 2 - y * 6 + 3 THEN\n x := x * 1;;\n y := 0\n ELSE\n SKIP\n END \".\n====>\n SomeE\n (IFB BEq (AId (Id 0))\n (APlus\n (AMinus (APlus (APlus (AId (Id 1)) (ANum 1)) (ANum 2))\n (AMult (AId (Id 1)) (ANum 6))) \n (ANum 3))\n THEN Id 0 ::= AMult (AId (Id 0)) (ANum 1);; Id 1 ::= ANum 0\n ELSE SKIP FI, [])\n*)\n\n(*\nEval compute in parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n====> \n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO \n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0) \n ELSE SKIP FI;; \n SKIP \n END;; \n Id 1 ::= AId (Id 0), \n []) \n*)\n\n(*\nEval compute in parse \"\n SKIP;;\n z:=x*y*(x*x);;\n WHILE x==x DO\n IF z <= z*z && not x == 2 THEN\n x := z;;\n y := z\n ELSE\n SKIP\n END;;\n SKIP\n END;;\n x:=z \".\n=====> \n SomeE\n (SKIP;;\n Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n (AMult (AId (Id 1)) (AId (Id 1)));;\n WHILE BEq (AId (Id 1)) (AId (Id 1)) DO \n IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n (BNot (BEq (AId (Id 1)) (ANum 2)))\n THEN Id 1 ::= AId (Id 0);; \n Id 2 ::= AId (Id 0) \n ELSE SKIP \n FI;; \n SKIP \n END;;\n Id 1 ::= AId (Id 0), \n []).\n*)\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/ImpParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.1347759261111811, "lm_q1q2_score": 0.06528277444824253}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(* ################################################################# *)\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward.\n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (mostly works), and Scheme (a bit\n out of date). *)\n\nExtraction Language Ocaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ################################################################# *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ################################################################# *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we first need\n to set up the right correspondence between Coq strings and lists\n of OCaml characters. *)\n\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlString.\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nRequire Import Imp.\nRequire Import ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ################################################################# *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(* ################################################################# *)\n(** * Going Further *)\n\n(** Further details about extraction can be found in the Extract\n chapter in _Verified Functional Algorithms_ (_Software\n Foundations_ volume 3). *)\n\n(** $Date: 2017-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/revisit/lf/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.14608724704829568, "lm_q1q2_score": 0.06508618110160412}} {"text": "(* *********************************************************************)\n(* *)\n(* The Compcert verified compiler *)\n(* *)\n(* Xavier Leroy, INRIA Paris *)\n(* *)\n(* Copyright Institut National de Recherche en Informatique et en *)\n(* Automatique. All rights reserved. This file is distributed *)\n(* under the terms of the INRIA Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n\n(** Correctness proof for x86-64 generation: main proof. *)\n\nRequire Import Coqlib Errors.\nRequire Import Integers Floats AST Linking.\nRequire Import Values Memory Events Globalenvs Smallstep.\nRequire Import Op Locations Mach Conventions Asm.\nRequire Import Asmgen Asmgenproof0 Asmgenproof1.\nRequire Import sflib.\n\nDefinition match_prog (p: Mach.program) (tp: Asm.program) :=\n match_program (fun _ f tf => transf_fundef f = OK tf) eq p tp.\n\nLemma transf_program_match:\n forall p tp, transf_program p = OK tp -> match_prog p tp.\nProof.\n intros. eapply match_transform_partial_program; eauto.\nQed.\n\nSection PRESERVATION.\n\nVariable prog: Mach.program.\nVariable tprog: Asm.program.\nHypothesis TRANSF: match_prog prog tprog.\n\nSection CORELEMMA.\n\nContext {CTX: main_args_ctx}.\nVariable se tse: Senv.t.\nHypothesis (MATCH_SENV: Senv.equiv se tse).\nVariable ge : Mach.genv.\nVariable tge : Asm.genv.\n\nHypothesis (MATCH_GENV: Genv.match_genvs (match_globdef (fun _ f tf => transf_fundef f = OK tf) eq prog) ge tge).\n\nLemma symbols_preserved:\n forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof (Genv.find_symbol_match_genv MATCH_GENV).\n\nLemma senv_preserved:\n Senv.equiv ge tge.\nProof (Genv.senv_match_genv MATCH_GENV).\n\nLemma functions_translated:\n forall b f,\n Genv.find_funct_ptr ge b = Some f ->\n exists tf,\n Genv.find_funct_ptr tge b = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial_genv MATCH_GENV).\n\nLemma functions_transl:\n forall fb f tf,\n Genv.find_funct_ptr ge fb = Some (Internal f) ->\n transf_function f = OK tf ->\n Genv.find_funct_ptr tge fb = Some (Internal tf).\nProof.\n intros. exploit functions_translated; eauto. intros [tf' [A B]].\n monadInv B. rewrite H0 in EQ; inv EQ; auto.\nQed.\n\n(** * Properties of control flow *)\n\nLemma transf_function_no_overflow:\n forall f tf,\n transf_function f = OK tf -> list_length_z (fn_code tf) <= Ptrofs.max_unsigned.\nProof.\n intros. monadInv H. destruct (zlt Ptrofs.max_unsigned (list_length_z (fn_code x))); monadInv EQ0.\n omega.\nQed.\n\nLemma exec_straight_exec:\n forall fb f c ep tf tc c' rs m rs' m',\n transl_code_at_pc ge (rs PC) fb f c ep tf tc ->\n exec_straight tge tf tc rs m c' rs' m' ->\n plus step tse tge (State rs m) E0 (State rs' m').\nProof.\n intros. inv H.\n eapply exec_straight_steps_1; eauto.\n eapply transf_function_no_overflow; eauto.\n eapply functions_transl; eauto.\nQed.\n\nLemma exec_straight_at:\n forall fb f c ep tf tc c' ep' tc' rs m rs' m',\n transl_code_at_pc ge (rs PC) fb f c ep tf tc ->\n transl_code f c' ep' = OK tc' ->\n exec_straight tge tf tc rs m tc' rs' m' ->\n transl_code_at_pc ge (rs' PC) fb f c' ep' tf tc'.\nProof.\n intros. inv H.\n exploit exec_straight_steps_2; eauto.\n eapply transf_function_no_overflow; eauto.\n eapply functions_transl; eauto.\n intros [ofs' [PC' CT']].\n rewrite PC'. constructor; auto.\nQed.\n\n(** The following lemmas show that the translation from Mach to Asm\n preserves labels, in the sense that the following diagram commutes:\n<<\n translation\n Mach code ------------------------ Asm instr sequence\n | |\n | Mach.find_label lbl find_label lbl |\n | |\n v v\n Mach code tail ------------------- Asm instr seq tail\n translation\n>>\n The proof demands many boring lemmas showing that Asm constructor\n functions do not introduce new labels.\n\n In passing, we also prove a \"is tail\" property of the generated Asm code.\n*)\n\nSection TRANSL_LABEL.\n\nRemark mk_mov_label:\n forall rd rs k c, mk_mov rd rs k = OK c -> tail_nolabel k c.\nProof.\n unfold mk_mov; intros.\n destruct rd; try discriminate; destruct rs; TailNoLabel.\nQed.\nHint Resolve mk_mov_label: labels.\n\nRemark mk_shrximm_label:\n forall n k c, mk_shrximm n k = OK c -> tail_nolabel k c.\nProof.\n intros. monadInv H; TailNoLabel.\nQed.\nHint Resolve mk_shrximm_label: labels.\n\nRemark mk_shrxlimm_label:\n forall n k c, mk_shrxlimm n k = OK c -> tail_nolabel k c.\nProof.\n intros. monadInv H. destruct (Int.eq n Int.zero); TailNoLabel.\nQed.\nHint Resolve mk_shrxlimm_label: labels.\n\nRemark mk_intconv_label:\n forall f r1 r2 k c, mk_intconv f r1 r2 k = OK c ->\n (forall r r', nolabel (f r r')) ->\n tail_nolabel k c.\nProof.\n unfold mk_intconv; intros. TailNoLabel.\nQed.\nHint Resolve mk_intconv_label: labels.\n\nRemark mk_storebyte_label:\n forall addr r k c, mk_storebyte addr r k = OK c -> tail_nolabel k c.\nProof.\n unfold mk_storebyte; intros. TailNoLabel.\nQed.\nHint Resolve mk_storebyte_label: labels.\n\nRemark loadind_label:\n forall base ofs ty dst k c,\n loadind base ofs ty dst k = OK c ->\n tail_nolabel k c.\nProof.\n unfold loadind; intros. destruct ty; try discriminate; destruct (preg_of dst); TailNoLabel.\nQed.\n\nRemark storeind_label:\n forall base ofs ty src k c,\n storeind src base ofs ty k = OK c ->\n tail_nolabel k c.\nProof.\n unfold storeind; intros. destruct ty; try discriminate; destruct (preg_of src); TailNoLabel.\nQed.\n\nRemark mk_setcc_base_label:\n forall xc rd k,\n tail_nolabel k (mk_setcc_base xc rd k).\nProof.\n intros. destruct xc; simpl; destruct (ireg_eq rd RAX); TailNoLabel.\nQed.\n\nRemark mk_setcc_label:\n forall xc rd k,\n tail_nolabel k (mk_setcc xc rd k).\nProof.\n intros. unfold mk_setcc. destruct (Archi.ptr64 || low_ireg rd).\n apply mk_setcc_base_label.\n eapply tail_nolabel_trans. apply mk_setcc_base_label. TailNoLabel.\nQed.\n\nRemark mk_jcc_label:\n forall xc lbl' k,\n tail_nolabel k (mk_jcc xc lbl' k).\nProof.\n intros. destruct xc; simpl; TailNoLabel.\nQed.\n\nRemark mk_sel_label:\n forall xc rd r2 k c,\n mk_sel xc rd r2 k = OK c ->\n tail_nolabel k c.\nProof.\n unfold mk_sel; intros; destruct xc; inv H; TailNoLabel.\nQed.\n\nRemark transl_cond_label:\n forall cond args k c,\n transl_cond cond args k = OK c ->\n tail_nolabel k c.\nProof.\n unfold transl_cond; intros.\n destruct cond; TailNoLabel.\n destruct (Int.eq_dec n Int.zero); TailNoLabel.\n destruct (Int64.eq_dec n Int64.zero); TailNoLabel.\n destruct c0; simpl; TailNoLabel.\n destruct c0; simpl; TailNoLabel.\n destruct c0; simpl; TailNoLabel.\n destruct c0; simpl; TailNoLabel.\nQed.\n\nRemark transl_op_label:\n forall op args r k c,\n transl_op op args r k = OK c ->\n tail_nolabel k c.\nProof.\n unfold transl_op; intros. destruct op; TailNoLabel.\n destruct (Int.eq_dec n Int.zero); TailNoLabel.\n destruct (Int64.eq_dec n Int64.zero); TailNoLabel.\n destruct (Float.eq_dec n Float.zero); TailNoLabel.\n destruct (Float32.eq_dec n Float32.zero); TailNoLabel.\n destruct (normalize_addrmode_64 x) as [am' [delta|]]; TailNoLabel.\n eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_setcc_label.\n unfold transl_sel in EQ2. destruct (ireg_eq x x0); monadInv EQ2.\n TailNoLabel.\n eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_sel_label; eauto.\nQed.\n\nRemark transl_load_label:\n forall chunk addr args dest k c,\n transl_load chunk addr args dest k = OK c ->\n tail_nolabel k c.\nProof.\n intros. monadInv H. destruct chunk; TailNoLabel.\nQed.\n\nRemark transl_store_label:\n forall chunk addr args src k c,\n transl_store chunk addr args src k = OK c ->\n tail_nolabel k c.\nProof.\n intros. monadInv H. destruct chunk; TailNoLabel.\nQed.\n\nLemma transl_instr_label:\n forall f i ep k c,\n transl_instr f i ep k = OK c ->\n match i with Mlabel lbl => c = Plabel lbl :: k | _ => tail_nolabel k c end.\nProof.\nOpaque loadind.\n unfold transl_instr; intros; destruct i; TailNoLabel.\n eapply loadind_label; eauto.\n eapply storeind_label; eauto.\n eapply loadind_label; eauto.\n eapply tail_nolabel_trans; eapply loadind_label; eauto.\n eapply transl_op_label; eauto.\n eapply transl_load_label; eauto.\n eapply transl_store_label; eauto.\n destruct s0; TailNoLabel.\n destruct s0; TailNoLabel.\n eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_jcc_label.\nQed.\n\nLemma transl_instr_label':\n forall lbl f i ep k c,\n transl_instr f i ep k = OK c ->\n find_label lbl c = if Mach.is_label lbl i then Some k else find_label lbl k.\nProof.\n intros. exploit transl_instr_label; eauto.\n destruct i; try (intros [A B]; apply B).\n intros. subst c. simpl. auto.\nQed.\n\nLemma transl_code_label:\n forall lbl f c ep tc,\n transl_code f c ep = OK tc ->\n match Mach.find_label lbl c with\n | None => find_label lbl tc = None\n | Some c' => exists tc', find_label lbl tc = Some tc' /\\ transl_code f c' false = OK tc'\n end.\nProof.\n induction c; simpl; intros.\n inv H. auto.\n monadInv H. rewrite (transl_instr_label' lbl _ _ _ _ _ EQ0).\n generalize (Mach.is_label_correct lbl a).\n destruct (Mach.is_label lbl a); intros.\n subst a. simpl in EQ. exists x; auto.\n eapply IHc; eauto.\nQed.\n\nLemma transl_find_label:\n forall lbl f tf,\n transf_function f = OK tf ->\n match Mach.find_label lbl f.(Mach.fn_code) with\n | None => find_label lbl tf.(fn_code) = None\n | Some c => exists tc, find_label lbl tf.(fn_code) = Some tc /\\ transl_code f c false = OK tc\n end.\nProof.\n intros. monadInv H. destruct (zlt Ptrofs.max_unsigned (list_length_z (fn_code x))); inv EQ0.\n monadInv EQ. simpl. eapply transl_code_label; eauto. rewrite transl_code'_transl_code in EQ0; eauto.\nQed.\n\nEnd TRANSL_LABEL.\n\n(** A valid branch in a piece of Mach code translates to a valid ``go to''\n transition in the generated PPC code. *)\n\nLemma find_label_goto_label:\n forall f tf lbl rs m c' b ofs,\n Genv.find_funct_ptr ge b = Some (Internal f) ->\n transf_function f = OK tf ->\n rs PC = Vptr b ofs ->\n Mach.find_label lbl f.(Mach.fn_code) = Some c' ->\n exists tc', exists rs',\n goto_label tf lbl rs m = Next rs' m\n /\\ transl_code_at_pc ge (rs' PC) b f c' false tf tc'\n /\\ forall r, r <> PC -> rs'#r = rs#r.\nProof.\n intros. exploit (transl_find_label lbl f tf); eauto. rewrite H2.\n intros [tc [A B]].\n exploit label_pos_code_tail; eauto. instantiate (1 := 0).\n intros [pos' [P [Q R]]].\n exists tc; exists (rs#PC <- (Vptr b (Ptrofs.repr pos'))).\n split. unfold goto_label. rewrite P. rewrite H1. auto.\n split. rewrite Pregmap.gss. constructor; auto.\n rewrite Ptrofs.unsigned_repr. replace (pos' - 0) with pos' in Q.\n auto. omega.\n generalize (transf_function_no_overflow _ _ H0). omega.\n intros. apply Pregmap.gso; auto.\nQed.\n\n(** Existence of return addresses *)\n\nLemma return_address_exists:\n forall f sg ros c id (FUNCT: In (id, Gfun (Internal f)) (prog_defs prog)), is_tail (Mcall sg ros :: c) f.(Mach.fn_code) ->\n exists ra, return_address_offset f c ra.\nProof.\n intros.\n assert(TF: exists tf, transf_function f = OK tf).\n { inv TRANSF.\n eapply list_forall2_in_left in H0; eauto.\n des. inv H2. ss. clarify. inv H5. ss. monadInv H7. esplits; eauto.\n } des.\n eapply Asmgenproof0.return_address_exists; eauto.\n- intros. exploit transl_instr_label; eauto.\n destruct i; try (intros [A B]; apply A). intros. subst c0. repeat constructor.\n- intros. monadInv TF.\n destruct (zlt Ptrofs.max_unsigned (list_length_z (fn_code x))); inv EQ0.\n monadInv EQ. rewrite transl_code'_transl_code in EQ0.\n exists x; exists true; split; auto. unfold fn_code. repeat constructor.\n- eapply transf_function_no_overflow; eauto.\nQed.\n\n(** * Proof of semantic preservation *)\n\n(** Semantic preservation is proved using simulation diagrams\n of the following form.\n<<\n st1 --------------- st2\n | |\n t| *|t\n | |\n v v\n st1'--------------- st2'\n>>\n The invariant is the [match_states] predicate below, which includes:\n- The PPC code pointed by the PC register is the translation of\n the current Mach code sequence.\n- Mach register values and PPC register values agree.\n*)\n\nInductive match_states: Mach.state -> Asm.state -> Prop :=\n | match_states_dummy sp v rs m rs0 m0 (EXT: Mem.extends m m0):\n match_states (Mach.State [] sp v [] rs m) (State rs0 m0)\n | match_states_intro:\n forall s fb sp c ep ms m m' rs f tf tc\n (STACKS: match_stack ge s)\n (OFSZERO: forall ofs blk (SPOFS: sp = Vptr blk ofs), ofs = Ptrofs.zero)\n (FIND: Genv.find_funct_ptr ge fb = Some (Internal f))\n (MEXT: Mem.extends m m')\n (AT: transl_code_at_pc ge (rs PC) fb f c ep tf tc)\n (AG: agree ms sp rs)\n (AXP: ep = true -> rs#RAX = parent_sp s),\n match_states (Mach.State s fb sp c ms m)\n (Asm.State rs m')\n | match_states_call:\n forall s fptr ms m m' rs\n (STACKS: match_stack ge s)\n (MEXT: Mem.extends m m')\n (AG: agree ms (parent_sp s) rs)\n (* (ATPC: rs PC = Vptr fb Ptrofs.zero) *)\n (FPTR: Val.lessdef fptr (rs PC))\n (ATLR: Val.lessdef (parent_ra s) (rs RA)),\n match_states (Mach.Callstate s fptr ms m)\n (Asm.State rs m')\n | match_states_return:\n forall s ms m m' rs\n (STACKS: match_stack ge s)\n (MEXT: Mem.extends m m')\n (AG: agree ms (parent_sp s) rs)\n (ATPC: Val.lessdef (parent_ra s) (rs PC)),\n match_states (Mach.Returnstate s ms m)\n (Asm.State rs m').\n\nLemma exec_straight_steps:\n forall s fb f rs1 i c ep tf tc m1' m2 m2' sp ms2,\n match_stack ge s ->\n forall (OFSZERO: forall ofs blk (SPOFS: sp = Vptr blk ofs), ofs = Ptrofs.zero),\n Mem.extends m2 m2' ->\n Genv.find_funct_ptr ge fb = Some (Internal f) ->\n transl_code_at_pc ge (rs1 PC) fb f (i :: c) ep tf tc ->\n (forall k c (TR: transl_instr f i ep k = OK c),\n exists rs2,\n exec_straight tge tf c rs1 m1' k rs2 m2'\n /\\ agree ms2 sp rs2\n /\\ (it1_is_parent ep i = true -> rs2#RAX = parent_sp s)) ->\n exists st',\n plus step tse tge (State rs1 m1') E0 st' /\\\n match_states (Mach.State s fb sp c ms2 m2) st'.\nProof.\n intros. inversion H2. subst. monadInv H7.\n exploit H3; eauto. intros [rs2 [A [B C]]].\n exists (State rs2 m2'); split.\n eapply exec_straight_exec; eauto.\n econstructor; eauto. eapply exec_straight_at; eauto.\nQed.\n\nLemma exec_straight_steps_goto:\n forall s fb f rs1 i c ep tf tc m1' m2 m2' sp ms2 lbl c',\n match_stack ge s ->\n forall (OFSZERO: forall ofs blk (SPOFS: sp = Vptr blk ofs), ofs = Ptrofs.zero),\n Mem.extends m2 m2' ->\n Genv.find_funct_ptr ge fb = Some (Internal f) ->\n Mach.find_label lbl f.(Mach.fn_code) = Some c' ->\n transl_code_at_pc ge (rs1 PC) fb f (i :: c) ep tf tc ->\n it1_is_parent ep i = false ->\n (forall k c (TR: transl_instr f i ep k = OK c),\n exists jmp, exists k', exists rs2,\n exec_straight tge tf c rs1 m1' (jmp :: k') rs2 m2'\n /\\ agree ms2 sp rs2\n /\\ exec_instr tge tf jmp rs2 m2' = goto_label tf lbl rs2 m2') ->\n exists st',\n plus step tse tge (State rs1 m1') E0 st' /\\\n match_states (Mach.State s fb sp c' ms2 m2) st'.\nProof.\n intros. inversion H3. subst. monadInv H9.\n exploit H5; eauto. intros [jmp [k' [rs2 [A [B C]]]]].\n generalize (functions_transl _ _ _ H7 H8); intro FN.\n generalize (transf_function_no_overflow _ _ H8); intro NOOV.\n exploit exec_straight_steps_2; eauto.\n intros [ofs' [PC2 CT2]].\n exploit find_label_goto_label; eauto.\n intros [tc' [rs3 [GOTO [AT' OTH]]]].\n exists (State rs3 m2'); split.\n eapply plus_right'.\n eapply exec_straight_steps_1; eauto.\n econstructor; eauto.\n eapply find_instr_tail. eauto.\n rewrite C. eexact GOTO.\n traceEq.\n econstructor; eauto.\n apply agree_exten with rs2; auto with asmgen.\n congruence.\nQed.\n\n(** We need to show that, in the simulation diagram, we cannot\n take infinitely many Mach transitions that correspond to zero\n transitions on the PPC side. Actually, all Mach transitions\n correspond to at least one Asm transition, except the\n transition from [Mach.Returnstate] to [Mach.State].\n So, the following integer measure will suffice to rule out\n the unwanted behaviour. *)\n\nDefinition measure (s: Mach.state) : nat :=\n match s with\n | Mach.State _ _ _ _ _ _ => 0%nat\n | Mach.Callstate _ _ _ _ => 0%nat\n | Mach.Returnstate _ _ _ => 1%nat\n end.\n\n(** This is the simulation diagram. We prove it by case analysis on the Mach transition. *)\n\nTheorem step_simulation:\n forall S1 t S2, Mach.step return_address_offset se ge S1 t S2 ->\n forall S1' (MS: match_states S1 S1'),\n (exists S2', plus step tse tge S1' t S2' /\\ match_states S2 S2')\n \\/ (measure S2 < measure S1 /\\ t = E0 /\\ match_states S2 S1')%nat.\nProof.\n induction 1; intros; inv MS.\n\n- (* Mlabel *)\n left; eapply exec_straight_steps; eauto; intros.\n monadInv TR. econstructor; split. apply exec_straight_one. simpl; eauto. auto.\n split. apply agree_nextinstr; auto. simpl; congruence.\n\n- (* Mgetstack *)\n unfold load_stack in H.\n exploit Mem.loadv_extends; eauto. intros [v' [A B]].\n rewrite (sp_val _ _ _ AG) in A.\n left; eapply exec_straight_steps; eauto. intros. simpl in TR.\n exploit loadind_correct; eauto. intros [rs' [P [Q R]]].\n exists rs'; split. eauto.\n split. eapply agree_set_mreg; eauto. congruence.\n simpl; congruence.\n\n- (* Msetstack *)\n unfold store_stack in H.\n assert (Val.lessdef (rs src) (rs0 (preg_of src))). eapply preg_val; eauto.\n exploit Mem.storev_extends; eauto. intros [m2' [A B]].\n left; eapply exec_straight_steps; eauto.\n rewrite (sp_val _ _ _ AG) in A. intros. simpl in TR.\n exploit storeind_correct; eauto. intros [rs' [P Q]].\n exists rs'; split. eauto.\n split. eapply agree_undef_regs; eauto.\n simpl; intros. rewrite Q; auto with asmgen.\nLocal Transparent destroyed_by_setstack.\n destruct ty; simpl; intuition congruence.\n\n- (* Mgetparam *)\n assert (f0 = f) by congruence; subst f0.\n unfold load_stack in *.\n exploit Mem.loadv_extends. eauto. eexact H0. auto.\n intros [parent' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n exploit lessdef_parent_sp; eauto. clear B; intros B; subst parent'.\n exploit Mem.loadv_extends. eauto. eexact H1. auto.\n intros [v' [C D]].\nOpaque loadind.\n left; eapply exec_straight_steps; eauto; intros.\n assert (DIFF: negb (mreg_eq dst AX) = true -> IR RAX <> preg_of dst).\n intros. change (IR RAX) with (preg_of AX). red; intros.\n unfold proj_sumbool in H1. destruct (mreg_eq dst AX); try discriminate.\n elim n. eapply preg_of_injective; eauto.\n destruct ep; simpl in TR.\n(* RAX contains parent *)\n exploit loadind_correct. eexact TR.\n instantiate (2 := rs0). rewrite AXP; eauto.\n intros [rs1 [P [Q R]]].\n exists rs1; split. eauto.\n split. eapply agree_set_mreg. eapply agree_set_mreg; eauto. congruence. auto.\n simpl; intros. rewrite R; auto.\n(* RAX does not contain parent *)\n monadInv TR.\n exploit loadind_correct. eexact EQ0. eauto. intros [rs1 [P [Q R]]]. simpl in Q.\n exploit loadind_correct. eexact EQ. instantiate (2 := rs1). rewrite Q. eauto.\n intros [rs2 [S [T U]]].\n exists rs2; split. eapply exec_straight_trans; eauto.\n split. eapply agree_set_mreg. eapply agree_set_mreg; eauto. congruence. auto.\n simpl; intros. rewrite U; auto.\n\n- (* Mop *)\n assert (eval_operation tge sp op rs##args m = Some v).\n rewrite <- H. apply eval_operation_preserved. exact symbols_preserved.\n exploit eval_operation_lessdef. eapply preg_vals; eauto. eauto. eexact H0.\n intros [v' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n left; eapply exec_straight_steps; eauto; intros. simpl in TR.\n exploit transl_op_correct; eauto. intros [rs2 [P [Q R]]].\n assert (S: Val.lessdef v (rs2 (preg_of res))) by (eapply Val.lessdef_trans; eauto).\n exists rs2; split. eauto.\n split. eapply agree_set_undef_mreg; eauto.\n simpl; congruence.\n\n- (* Mload *)\n assert (eval_addressing tge sp addr rs##args = Some a).\n rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.\n exploit eval_addressing_lessdef. eapply preg_vals; eauto. eexact H1.\n intros [a' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n exploit Mem.loadv_extends; eauto. intros [v' [C D]].\n left; eapply exec_straight_steps; eauto; intros. simpl in TR.\n exploit transl_load_correct; eauto. intros [rs2 [P [Q R]]].\n exists rs2; split. eauto.\n split. eapply agree_set_undef_mreg; eauto. congruence.\n simpl; congruence.\n\n- (* Mstore *)\n assert (eval_addressing tge sp addr rs##args = Some a).\n rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.\n exploit eval_addressing_lessdef. eapply preg_vals; eauto. eexact H1.\n intros [a' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n assert (Val.lessdef (rs src) (rs0 (preg_of src))). eapply preg_val; eauto.\n exploit Mem.storev_extends; eauto. intros [m2' [C D]].\n left; eapply exec_straight_steps; eauto.\n intros. simpl in TR.\n exploit transl_store_correct; eauto. intros [rs2 [P Q]].\n exists rs2; split. eauto.\n split. eapply agree_undef_regs; eauto.\n simpl; congruence.\n\n- (* Mcall *)\n assert (f0 = f) by congruence. subst f0.\n inv AT.\n assert (NOOV: list_length_z tf.(fn_code) <= Ptrofs.max_unsigned).\n eapply transf_function_no_overflow; eauto.\n destruct ros as [rf|fid]; simpl in H; monadInv H5.\n+ (* Indirect call *)\n inv H.\n assert(Val.lessdef (rs rf) (rs0 x0)).\n exploit ireg_val; eauto.\n generalize (code_tail_next_int _ _ _ _ NOOV H6). intro CT1.\n assert (TCA: transl_code_at_pc ge (Vptr fb (Ptrofs.add ofs Ptrofs.one)) fb f c false tf x).\n econstructor; eauto.\n exploit return_address_offset_correct; eauto. intros; subst ra.\n left; econstructor; split.\n apply plus_one. eapply exec_step_internal. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. eauto.\n econstructor; eauto.\n econstructor; eauto.\n eapply agree_sp_def; eauto.\n simpl. eapply agree_exten; eauto. intros. Simplifs.\n Simplifs. rewrite <- H2. auto.\n+ (* Direct call *)\n (* destruct (Genv.find_symbol ge fid) eqn:T; inv H; clarify. *)\n generalize (code_tail_next_int _ _ _ _ NOOV H6). intro CT1.\n assert (TCA: transl_code_at_pc ge (Vptr fb (Ptrofs.add ofs Ptrofs.one)) fb f c false tf x).\n econstructor; eauto.\n exploit return_address_offset_correct; eauto. intros; subst ra.\n left; econstructor; split.\n apply plus_one. eapply exec_step_internal. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. unfold Genv.symbol_address. rewrite symbols_preserved. rewrite H. eauto.\n econstructor; eauto.\n econstructor; eauto.\n eapply agree_sp_def; eauto.\n simpl. eapply agree_exten; eauto. intros. Simplifs.\n Simplifs. rewrite <- H2. auto.\n\n- (* Mtailcall *)\n assert (f0 = f) by congruence. subst f0.\n inv AT.\n assert (NOOV: list_length_z tf.(fn_code) <= Ptrofs.max_unsigned).\n eapply transf_function_no_overflow; eauto.\n rewrite (sp_val _ _ _ AG) in *. unfold load_stack in *.\n exploit Mem.loadv_extends. eauto. eexact H1. auto. simpl. intros [parent' [A B]].\n exploit Mem.loadv_extends. eauto. eexact H2. auto. simpl. intros [ra' [C D]].\n exploit lessdef_parent_sp; eauto. intros. subst parent'. clear B.\n exploit Mem.free_parallel_extends; eauto. intros [m2' [E F]].\n destruct ros as [rf|fid]; simpl in H; monadInv H7.\n+ (* Indirect call *)\n clarify.\n assert(Val.lessdef (rs rf) (rs0 x0)).\n exploit ireg_val; eauto.\n generalize (code_tail_next_int _ _ _ _ NOOV H8). intro CT1.\n left; econstructor; split.\n eapply plus_left. eapply exec_step_internal. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. replace (chunk_of_type Tptr) with Mptr in * by (unfold Tptr, Mptr; destruct Archi.ptr64; auto).\n rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG) in *. exploit OFSZERO; eauto. i. clarify.\n rewrite Ptrofs.unsigned_zero in *. rewrite Z.add_0_l in *. rewrite E. eauto.\n apply star_one. eapply exec_step_internal.\n transitivity (Val.offset_ptr rs0#PC Ptrofs.one). auto. rewrite <- H4. simpl. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. eauto. traceEq.\n econstructor; eauto.\n apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.\n eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.\n cbn. rewrite <- H. Simplifs. rewrite Pregmap.gso; auto. \n generalize (preg_of_not_SP rf). rewrite (ireg_of_eq _ _ EQ1). congruence.\n+ (* Direct call *)\n generalize (code_tail_next_int _ _ _ _ NOOV H8). intro CT1.\n left; econstructor; split.\n eapply plus_left. eapply exec_step_internal. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. replace (chunk_of_type Tptr) with Mptr in * by (unfold Tptr, Mptr; destruct Archi.ptr64; auto).\n rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG) in *. exploit OFSZERO; eauto. i. clarify.\n rewrite Ptrofs.unsigned_zero in *. rewrite Z.add_0_l in *. rewrite E. eauto.\n apply star_one. eapply exec_step_internal.\n transitivity (Val.offset_ptr rs0#PC Ptrofs.one). auto. rewrite <- H4. simpl. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. eauto. traceEq.\n econstructor; eauto.\n apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.\n eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.\n rewrite Pregmap.gss. unfold Genv.symbol_address. rewrite symbols_preserved. rewrite H. auto.\n\n- (* Mbuiltin *)\n inv AT. monadInv H4.\n exploit functions_transl; eauto. intro FN.\n generalize (transf_function_no_overflow _ _ H3); intro NOOV.\n exploit builtin_args_match; eauto. intros [vargs' [P Q]].\n exploit external_call_mem_extends; eauto.\n intros [vres' [m2' [A [B [C D]]]]].\n left. econstructor; split. apply plus_one.\n eapply exec_step_builtin. eauto. eauto.\n eapply find_instr_tail; eauto.\n erewrite <- sp_val by eauto.\n eapply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n eapply external_call_symbols_preserved; eauto.\n eauto.\n econstructor; eauto.\n instantiate (2 := tf); instantiate (1 := x).\n unfold nextinstr_nf, nextinstr. rewrite Pregmap.gss.\n rewrite undef_regs_other. rewrite set_res_other. rewrite undef_regs_other_2.\n rewrite <- H1. simpl. econstructor; eauto.\n eapply code_tail_next_int; eauto.\n rewrite preg_notin_charact. intros. auto with asmgen.\n auto with asmgen.\n simpl; intros. intuition congruence.\n apply agree_nextinstr_nf. eapply agree_set_res; auto.\n eapply agree_undef_regs; eauto. intros; apply undef_regs_other_2; auto.\n congruence.\n\n- (* Mgoto *)\n assert (f0 = f) by congruence. subst f0.\n inv AT. monadInv H4.\n exploit find_label_goto_label; eauto. intros [tc' [rs' [GOTO [AT2 INV]]]].\n left; exists (State rs' m'); split.\n apply plus_one. econstructor; eauto.\n eapply functions_transl; eauto.\n eapply find_instr_tail; eauto.\n simpl; eauto.\n econstructor; eauto.\n eapply agree_exten; eauto with asmgen.\n congruence.\n\n- (* Mcond true *)\n assert (f0 = f) by congruence. subst f0.\n exploit eval_condition_lessdef. eapply preg_vals; eauto. eauto. eauto. intros EC.\n left; eapply exec_straight_steps_goto; eauto.\n intros. simpl in TR.\n destruct (transl_cond_correct tge tf cond args _ _ rs0 m' TR)\n as [rs' [A [B C]]].\n rewrite EC in B. destruct B as [B _].\n destruct (testcond_for_condition cond); simpl in *.\n(* simple jcc *)\n exists (Pjcc c1 lbl); exists k; exists rs'.\n split. eexact A.\n split. eapply agree_exten; eauto.\n simpl. rewrite B. auto.\n(* jcc; jcc *)\n destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n destruct b1.\n (* first jcc jumps *)\n exists (Pjcc c1 lbl); exists (Pjcc c2 lbl :: k); exists rs'.\n split. eexact A.\n split. eapply agree_exten; eauto.\n simpl. rewrite TC1. auto.\n (* second jcc jumps *)\n exists (Pjcc c2 lbl); exists k; exists (nextinstr rs').\n split. eapply exec_straight_trans. eexact A.\n eapply exec_straight_one. simpl. rewrite TC1. auto. auto.\n split. eapply agree_exten; eauto.\n intros; Simplifs.\n simpl. rewrite eval_testcond_nextinstr. rewrite TC2.\n destruct b2; auto || discriminate.\n(* jcc2 *)\n destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n destruct (andb_prop _ _ H3). subst.\n exists (Pjcc2 c1 c2 lbl); exists k; exists rs'.\n split. eexact A.\n split. eapply agree_exten; eauto.\n simpl. rewrite TC1; rewrite TC2; auto.\n\n- (* Mcond false *)\n exploit eval_condition_lessdef. eapply preg_vals; eauto. eauto. eauto. intros EC.\n left; eapply exec_straight_steps; eauto. intros. simpl in TR.\n destruct (transl_cond_correct tge tf cond args _ _ rs0 m' TR)\n as [rs' [A [B C]]].\n rewrite EC in B. destruct B as [B _].\n destruct (testcond_for_condition cond); simpl in *.\n(* simple jcc *)\n econstructor; split.\n eapply exec_straight_trans. eexact A.\n apply exec_straight_one. simpl. rewrite B. eauto. auto.\n split. apply agree_nextinstr. eapply agree_exten; eauto.\n simpl; congruence.\n(* jcc ; jcc *)\n destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n destruct (orb_false_elim _ _ H1); subst.\n econstructor; split.\n eapply exec_straight_trans. eexact A.\n eapply exec_straight_two. simpl. rewrite TC1. eauto. auto.\n simpl. rewrite eval_testcond_nextinstr. rewrite TC2. eauto. auto. auto.\n split. apply agree_nextinstr. apply agree_nextinstr. eapply agree_exten; eauto.\n simpl; congruence.\n(* jcc2 *)\n destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n exists (nextinstr rs'); split.\n eapply exec_straight_trans. eexact A.\n apply exec_straight_one. simpl.\n rewrite TC1; rewrite TC2.\n destruct b1. simpl in *. subst b2. auto. auto.\n auto.\n split. apply agree_nextinstr. eapply agree_exten; eauto.\n rewrite H1; congruence.\n\n- (* Mjumptable *)\n assert (f0 = f) by congruence. subst f0.\n inv AT. monadInv H6.\n exploit functions_transl; eauto. intro FN.\n generalize (transf_function_no_overflow _ _ H5); intro NOOV.\n set (rs1 := rs0 #RAX <- Vundef #RDX <- Vundef).\n exploit (find_label_goto_label f tf lbl rs1); eauto.\n intros [tc' [rs' [A [B C]]]].\n exploit ireg_val; eauto. rewrite H. intros LD; inv LD.\n left; econstructor; split.\n apply plus_one. econstructor; eauto.\n eapply find_instr_tail; eauto.\n simpl. rewrite <- H9. unfold Mach.label in H0; unfold label; rewrite H0. eexact A.\n econstructor; eauto.\nTransparent destroyed_by_jumptable.\n apply agree_undef_regs with rs0; auto.\n simpl; intros. destruct H8. rewrite C by auto with asmgen. unfold rs1; Simplifs.\n congruence.\n\n- (* Mreturn *)\n assert (f0 = f) by congruence. subst f0.\n inv AT.\n assert (NOOV: list_length_z tf.(fn_code) <= Ptrofs.max_unsigned).\n eapply transf_function_no_overflow; eauto.\n rewrite (sp_val _ _ _ AG) in *. unfold load_stack in *.\n replace (chunk_of_type Tptr) with Mptr in * by (unfold Tptr, Mptr; destruct Archi.ptr64; auto).\n exploit Mem.loadv_extends. eauto. eexact H0. auto. simpl. intros [parent' [A B]].\n exploit lessdef_parent_sp; eauto. intros. subst parent'. clear B.\n exploit Mem.loadv_extends. eauto. eexact H1. auto. simpl. intros [ra' [C D]].\n exploit Mem.free_parallel_extends; eauto. intros [m2' [E F]].\n monadInv H6.\n exploit code_tail_next_int; eauto. intro CT1.\n left; econstructor; split.\n eapply plus_left. eapply exec_step_internal. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG) in *. exploit OFSZERO; eauto. i. clarify.\n rewrite Ptrofs.unsigned_zero in *. rewrite Z.add_0_l in *. rewrite E. eauto.\n apply star_one. eapply exec_step_internal.\n transitivity (Val.offset_ptr rs0#PC Ptrofs.one). auto. rewrite <- H3. simpl. eauto.\n eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n simpl. eauto. traceEq.\n constructor; auto.\n apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.\n eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.\n\n- (* internal function *)\n inv FPTR0. rename H5 into ATPC. symmetry in ATPC.\n exploit functions_translated; eauto. intros [tf [A B]]. monadInv B.\n generalize EQ; intros EQ'. monadInv EQ'.\n destruct (zlt Ptrofs.max_unsigned (list_length_z (fn_code x0))); inv EQ1.\n monadInv EQ0. rewrite transl_code'_transl_code in EQ1.\n unfold store_stack in *.\n exploit Mem.alloc_extends. eauto. eauto. apply Z.le_refl. apply Z.le_refl.\n intros [m1' [C D]].\n exploit Mem.storev_extends. eexact D. eexact H1. eauto. eauto.\n intros [m2' [F G]].\n exploit Mem.storev_extends. eexact G. eexact H2. eauto. exact ATLR.\n intros [m3' [P Q]].\n left; econstructor; split.\n apply plus_one. econstructor; eauto.\n simpl. rewrite Ptrofs.unsigned_zero. simpl. eauto.\n simpl. rewrite C. simpl in F, P.\n replace (chunk_of_type Tptr) with Mptr in F, P by (unfold Tptr, Mptr; destruct Archi.ptr64; auto).\n rewrite (sp_val _ _ _ AG) in F. rewrite F.\n rewrite P. eauto.\n econstructor; eauto.\n ii. unfold sp in *. clarify.\n unfold nextinstr. rewrite Pregmap.gss. repeat rewrite Pregmap.gso; auto with asmgen.\n rewrite ATPC. simpl. constructor; eauto.\n unfold fn_code. eapply code_tail_next_int. simpl in g. omega.\n constructor.\n apply agree_nextinstr. eapply agree_change_sp; eauto.\nTransparent destroyed_at_function_entry.\n apply agree_undef_regs with rs0; eauto.\n simpl; intros. apply Pregmap.gso; auto with asmgen. tauto.\n congruence.\n intros. Simplifs. eapply agree_sp; eauto.\n\n- (* external function *)\n exploit Genv.find_funct_inv; eauto. i; des. clarify. inv FPTR. rename H4 into ATPC. symmetry in ATPC. rewrite Genv.find_funct_find_funct_ptr in H.\n exploit functions_translated; eauto.\n intros [tf [A B]]. simpl in B. inv B.\n exploit extcall_arguments_match; eauto.\n intros [args' [C D]].\n exploit external_call_mem_extends; eauto.\n intros [res' [m2' [P [Q [R S]]]]].\n left; econstructor; split.\n apply plus_one. eapply exec_step_external; eauto.\n eapply external_call_symbols_preserved; eauto.\n econstructor; eauto.\n unfold loc_external_result. apply agree_set_other; auto. apply agree_set_pair; auto.\n rewrite regset_after_external_eq.\n apply agree_undef_caller_save_regs; auto. \n\n- (* return *)\n inv STACKS; simpl in *. { right. esplits; eauto. econs. auto. }\n right. split. omega. split. auto.\n econstructor; eauto. replace (rs0 PC) with ra; eauto.\n { inv H5. inv ATPC. auto. } congruence.\nQed.\n\nEnd CORELEMMA.\n\nSection WHOLE.\n\nLocal Existing Instance main_args_none.\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLet MATCH_GENV: Genv.match_genvs (match_globdef (fun _ f tf => transf_fundef f = OK tf) eq prog) ge tge.\nProof. apply Genv.globalenvs_match; auto. Qed.\n\nLemma transf_initial_states:\n forall st1, Mach.initial_state prog st1 ->\n exists st2, Asm.initial_state tprog st2 /\\ match_states ge st1 st2.\nProof.\n intros. inversion H. unfold ge0 in *.\n econstructor; split.\n econstructor.\n eapply (Genv.init_mem_transf_partial TRANSF); eauto.\n replace (Genv.symbol_address (Genv.globalenv tprog) (prog_main tprog) Ptrofs.zero)\n with (Vptr fb Ptrofs.zero).\n econstructor; eauto.\n constructor. auto.\n apply Mem.extends_refl.\n split. reflexivity. simpl.\n unfold Vnullptr; destruct Archi.ptr64; congruence.\n intros. rewrite Regmap.gi. auto.\n unfold Genv.symbol_address.\n rewrite (match_program_main TRANSF).\n erewrite symbols_preserved; eauto.\n unfold ge; rewrite H1. auto.\nQed.\n\nLemma transf_final_states:\n forall st1 st2 r,\n match_states ge st1 st2 -> Mach.final_state st1 r -> Asm.final_state st2 r.\nProof.\n intros. inv H0. inv H. constructor. { inv ATPC. auto. } auto.\n assert (r0 = AX).\n { unfold loc_result in H1; destruct Archi.ptr64; compute in H1; congruence. }\n subst r0.\n generalize (preg_val _ _ _ AX AG). rewrite H2. intros LD; inv LD. auto.\nQed.\n\nTheorem transf_program_correct:\n forward_simulation (Mach.semantics return_address_offset prog) (Asm.semantics tprog).\nProof.\n eapply forward_simulation_star with (measure := measure).\n apply senv_preserved; auto.\n eexact transf_initial_states.\n eexact transf_final_states.\n apply step_simulation; auto.\n apply senv_preserved; eauto.\nQed.\n\nEnd WHOLE.\n\nEnd PRESERVATION.\n", "meta": {"author": "snu-sf", "repo": "CompCertR", "sha": "f059afea5ce5cfc381ef3206df5f0a0d574694a3", "save_path": "github-repos/coq/snu-sf-CompCertR", "path": "github-repos/coq/snu-sf-CompCertR/CompCertR-f059afea5ce5cfc381ef3206df5f0a0d574694a3/x86/Asmgenproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.0640407344106306}} {"text": "\n(**************************************************************************\n* Useful General-Purpose Tactics for Coq *\n* Arthur Charguéraud *\n* Distributed under the terms of the LGPL-v3 license *\n***************************************************************************)\n\n\n(** This file contains a set of tactics that extends the set of builtin\n tactics provided with the standard distribution of Coq. It intends\n to overcome a number of limitations of the standard set of tactics,\n and thereby to help user to write shorter and more robust scripts. \n \n Hopefully, Coq tactics will be improved as time goes by, and this \n file should ultimately be useless. In the meanwhile, you will \n probably find it very useful. \n*)\n\n(** The main features offered are:\n - More convenient syntax for naming hypotheses, with tactics for\n introduction and inversion that take as input only the name of\n hypotheses of type [Prop], rather than the name of all variables. \n - Tactics providing true support for manipulating N-ary conjunctions, \n disjunctions and existentials, hidding the fact that the underlying \n implementation is based on binary predicates.\n - Convenient support for automation: tactic followed with the symbol\n \"~\" or \"*\" will call automation on the generated subgoals. \n Symbol \"~\" stands for [auto] and \"*\" for [intuition eauto].\n These bindings can be customized.\n - Forward-chaining tactics are provided to instantiate lemmas\n either with variable or hypotheses or a mix of both.\n - A more powerful implementation of [apply] is provided (it is based\n on [refine] and thus behaves better with respect to conversion).\n - An improved inversion tactic which substitutes equalities on variables\n generated by the standard inversion mecanism. Moreover, it supports\n the elimination of dependently-typed equalities (requires axiom [K],\n which is a weak form of Proof Irrelevance).\n - An improved induction tactic that saves the relevant information\n by introducing equalities before doing the induction and \n substitutes these equality in each subgoal generated by [induction].\n - Tactics for saving time when writing proofs, with tactics to\n asserts hypotheses or sub-goals, and improved tactics for\n clearing, renaming, and sorting hypotheses.\n*)\n\n(** External credits:\n - thanks to Xavier Leroy for providing with the idea of tactic [forward],\n - thanks to Georges Gonthier for the implementation trick in [applys],\n - thanks to Hugo Herbelin for useful feedback on several tactics.\n*)\n\nSet Implicit Arguments.\n\n(* ********************************************************************** *)\n(** * Additional notations for Coq *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** N-ary Existentials *)\n\n(** [exists T1 ... TN, P] is a shorthand for \n [exists T1, ..., exists TN, P]. Note that\n [Coq.Program.Syntax] already defines exists\n for arity up to 4. *)\n\nNotation \"'exists' x1 ',' P\" :=\n (exists x1, P)\n (at level 200, x1 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 ',' P\" :=\n (exists x1, exists x2, P)\n (at level 200, x1 ident, x2 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 ',' P\" :=\n (exists x1, exists x2, exists x3, P)\n (at level 200, x1 ident, x2 ident, x3 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 x6 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, exists x6, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n x6 ident,\n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 x6 x7 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, exists x6, \n exists x7, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n x6 ident, x7 ident,\n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 x6 x7 x8 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, exists x6, \n exists x7, exists x8, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n x6 ident, x7 ident, x8 ident,\n right associativity) : type_scope. \n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Partial application of equality *)\n\n(** [= x] is a unary predicate which holds of values equal to [x].\n It simply denotes the partial application of equality. *)\n\nNotation \"'=' x\" := (fun y => y = x) (at level 71).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Notation for projections *)\n\n(*\nNotation \"'proj21' P\" := (proj1 P) (at level 69, only parsing).\nNotation \"'proj22' P\" := (proj2 P) (at level 69, only parsing).\n\nNotation \"'proj31' P\" := (proj1 P) (at level 69).\nNotation \"'proj32' P\" := (proj1 (proj2 P)) (at level 69).\nNotation \"'proj33' P\" := (proj2 (proj2 P)) (at level 69).\n\nNotation \"'proj41' P\" := (proj1 P) (at level 69).\nNotation \"'proj42' P\" := (proj1 (proj2 P)) (at level 69).\nNotation \"'proj43' P\" := (proj1 (proj2 (proj2 P))) (at level 69).\nNotation \"'proj44' P\" := (proj2 (proj2 (proj2 P))) (at level 69).\n\nNotation \"'proj51' P\" := (proj1 P) (at level 69).\nNotation \"'proj52' P\" := (proj1 (proj2 P)) (at level 69).\nNotation \"'proj53' P\" := (proj1 (proj2 (proj2 P))) (at level 69).\nNotation \"'proj54' P\" := (proj1 (proj2 (proj2 (proj2 P)))) (at level 69).\nNotation \"'proj55' P\" := (proj2 (proj2 (proj2 (proj2 P)))) (at level 69).\n*)\n\n\n(* ********************************************************************** *)\n(** * Tools for programming with Ltac *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Programming tactics *)\n\n(** [ltac_no_arg] is a constant that can be used to simulate \n optional arguments in tactic definitions. \n Use [mytactic ltac_no_arg] on the tactic invokation,\n and use [match arg with ltac_no_arg => ..] or\n [match type of arg with ltac_No_arg => ..] to\n test whether an argument was provided. *)\n\nInductive ltac_No_arg : Set := \n | ltac_no_arg : ltac_No_arg.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Returning values *)\n\n(** Ltac tactics are not allowed to both perform side-effect on the goal\n and return a value in the same time. To work around this limitation,\n we can use either the current goal or the proof context as a stack \n to place return values. To avoid interferences, we box the return\n values.\n\n When the goal is used as stack, we use [ltac_tag_result] to box values.\n When the context is used, we use the type [Carrier] to box values. *) \n\nDefinition ltac_tag_result (A:Type) (x:A) := x.\n\n(** [build_result E] changes the goal from [G] to \n [ltac_tag_result T -> G] where [T] is the type of [E]. *)\n\nLtac build_result t :=\n match type of t with ?T =>\n let H := fresh \"TEMP\" in\n assert (H : ltac_tag_result T); \n [ unfold ltac_tag_result; exact t | generalize H; clear H ]\n end.\n\n(** [if_is_result] is the identity on a goal of the form [ltac_tag_result T -> G] \n and fails otherwise. *)\n\nLtac if_is_result :=\n match goal with |- ltac_tag_result _ -> _ => idtac end.\n\n(** [name_result H] expects a of the form [ltac_tag_result T -> G] \n and changes the goal to [G] by introducing an hypothesis [H:T]. *)\n\nTactic Notation \"name_result\" simple_intropattern(H) :=\n match goal with |- ltac_tag_result _ -> _ =>\n unfold ltac_tag_result at 1; \n first [ intros H\n | let H' := fresh \"NameAlreadyUsed\" in intros H'] end.\n\n(** With the type [Carrier], we implement the three following tactics:\n - [_put x] is used to return a value (leaving it on the stack)\n - [_get] is used to obtain the last returned value \n - [_rem] is used to remove the last returned value from the \n context. \n The typicall usage is: [mytactic args; let result := _get in _rem; ...].\n *)\n\nInductive Carrier : forall A, A -> Type :=\n | carrier : forall A x, @Carrier A x.\n\n(** [_put x] adds on hypothesis of type [Carrier x].\n [_put2 x y] and [_put3 x y z] can be used for functions\n that return pairs or triples of values. *)\n\nLtac _put x :=\n generalize (carrier x); intro.\nLtac _put2 x y :=\n _put y; _put x.\nLtac _put3 x y z :=\n _put z; _put y; _put x.\n\n(** [_get] returns the value [x] contained in the last hypothesis of \n type [Carrier x] available in the context. If fails if there\n is no such hypothesis. *)\n\nLtac _get :=\n match goal with H: Carrier ?t |- _ => t end.\n\n(** [_rem] clears the last hypothesis of type [Carrier _]. \n If fails if there is no such hypothesis. *)\n\nLtac _rem :=\n match goal with H: Carrier ?t |- _ => clear H end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** List of arguments for tactics *)\n\nRequire Import Coq.Lists.List.\n\n(** [ltac_wild] is a constant that can be used to simulate \n wildcard arguments in tactic definitions. Notation is [__]. *)\n\nInductive ltac_Wild : Set := \n | ltac_wild : ltac_Wild.\n\n(*\nNotation \"'__'\" := ltac_wild : ltac_scope.\n*)\n(** [ltac_wilds] is another constant that can be used to simulate \n a sequence of [N] wildcards, with [N] chosen appropriately \n depending on the context. Notation is [___]. *)\n\nInductive ltac_Wilds : Set := \n | ltac_wilds : ltac_Wilds.\n\n(*\nNotation \"'___'\" := ltac_wilds : ltac_scope.\n*)\n\n(** [Boxer] is a datatype such that the type [list Boxer] can be used \n1 to manipulate list of values in ltac. *)\n\nInductive Boxer : Type :=\n | boxer : forall (A:Type), A -> Boxer.\n\nNotation \"'>>>'\" :=\n (@nil Boxer)\n (at level 0)\n : ltac_scope.\nNotation \"'>>>' v1\" :=\n ((boxer v1)::nil)\n (at level 0, v1 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2\" :=\n ((boxer v1)::(boxer v2)::nil)\n (at level 0, v1 at level 0, v2 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4 v5\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::(boxer v5)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0, v5 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4 v5 v6\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::(boxer v5)\n ::(boxer v6)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0, v5 at level 0, v6 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4 v5 v6 v7\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::(boxer v5)\n ::(boxer v6)::(boxer v7)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0, v5 at level 0, v6 at level 0, v7 at level 0)\n : ltac_scope.\n\nOpen Scope ltac_scope.\n\n(** [ltac_inst] is a datatype that describes the four instantiation\n modes that can be used in tactics [specializes], [lets],\n [applys] and [forwards]. \n - [Args]: all arguments are to be provided,\n - [Hyps]: only hypotheses are to be provided\n (hypotheses = arguments not used dependently)\n - [Vars]: only variables are to be provided\n (variables = arguments used dependently)\n - [Hnts]: the arguments provided are used as hints and are\n affected to the first argument of matching type.\n *)\n\nInductive ltac_inst : Set :=\n | Args : ltac_inst\n | Hyps : ltac_inst\n | Vars : ltac_inst\n | Hnts : ltac_inst.\n\n(** [ltac_args] inputs a term [E] and returns a term of type \"list boxer\":\n - if [E] is already of type \"list Boxer\" that starts with the\n value of an instantiation mode, it returns [E],\n - otherwise if [E] is already of type \"list Boxer\", it returns\n [(boxer Hnts)::E], in other words, mode [Hnts] is the default,\n - otherwise, it returns the list containing \n [(boxer Hnts)::(boxer E)::nil], describing the fact that there\n is only one argument provided, in the mode [Hnts]. *)\n\nLtac ltac_args E := \n match type of E with \n | List.list Boxer => \n match E with\n | (@boxer ltac_inst _)::_ => constr:(E)\n | _ => constr:((boxer Hnts)::E)\n end\n | _ => constr:((boxer Hnts)::(boxer E)::nil)\n end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Numbers as arguments *)\n\n(** When tactic takes a natural number as argument, it may be\n parsed as a relative number. In order for tactics to convert\n their arguments into natural numbers, we provide a conversion\n tactic that behaves appropriately when the module LibInt is\n loaded. *)\n \nLtac nat_from_number N := constr:(N).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Testing tactics *)\n\n(** [show tac] executes a tactic [tac] that produces a result (not \n performing any side-effect on the goal) and then display its result. *)\n\nTactic Notation \"show\" tactic(tac) :=\n let R := tac in pose R.\n\n(** [dup N] produces [N] copies of the current goal. It is useful\n for building examples on which to illustrate behaviour of tactics.\n [dup] is short for [dup 2]. *)\n\nLemma dup_lemma : forall P, P -> P -> P.\nProof. auto. Qed.\n\nLtac dup_tactic N :=\n match nat_from_number N with\n | 0 => idtac\n | S 0 => idtac\n | S ?N' => apply dup_lemma; [ | dup_tactic N' ]\n end.\n\nTactic Notation \"dup\" constr(N) := \n dup_tactic N.\nTactic Notation \"dup\" := \n dup 2.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Deconstructing terms *)\n\n(** [get_head E] is a tactic that returns the head constant of the \n term [E], ie, when applied to a term of the form [P x1 ... xN] \n it returns [P]. If [E] is not an application, it returns [E]. *)\n\nLtac get_head E :=\n match E with\n | ?P _ _ _ _ _ _ _ _ _ => constr:(P)\n | ?P _ _ _ _ _ _ _ _ => constr:(P) \n | ?P _ _ _ _ _ _ _ => constr:(P)\n | ?P _ _ _ _ _ _ => constr:(P)\n | ?P _ _ _ _ _ => constr:(P) \n | ?P _ _ _ _ => constr:(P) \n | ?P _ _ _ => constr:(P) \n | ?P _ _ => constr:(P) \n | ?P _ => constr:(P)\n | ?P => constr:(P)\n end.\n\n(* [is_metavar E] returns whether E is a meta-variable.\n However, its implementation is approximative, since it\n returns [true] also for constants (i.e. not-applicative terms). *)\n\nLtac is_metavar E :=\n match E with\n | ?P _ _ _ _ _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ _ _ _ _ => constr:(false) \n | ?P _ _ _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ => constr:(false)\n | ?P _ _ _ => constr:(false)\n | ?P _ _ => constr:(false)\n | ?P _ => constr:(false)\n | ?P => constr:(true)\n end.\n\n\n(* ********************************************************************** *)\n(** * Backward and forward chaining *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Adding assumptions *)\n\n(** [lets H: E] adds an hypothesis [H : T] to the context, where [T] is \n the type of term [E]. If [H] is an introduction pattern, it will\n destruct [H] according to the pattern. *)\n\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E) :=\n generalize E; intros I.\n\n(** [lets H1 .. HN : E] is the same as \n [lets \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]:E], and thus equivalent to\n [destruct E as \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]]. *)\n\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(E) :=\n lets [I1 I2]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(E) :=\n lets [I1 [I2 I3]]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(E) :=\n lets [I1 [I2 [I3 I4]]]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(E) :=\n lets [I1 [I2 [I3 [I4 I5]]]]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(E) :=\n lets [I1 [I2 [I3 [I4 [I5 I6]]]]]: E.\n\n(** [lets_simpl H: E] is the same as [lets H: E] excepts that it\n calls [simpl] on the hypothesis H. *)\n\nTactic Notation \"lets_simpl\" ident(H) \":\" constr(E) :=\n lets H: E; simpl in H.\n\n(** [lets_hnf H: E] is the same as [lets H: E] excepts that it\n calls [hnf] to set the definition in head normal form. *)\n\nTactic Notation \"lets_hnf\" ident(H) \":\" constr(E) :=\n lets H: E; hnf in H.\n\n(** [lets: E] is equivalent to [lets H: E], only the name [H] is\n automatically chosen by Coq. It is useful to type-check a\n term (like the top-level command [Check]), but also to add\n facts that are going to be used by automation. \n Syntax [lets: E1 .. EN] is short for [lets: E1; ..; lets: EN]. *)\n\nTactic Notation \"lets\" \":\" constr(E1) :=\n generalize E1; intro.\nTactic Notation \"lets\" \":\" constr(E1) constr(E2) :=\n lets: E1; lets: E2.\nTactic Notation \"lets\" \":\" constr(E1) constr(E2) constr(E3) :=\n lets: E1; lets: E2; lets: E3.\n\n(** [lets_simpl: E] is the same as [lets_simpl H: E] with \n the name [H] being choosed automatically. *)\n\nTactic Notation \"lets_simpl\" \":\" constr(T) :=\n let H := fresh in lets_simpl H: T.\n\n(** [lets_hnf: E] is the same as [lets_hnf H: E] with \n the name [H] being choosed automatically. *)\n\nTactic Notation \"lets_hnf\" \":\" constr(T) :=\n let H := fresh in lets_hnf H: T.\n\n(** [put X: E] is a synonymous for [pose (X := E)].\n Other syntaxes are [put: E]. *)\n\nTactic Notation \"put\" ident(X) \":\" constr(E) :=\n pose (X := E).\nTactic Notation \"put\" \":\" constr(E) :=\n let X := fresh \"X\" in pose (X := E).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Application *)\n\n(** [applys] is a tactic similar to [eapply] except that it is\n based on the [refine] tactics, and thus is strictly more \n powerful (at least in theory :). In short, it is able to perform\n on-the-fly conversions when required for arguments to match,\n and it is able to instantiate existentials when required. *)\n\nTactic Notation \"applys\" constr(t) :=\n first \n [ refine (@t)\n | refine (@t _) \n | refine (@t _ _) \n | refine (@t _ _ _)\n | refine (@t _ _ _ _)\n | refine (@t _ _ _ _ _)\n | refine (@t _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _ _ _ _)\n ].\n\n(** The tactics [applys_N T], where [N] is a natural number,\n provides a more efficient way of using [applys T]. It avoids\n trying out all possible arities, by specifying explicitely\n the arity of function [T]. This version is to be preferred\n for programming intensively-used tactics. *)\n\nTactic Notation \"applys_0\" constr(t) :=\n refine (@t).\nTactic Notation \"applys_1\" constr(t) :=\n refine (@t _).\nTactic Notation \"applys_2\" constr(t) :=\n refine (@t _ _).\nTactic Notation \"applys_3\" constr(t) :=\n refine (@t _ _ _).\nTactic Notation \"applys_4\" constr(t) :=\n refine (@t _ _ _ _).\nTactic Notation \"applys_5\" constr(t) :=\n refine (@t _ _ _ _ _).\nTactic Notation \"applys_6\" constr(t) :=\n refine (@t _ _ _ _ _ _).\nTactic Notation \"applys_7\" constr(t) :=\n refine (@t _ _ _ _ _ _ _).\nTactic Notation \"applys_8\" constr(t) :=\n refine (@t _ _ _ _ _ _ _ _).\nTactic Notation \"applys_9\" constr(t) :=\n refine (@t _ _ _ _ _ _ _ _ _).\nTactic Notation \"applys_10\" constr(t) :=\n refine (@t _ _ _ _ _ _ _ _ _ _).\n\n(** [applys_to H E] transform the type of hypothesis [H] by \n replacing it by the result of the application of the term \n [E] to [H]. Intuitively, it is equivalent to [lets H: (E H)]. *)\n\nTactic Notation \"applys_to\" hyp(H) constr(E) :=\n let H' := fresh in rename H into H';\n (first [ lets H: (E H') \n | lets H: (E _ H') \n | lets H: (E _ _ H') \n | lets H: (E _ _ _ H') \n | lets H: (E _ _ _ _ H') \n | lets H: (E _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ _ _ _ H') ]\n ); clear H'.\n\n(** [applys_in H E] transform the hypothesis [H] by replacing it\n by the result of the application of [H] to the term [E]\n Intuitively, it is equivalent to [lets H: (H E)]. \n DEPRECATED: use [specializes H E] instead. *)\n\nTactic Notation \"applys_in\" hyp(H) constr(E) :=\n let H' := fresh in rename H into H';\n (first [ lets H: (H' E) \n | lets H: (H' _ E) \n | lets H: (H' _ _ E) \n | lets H: (H' _ _ _ E) \n | lets H: (H' _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ _ _ _ E) ]\n ); clear H'.\n\n(** [applys_clear E] performs [applys E] and then calls [clear] on\n the head term of [E]. It fails if this head term is not an hypothesis\n or if it used dependently. *)\n\nTactic Notation \"applys_clear\" constr(E) :=\n applys E; let H := get_head E in clear E.\nTactic Notation \"apply_clear\" constr(E) :=\n applys_clear E.\n\n(** [constructors] calls [constructor] or [econstructor]. *)\n(* TODO: is [econstructor] stricly more powerful than\n [constructor]? *)\n\nTactic Notation \"constructors\" :=\n first [ constructor | econstructor ].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Assertions *)\n\n(** [false_goal] replaces any goal by the goal [False]. \n Contrary to the tactic [false] (below), it does not try to do\n anything else *)\n\nTactic Notation \"false_goal\" :=\n elimtype False.\n (* alternative implementation:\n assert False; [ | contradiction ]. *)\n\n(** [false] replaces any goal by the goal [False].\n Furthermore, it discharges the obligation if the context contains \n [False] or an hypothesis of the form [C x1 .. xN = D y1 .. yM]. *)\n\nTactic Notation \"false\" :=\n false_goal; try assumption; try discriminate.\n\n(** [tryfalse] tries to solve a goal by contradiction, and leaves\n the goal unchanged if it cannot solve it.\n It is equivalent to [try solve \\[ false \\]]. *)\n\nTactic Notation \"tryfalse\" :=\n try solve [ false ].\n\n(** [tryfalse by tac /] is that same as [tryfalse] except that\n it tries to solve the goal using tactic [tac] if [assumption]\n and [discriminate] do not apply.\n It is equivalent to [try solve \\[ false; tac \\]]. *)\n\nTactic Notation \"tryfalse\" \"by\" tactic(tac) \"/\" :=\n try solve [ false; tac ].\n\n(** [false T] is equivalent to [false; apply T]. It also \n solves the goal if [T] has type [C x1 .. xN = D y1 .. yM]. *)\n\nTactic Notation \"false\" constr(T) \"by\" tactic(tac) \"/\" :=\n false_goal; first \n [ first [ apply T | eapply T | applys T]; tac\n | let H := fresh in lets H: T; discriminate H ].\n\nTactic Notation \"false\" constr(T) :=\n false T by idtac/.\n\n(** [false_inv] proves any goal provided there is an\n hypothesis [H] in the context that can be proved absurd\n by calling [inversion H]. *)\nLtac false_inv_tactic :=\n match goal with H:_ |- _ =>\n solve [ inversion H\n | clear H; false_inv_tactic\n | fail 2 ] end.\n\nTactic Notation \"false_inv\" :=\n false_inv_tactic.\n\n(** [tryfalse_inv] tries to prove the goal using\n [false] or [false_inv], and leaves the goal\n unchanged if it does not succeed. *)\n\nTactic Notation \"tryfalse_inv\" :=\n try solve [ false | false_inv ].\n\n(** [asserts H: T] is another syntax for [assert (H : T)], which\n also works with introduction patterns. For instance, we can write:\n [asserts \\[x P\\] (exists n, n = 3)], or \n [asserts \\[H|H\\] (n = 0 \\/ n = 1). *)\n\nTactic Notation \"asserts\" simple_intropattern(I) \":\" constr(T) :=\n let H := fresh in assert (H : T); \n [ | generalize H; clear H; intros I ].\n\n(** [asserts H1 .. HN: T] is the same as \n [asserts \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]: T]. *)\n\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(T) :=\n asserts [I1 I2]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(T) :=\n asserts [I1 [I2 I3]]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(T) :=\n asserts [I1 [I2 [I3 I4]]]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(T) :=\n asserts [I1 [I2 [I3 [I4 I5]]]]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(T) :=\n asserts [I1 [I2 [I3 [I4 [I5 I6]]]]]: T.\n\n(** [asserts: T as H] is another syntax for [asserts H: T] *)\n\nTactic Notation \"asserts\" \":\" constr(T) \"as\" simple_intropattern(I) :=\n asserts I : T.\n\n(** [asserts: T] is [asserts H: T] with [H] being chosen automatically. *)\n\nTactic Notation \"asserts\" \":\" constr(T) :=\n let H := fresh in asserts H : T.\n\n(** [cuts H: T] is the same as [asserts H: T] except that the two subgoals\n generated are swapped: the subgoal [T] comes second. Note that contrary\n to [cut], it introduces the hypothesis. *)\n\nTactic Notation \"cuts\" simple_intropattern(I) \":\" constr(T) :=\n cut (T); [ intros I | idtac ].\n\n(** [cuts: T] is [cuts H: T] with [H] being chosen automatically. *)\n\nTactic Notation \"cuts\" \":\" constr(T) :=\n let H := fresh in cuts H: T.\n\n(** [cuts H1 .. HN: T] is the same as \n [cuts \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]: T]. *)\n\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(T) :=\n cuts [I1 I2]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(T) :=\n cuts [I1 [I2 I3]]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(T) :=\n cuts [I1 [I2 [I3 I4]]]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(T) :=\n cuts [I1 [I2 [I3 [I4 I5]]]]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(T) :=\n cuts [I1 [I2 [I3 [I4 [I5 I6]]]]]: T.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Instantiation and forward-chaining *)\n\n(** The instantiation tactics are used to instantiate a lemma [E]\n (whose type is a product) on some arguments. The type of [E] is\n made of implications and universal quantifications, e.g.\n [forall x, P x -> forall y z, Q x y z -> R z].\n \n The first possibility is to provide arguments in order: first [x],\n then a proof of [P x], then [y] etc... In this mode, called \"Args\",\n all the arguments are to be provided. If a wildcard is provided\n (written [__]), then an existential variable will be introduced in\n place of the argument.\n\n It often saves a lot of time to give only the dependent variables,\n (here [x], [y] and [z]), and have the hypotheses generated as \n subgoals. In this \"Vars\" mode, only variables are to be provided. \n For instance, lemma [E] applied to [3] and [4] is a term\n of type [forall z, Q 3 4 z -> R z], and [P 3] is a new subgoal.\n It is possible to use wildcards to introduce existential variables.\n\n However, there are situations where some of the hypotheses already\n exists, and it saves time to instantiate the lemma [E] using the \n hypotheses. For instance, suppose [F] is a term of type [P 2]. \n Then the application of [E] to [F] in this \"Hyps\" mode is a term of type\n [forall y z, Q 2 y z -> R z]. Each wildcard use\n will generate an assertion instead, for instance if [G] has type\n [Q 2 3 4], then the application of [E] to a wildcard and to [G] \n in mode-h is a term of type [R 4], and [P 2] is a new subgoal.\n\n It is very convenient to give some arguments the lemma should be\n instantiated on, and let the tactic find out automatically where\n underscores should be insterted. The technique is simple: try to\n place an argument, and if it does not work insert an underscore.\n In this \"Hints\" mode ([Hnts] for short), underscore [__] would be useless,\n since they can be omitted. So, we interpret underscore as follows:\n an underscore means that we want to skip the argument that has the\n same type as the next real argument provided (real means not an\n underscore). If there is no real argument after underscore, then the\n the underscore is used for the first possible argument.\n\n There are four modes of instantiation:\n - \"Args\": give all arguments,\n - \"Vars\": give only variables,\n - \"Hyps\": give only hypotheses,\n - \"Hnts\": give some arguments.\n \n The general syntax is [tactic (>>>Mode E1 .. EN)] where [tactic] is\n the name of the tactic (possibly with some arguments) and [Mode]\n is the name of the mode, and [Ei] are the arguments.\n If [Mode] is omitted, [Hnts] will be inserted.\n If [>>>Mode] is omitted, [>>>Hnts] will be inserted.\n Moreover, some tactics accept the syntax [tactic E1 .. EN]\n as short for [tactic (>>>Hnts E1 .. EN)].\n\n Finally, if the argument [EN] given is a triple-underscore [___],\n then it is equivalent to providing a list of wildcards, with\n the appropriate number of wildcards. This means that all\n the remaining arguments of the lemma will be instantiated.\n\n*)\n\n(* Underlying implementation *)\n\n(* -- to be used once v8.1pl4 is no longer supported\nLtac app_darg t A v cont :=\n let x := fresh \"TEMP\" in\n evar (x:A); \n instantiate (1:=v) in (Value of x);\n let t' := constr:(t x) in\n let t'' := (eval unfold x in t') in\n subst x; cont t''.\n*)\n\nLtac app_arg t P v cont :=\n let H := fresh \"TEMP\" in\n assert (H : P); [ apply v | cont(t H); try clear H ].\n\nLtac app_assert t P cont :=\n let H := fresh \"TEMP\" in\n assert (H : P); [ | cont(t H); clear H ].\n\nLtac app_evar t A cont :=\n let x := fresh \"TEMP\" in\n evar (x:A); \n let t' := constr:(t x) in\n let t'' := (eval unfold x in t') in\n subst x; cont t''.\n\nLtac build_app_alls t final :=\n let rec go t :=\n match type of t with \n | ?P -> ?Q => app_assert t P go\n | forall _:?A, _ => app_evar t A go\n | _ => final t\n end in \n go t.\n\nLtac build_app_args t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' => \n let cont t' := go t' vs' in\n match v with\n | ltac_wild => \n match type of t with \n | ?P -> ?Q => first [ app_assert t P cont | fail 3 ]\n | forall _:?A, _ => first [ app_evar t A cont | fail 3 ] \n end\n | _ => \n match type of t with \n | ?P -> ?Q => first [ app_arg t P v cont | fail 3 ]\n | forall _:?A, _ => first [ cont (t v) | fail 3 ]\n (*todo: v8.2, use: app_darg t A v cont *)\n end\n end\n end in\n go t vs.\n\nLtac build_app_vars t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' =>\n match type of t with\n | ?P -> ?Q => \n let cont t' := go t' vs in\n first [ app_assert t P cont | fail 3 ]\n | forall _:?A, _ => \n let cont t' := go t' vs' in\n match v with\n | ltac_wild => first [ app_evar t A cont | fail 3 ]\n | _ => first [ cont(t v) | fail 3 ]\n end\n end\n end in\n go t vs.\n\nLtac build_app_hyps t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' =>\n match type of t with\n | ?P -> ?Q => \n let cont t' := go t' vs' in\n match v with\n | ltac_wild => first [ app_assert t P cont | fail 3 ]\n | _ => first [ app_arg t P v cont | fail 3 ]\n (* if mismatch is authorized\n first [ app_arg t P v cont\n | let cont' t' := go t' vs in\n app_assert t P cont' ] *) \n end \n | forall _:?A, _ => \n let cont t' := go t' vs in\n first [ app_evar t A cont | fail 3 ]\n end\n end in\n go t vs.\n\nLtac boxerlist_next_type vs :=\n match vs with\n | nil => constr:(ltac_wild)\n | (boxer ltac_wild)::?vs' => boxerlist_next_type vs'\n | (boxer ltac_wilds)::_ => constr:(ltac_wild)\n | (@boxer ?T _)::_ => constr:(T)\n end.\n\nLtac build_app_hnts t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' => \n let cont t' := go t' vs in\n let cont' t' := go t' vs' in\n match v with\n | ltac_wild => \n first [ let T := boxerlist_next_type vs' in\n match T with\n | ltac_wild =>\n match type of t with \n | ?P -> ?Q => first [ app_assert t P cont' | fail 3 ]\n | forall _:?A, _ => first [ app_evar t A cont' | fail 3 ] \n end \n | _ =>\n match type of t with (* should test T for unifiability *)\n | T -> ?Q => first [ app_assert t T cont' | fail 3 ]\n | forall _:T, _ => first [ app_evar t T cont' | fail 3 ] \n | ?P -> ?Q => first [ app_assert t P cont | fail 3 ]\n | forall _:?A, _ => first [ app_evar t A cont | fail 3 ] \n end \n end\n | fail 2 ]\n | _ => \n match type of t with \n | ?P -> ?Q => first [ app_arg t P v cont'\n | app_assert t P cont\n | fail 3 ]\n | forall _:?A, _ => first [ cont' (t v) \n | app_evar t A cont\n | fail 3 ]\n end\n end\n end in\n go t vs.\n\n\nLtac build_app Ei final := \n let args := ltac_args Ei in \n first [ \n match args with (boxer ?mode)::(boxer ?t)::?vs => \n match mode with\n | Hnts => build_app_hnts t vs final\n | Args => build_app_args t vs final \n | Vars => build_app_vars t vs final\n | Hyps => build_app_hyps t vs final\n end end\n | fail 1 \"Instantiation fails for:\" args].\n\n\n(** [lets H: (>>> Mode E0 E1 .. EN)] will instantiate lemma [E0]\n on the arguments [Ei] (which may be wildcards [__]),\n and name [H] the resulting term. [H] may be an introduction\n pattern, or a sequence of introduction patterns [I1 I2 IN],\n or empty. \n Syntax [lets H: E0 E1 .. EN] is available for mode Hnts.\n The keyword \"ok\" may be replaced with \"of_vars\" or \"of_hyps\" \n for providing only variables or only hypotheses. If the last\n argument [EN] is [___] (triple-underscore), then all\n arguments of [H] will be instantiated. *)\n\nLtac lets_build I Ei :=\n build_app Ei ltac:(fun R => lets I: R).\n\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E) :=\n lets_build I E.\nTactic Notation \"lets\" \":\" constr(E) :=\n let H := fresh in lets H: E.\n\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n \":\" constr(E) :=\n lets [I1 I2]: E.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) \":\" constr(E) :=\n lets [I1 [I2 I3]]: E.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) \":\" constr(E) :=\n lets [I1 [I2 [I3 I4]]]: E.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5) \n \":\" constr(E) :=\n lets [I1 [I2 [I3 [I4 I5]]]]: E.\n \nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) :=\n lets I: (>>> E0 A1).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) :=\n lets I: (>>> E0 A1 A2).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) :=\n lets I: (>>> E0 A1 A2 A3).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) :=\n lets I: (>>> E0 A1 A2 A3 A4).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n lets I: (>>> E0 A1 A2 A3 A4 A5).\n\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) :=\n lets [I1 I2]: E0 A1.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) :=\n lets [I1 I2]: E0 A1 A2.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) :=\n lets [I1 I2]: E0 A1 A2 A3.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) :=\n lets [I1 I2]: E0 A1 A2 A3 A4.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n lets [I1 I2]: E0 A1 A2 A3 A4 A5.\n\n\n(** [forwards H: (>>> Mode E0 E1 .. EN)] is short for \n [forwards H: (>>> Mode E0 E1 .. EN ___)]. \n The arguments [Ei] can be wildcards [__] (except [E0]).\n [H] may be an introduction pattern, or a sequence of\n introduction pattern, or empty. \n Syntax [forwards H: E0 E1 .. EN] is available for mode Hnts. *)\n\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E) :=\n let E' := ltac_args E in\n let E'' := (eval simpl in (E' ++ ((boxer ltac_wilds)::nil))) in\n lets I: E''.\n\nTactic Notation \"forwards\" \":\" constr(E) := \n let H := fresh in forwards H: E.\n\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n \":\" constr(E) :=\n forwards [I1 I2]: E.\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) \":\" constr(E) :=\n forwards [I1 [I2 I3]]: E.\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) \":\" constr(E) :=\n forwards [I1 [I2 [I3 I4]]]: E.\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5) \n \":\" constr(E) :=\n forwards [I1 [I2 [I3 [I4 I5]]]]: E.\n\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) :=\n forwards I: (>>> E0 A1).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) :=\n forwards I: (>>> E0 A1 A2).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) :=\n forwards I: (>>> E0 A1 A2 A3).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) :=\n forwards I: (>>> E0 A1 A2 A3 A4).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n forwards I: (>>> E0 A1 A2 A3 A4 A5).\n\n\n(** [applys (>>> Mode E0 E1 .. EN)] instantiates lemma [E0]\n on the arguments [Ei] (which may be wildcards [__]),\n and apply the resulting term to the current goal,\n using the tactic [applys] defined earlier on.\n [applys E0 E1 E2 .. EN] is short \n for [applys (>>>Hnts E0 E1 E2 .. EN)]. *)\n\nLtac applys_build Ei :=\n build_app Ei ltac:(fun R =>\n first [ apply R | eapply R | applys R ]).\n\nTactic Notation \"applys\" constr(E0) :=\n match type of E0 with\n | list Boxer => applys_build E0 \n | _ => applys E0\n end.\nTactic Notation \"applys\" constr(E0) constr(A1) :=\n applys (>>> E0 A1).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) :=\n applys (>>> E0 A1 A2).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) constr(A3) :=\n applys (>>> E0 A1 A2 A3).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) constr(A3) constr(A4) :=\n applys (>>> E0 A1 A2 A3 A4).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n applys (>>> E0 A1 A2 A3 A4 A5).\n\n(** [specializes H (>>>Mode E1 E2 .. EN)] will instantiate hypothesis [H]\n on the arguments [Ei] (which may be wildcards [__]).\n The keyword \"ok\" may be replaced with \"of_vars\" or \"of_hyps\" \n for providing only variables or only hypotheses. If the last\n argument [EN] is [___] (triple-underscore), then all\n arguments of [H] will be instantiated. *)\n\nLtac specializes_build H Ei :=\n let H' := fresh \"TEMP\" in rename H into H';\n let Ei' := ltac_args Ei in\n match Ei' with (boxer ?mode)::?vs => \n let Ei'' := constr:((boxer mode)::(boxer H')::vs) in\n build_app Ei'' ltac:(fun R => lets H: R);\n clear H'\n end.\n \nTactic Notation \"specializes\" hyp(H) constr(A) :=\n specializes_build H A.\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) :=\n specializes H (>>> A1 A2).\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) constr(A3) :=\n specializes H (>>> A1 A2 A3).\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) constr(A3) constr(A4) :=\n specializes H (>>> A1 A2 A3 A4).\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n specializes H (>>> A1 A2 A3 A4 A5).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Experimental tactics for application *)\n\n(** [fapply] is a version of [apply] based on [forwards]. *)\n\nTactic Notation \"fapply\" constr(E) := \n let H := fresh in forwards H: E; \n first [ apply H | eapply H | hnf; apply H \n | hnf; eapply H | applys H ].\n\n(** [sapply] stands for \"super apply\". It tries\n [apply], [eapply], [applys] and [fapply],\n plus [hnf;apply] and [hnf;eapply]. *)\n\nTactic Notation \"sapply\" constr(H) :=\n first [ apply H | eapply H | applys H \n | hnf; apply H | hnf; eapply H | hnf; applys H\n | fapply H ].\n\n\n(* ********************************************************************** *)\n(** * Introduction and generalization *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Introduction *)\n\nDefinition ltac_tag_subst (A:Type) (x:A) := x.\n\n(** [introv] iterates [intro] on all universally-quantified \"variables\"\n at the head of the goal. More precisely, it introduces only the \n dependently-used variables. For example, [introv] applied\n to the goal [forall x y, P x -> Q] introduces [x] and [y] but not\n the hypothesis [P x]. If the goal is a definition, then it will\n unfold this definition. \n \n [introv H1 .. HN] calls [introv] then introduces an hypothesis as [H1],\n then call [introv] again and introduces an hypothesis as [H2], \n and so on.\n It provides a convenient way of introducing all the arguments of a\n theorem and name only the non-dependent hypotheses. *)\n \nLtac introv_rec :=\n match goal with\n | |- (ltac_tag_subst (?x = ?y) -> ?Q) =>\n let H := fresh \"Aux\" in \n intro H; unfold ltac_tag_subst in H;\n try subst x; introv_rec\n | |- ?P -> ?Q => idtac\n | |- forall _, _ => intro; introv_rec\n | |- _ => idtac\n end.\n\nLtac introv_to :=\n match goal with\n | |- (ltac_tag_subst (?x = ?y) -> ?Q) =>\n let H := fresh \"Aux\" in \n intro H; unfold ltac_tag_subst in H;\n try subst x; introv_to\n | |- ?P -> ?Q => idtac\n | |- forall _, _ => intro; introv_to\n | |- ?G => let P := get_head G in progress (unfold P); introv_to\n end.\n\nLtac introv_base :=\n match goal with\n | |- forall _, _ => introv_rec\n | |- ?G => let P := get_head G in unfold P; introv_rec\n end.\n\nTactic Notation \"introv\" :=\n introv_base.\nTactic Notation \"introv\" simple_intropattern(I) :=\n introv_to; intros I.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) :=\n introv_to; intros I1; introv_to; intros I2.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) :=\n introv; intros I1; introv; intros I2; introv; intros I3.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) :=\n introv; intros I1; introv; intros I2; introv; intros I3;\n introv; intros I4.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5) :=\n introv; intros I1; introv; intros I2; introv; intros I3;\n introv; intros I4; introv; intros I5.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) :=\n introv; intros I1; introv; intros I2; introv; intros I3;\n introv; intros I4; introv; intros I5; introv; intros I6.\n\n(** [intros_all] repeats [intro] as long as possible. Contrary to [intros],\n it unfolds any definition on the way. Remark that it also unfolds the\n definition of negation, so applying [introz] to a goal of the form\n [forall x, P x -> ~Q] will introduce [x] and [P x] and [Q], and will\n leave [False] in the goal. *)\n\nTactic Notation \"intros_all\" :=\n repeat intro.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Generalization *)\n\n(** [gen X1 .. XN] is a shorthand for calling [generalize dependent] \n successively on variables [XN]...[X1]. Note that the variables\n are generalized in reverse order, following the convention of\n the [generalize] tactic: it means that [X1] will be the first\n quantified variable in the resulting goal. *) \n\nTactic Notation \"gen\" ident(X1) :=\n generalize dependent X1.\nTactic Notation \"gen\" ident(X1) ident(X2) :=\n gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) :=\n gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) :=\n gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) :=\n gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) \n ident(X6) :=\n gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) \n ident(X6) ident(X7) :=\n gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) \n ident(X6) ident(X7) ident(X8) :=\n gen X8; gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\n\n(** [generalizes X] is a shorthand for calling [generalize X; clear X]. \n It is weaker than tactic [gen X] since it does not support\n dependencies. It is mainly intended for writing tactics. *) \n \nTactic Notation \"generalizes\" hyp(X) :=\n generalize X; clear X.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Naming *)\n\n(** [sets X: E] is the same as [set (X := E) in *], that is,\n it replaces all occurences of [E] by a fresh meta-variable [X]\n whose definition is [E]. *)\n\nTactic Notation \"sets\" ident(X) \":\" constr(E) :=\n set (X := E) in *.\n\n(** [def_to_eq E X H] applies when [X := E] is a local \n definition. It adds an assumption [H: X = E] \n and then clears the definition of [X].\n [def_to_eq_sym] is similar except that it generates\n the equality [H: E = X]. *)\n\nLtac def_to_eq X HX E :=\n assert (HX : X = E) by reflexivity; clearbody X.\nLtac def_to_eq_sym X HX E :=\n assert (HX : E = X) by reflexivity; clearbody X.\n\n(** [set_eq X H: E] generates the equality [H: X = E],\n for a fresh name [X], and replaces [E] by [X] in the\n current goal. Syntaxes [set_eq X: E] and\n [set_eq: E] are also available. Similarly,\n [set_eq <- X H: E] generates the equality [H: E = X]. \n\n [sets_eq X HX: E] does the same but replaces [E] by [X]\n everywhere in the goal. [sets_eq X HX: E in H] replaces in [H].\n [set_eq X HX: E in |-] performs no substitution at all. *)\n\nTactic Notation \"set_eq\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E); def_to_eq X HX E.\nTactic Notation \"set_eq\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in set_eq X HX: E.\nTactic Notation \"set_eq\" \":\" constr(E) :=\n let X := fresh \"X\" in set_eq X: E.\n\nTactic Notation \"set_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E); def_to_eq_sym X HX E.\nTactic Notation \"set_eq\" \"<-\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in set_eq <- X HX: E.\nTactic Notation \"set_eq\" \"<-\" \":\" constr(E) :=\n let X := fresh \"X\" in set_eq <- X: E.\n\nTactic Notation \"sets_eq\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E) in *; def_to_eq X HX E.\nTactic Notation \"sets_eq\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in sets_eq X HX: E.\nTactic Notation \"sets_eq\" \":\" constr(E) :=\n let X := fresh \"X\" in sets_eq X: E.\n\nTactic Notation \"sets_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E) in *; def_to_eq_sym X HX E.\nTactic Notation \"sets_eq\" \"<-\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in sets_eq <- X HX: E.\nTactic Notation \"sets_eq\" \"<-\" \":\" constr(E) :=\n let X := fresh \"X\" in sets_eq <- X: E.\n\nTactic Notation \"set_eq\" ident(X) ident(HX) \":\" constr(E) \"in\" hyp(H) :=\n set (X := E) in H; def_to_eq X HX E.\nTactic Notation \"set_eq\" ident(X) \":\" constr(E) \"in\" hyp(H) :=\n let HX := fresh \"EQ\" X in set_eq X HX: E in H.\nTactic Notation \"set_eq\" \":\" constr(E) \"in\" hyp(H) :=\n let X := fresh \"X\" in set_eq X: E in H.\n\nTactic Notation \"set_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) \"in\" hyp(H) :=\n set (X := E) in H; def_to_eq_sym X HX E.\nTactic Notation \"set_eq\" \"<-\" ident(X) \":\" constr(E) \"in\" hyp(H) :=\n let HX := fresh \"EQ\" X in set_eq <- X HX: E in H.\nTactic Notation \"set_eq\" \"<-\" \":\" constr(E) \"in\" hyp(H) :=\n let X := fresh \"X\" in set_eq <- X: E in H.\n\nTactic Notation \"set_eq\" ident(X) ident(HX) \":\" constr(E) \"in\" \"|-\" :=\n set (X := E) in |-; def_to_eq X HX E.\nTactic Notation \"set_eq\" ident(X) \":\" constr(E) \"in\" \"|-\" :=\n let HX := fresh \"EQ\" X in set_eq X HX: E in |-.\nTactic Notation \"set_eq\" \":\" constr(E) \"in\" \"|-\" :=\n let X := fresh \"X\" in set_eq X: E in |-.\n\nTactic Notation \"set_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) \"in\" \"|-\" :=\n set (X := E) in |-; def_to_eq_sym X HX E.\nTactic Notation \"set_eq\" \"<-\" ident(X) \":\" constr(E) \"in\" \"|-\" :=\n let HX := fresh \"EQ\" X in set_eq <- X HX: E in |-.\nTactic Notation \"set_eq\" \"<-\" \":\" constr(E) \"in\" \"|-\" :=\n let X := fresh \"X\" in set_eq <- X: E in |-.\n\n\n\n(* ********************************************************************** *)\n(** * Rewriting *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Pattern *)\n\n(** [ltac_pattern E at K] is the same as [pattern E at K] except that\n [K] is a Coq natural rather than a Ltac integer. Syntax \n [ltac_pattern E as K in H] is also available. *)\n\nTactic Notation \"ltac_pattern\" constr(E) \"at\" constr(K) :=\n match K with\n | 1 => pattern E at 1\n | 2 => pattern E at 2\n | 3 => pattern E at 3\n | 4 => pattern E at 4\n | 5 => pattern E at 5\n | 6 => pattern E at 6\n | 7 => pattern E at 7\n | 8 => pattern E at 8\n end.\n\nTactic Notation \"ltac_pattern\" constr(E) \"at\" constr(K) \"in\" hyp(H) :=\n match K with\n | 1 => pattern E at 1 in H\n | 2 => pattern E at 2 in H\n | 3 => pattern E at 3 in H\n | 4 => pattern E at 4 in H\n | 5 => pattern E at 5 in H\n | 6 => pattern E at 6 in H\n | 7 => pattern E at 7 in H\n | 8 => pattern E at 8 in H\n end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Action at occurence and action not at occurence *)\n\n(** [ltac_action_at K of E do Tac] isolates the [K]-th occurence of [E] in the\n goal, setting it in the form [P E] for some named pattern [P],\n then calls tactic [Tac], and finally unfolds [P]. Syntax\n [ltac_action_at K of E in H do Tac] is also available. *)\n\nTactic Notation \"ltac_action_at\" constr(K) \"of\" constr(E) \"do\" tactic(Tac) :=\n let p := fresh in ltac_pattern E at K;\n match goal with |- ?P _ => set (p:=P) end;\n Tac; unfold p; clear p.\n\nTactic Notation \"ltac_action_at\" constr(K) \"of\" constr(E) \"in\" hyp(H) \"do\" tactic(Tac) :=\n let p := fresh in ltac_pattern E at K in H;\n match type of H with ?P _ => set (p:=P) in H end;\n Tac; unfold p in H; clear p.\n\n(** [protects E do Tac] temporarily assigns a name to the expression [E] \n so that the execution of tactic [Tac] will not modify [E]. This is\n useful for instance to restrict the action of [simpl]. *)\n\nTactic Notation \"protects\" constr(E) \"do\" tactic(T) :=\n let x := fresh in sets_eq x: E; T; subst x.\n\nTactic Notation \"protects\" constr(E) \"do\" tactic(T) \"/\" :=\n protects E do T.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Rewriting *)\n\n(** [rewrite_all E] iterates version of [rewrite E] as long as possible. \n Warning: this tactic can easily get into an infinite loop. \n Syntax for rewriting from right to left and/or into an hypothese\n is similar to the one of [rewrite]. *)\n\nTactic Notation \"rewrite_all\" constr(E) :=\n repeat rewrite E.\nTactic Notation \"rewrite_all\" \"<-\" constr(E) :=\n repeat rewrite <- E.\nTactic Notation \"rewrite_all\" constr(E) \"in\" ident(H) :=\n repeat rewrite E in H.\nTactic Notation \"rewrite_all\" \"<-\" constr(E) \"in\" ident(H) :=\n repeat rewrite <- E in H.\nTactic Notation \"rewrite_all\" constr(E) \"in\" \"*\" :=\n repeat rewrite E in *.\nTactic Notation \"rewrite_all\" \"<-\" constr(E) \"in\" \"*\" :=\n repeat rewrite <- E in *.\n\n(** [asserts_rewrite E] asserts that an equality [E] holds (generating a \n corresponding subgoal) and rewrite it straight away in the current \n goal. It avoids giving a name to the equality and later clearing it. \n Syntax for rewriting from right to left and/or into an hypothese\n is similar to the one of [rewrite]. Note: the tactic [replaces] \n plays a similar role. *)\n\nLtac asserts_rewrite_tactic E action :=\n let EQ := fresh in (assert (EQ : E);\n [ idtac | action EQ; clear EQ ]).\n\nTactic Notation \"asserts_rewrite\" constr(E) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite EQ).\nTactic Notation \"asserts_rewrite\" \"<-\" constr(E) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ).\nTactic Notation \"asserts_rewrite\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite EQ in H).\nTactic Notation \"asserts_rewrite\" \"<-\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ in H).\n\n(** [cuts_rewrite E] is the same as [asserts_rewrite E] except\n that subgoals are permuted. *)\n\nLtac cuts_rewrite_tactic E action :=\n let EQ := fresh in (cuts EQ: E; \n [ action EQ; clear EQ | idtac ]).\n\nTactic Notation \"cuts_rewrite\" constr(E) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite EQ).\nTactic Notation \"cuts_rewrite\" \"<-\" constr(E) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ).\nTactic Notation \"cuts_rewrite\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite EQ in H).\nTactic Notation \"cuts_rewrite\" \"<-\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ in H).\n\n(** [rewrite_except H EQ] rewrites equality [EQ] everywhere\n but in hypothesis [H]. *)\n\nLtac rewrite_except H EQ :=\n let K := fresh in let T := type of H in \n set (K := T) in H;\n rewrite EQ in *; unfold K in H; clear K.\n\n(** [rewrites E at K] applies when [E] is of the form [T1 = T2]\n rewrites the equality [E] at the [K]-th occurence of [T1]\n in the current goal. \n Syntaxes [rewrites <- E at K] and [rewrites E at K in H]\n are also available. *)\n\nTactic Notation \"rewrites\" constr(E) \"at\" constr(K) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T1 do (rewrite E) end.\nTactic Notation \"rewrites\" \"<-\" constr(E) \"at\" constr(K) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T2 do (rewrite <- E) end.\nTactic Notation \"rewrites\" constr(E) \"at\" constr(K) \"in\" hyp(H) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T1 in H do (rewrite E in H) end.\nTactic Notation \"rewrites\" \"<-\" constr(E) \"at\" constr(K) \"in\" hyp(H) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T2 in H do (rewrite <- E in H) end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Replace *)\n\n(** [replaces E with F] is the same as [replace E with F] except that\n the equality [E = F] is generated as first subgoal. Syntax\n [replaces E with F in H] is also available. Note that contrary to\n [replace], [replaces] does not try to solve the equality \n by [assumption]. Note: [asserts_rewrite] plays a similar role. *)\n\nTactic Notation \"replaces\" constr(E) \"with\" constr(F) :=\n let T := fresh in assert (T: E = F); [ | replace E with F; clear T ].\n\nTactic Notation \"replaces\" constr(E) \"with\" constr(F) \"in\" hyp(H) :=\n let T := fresh in assert (T: E = F); [ | replace E with F in H; clear T ].\n\n(** [replaces E at K with F] replaces the [K]-th occurence of [E]\n with [F] in the current goal. Syntax [replaces E at K with F in H]\n is also available. *)\n\nTactic Notation \"replaces\" constr(E) \"at\" constr(K) \"with\" constr(F) :=\n let T := fresh in assert (T: E = F); [ | rewrites T at K; clear T ].\n \nTactic Notation \"replaces\" constr(E) \"at\" constr(K) \"with\" constr(F) \"in\" hyp(H) :=\n let T := fresh in assert (T: E = F); [ | rewrites T at K in H; clear T ].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Renaming *)\n\n(** [renames X1 to Y1, ..., XN to YN] is a shorthand for a sequence of\n renaming operations [rename Xi into Yi]. *)\n\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) :=\n rename X1 into Y1.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) :=\n renames X1 to Y1; renames X2 to Y2.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) \",\"\n ident(X4) \"to\" ident(Y4) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3, X4 to Y4.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) \",\"\n ident(X4) \"to\" ident(Y4) \",\" ident(X5) \"to\" ident(Y5) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3, X4 to Y4, X5 to Y5.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) \",\"\n ident(X4) \"to\" ident(Y4) \",\" ident(X5) \"to\" ident(Y5) \",\"\n ident(X6) \"to\" ident(Y6) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3, X4 to Y4, X5 to Y5, X6 to Y6.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Unfolding *)\n\n(** [unfolds] unfolds the head definition in the goal, i.e. if the\n goal has form [P x1 ... xN] then it calls [unfold P].\n If the goal is not in this form, it tries and call [intros] first. *)\n\nLtac unfolds_callback E cont :=\n let go E := let P := get_head E in cont P in\n match E with\n | ?A = ?B => first [ go A | go B ]\n | ?A => go A \n end.\n\nLtac unfolds_base :=\n match goal with |- ?G => \n unfolds_callback G ltac:(fun P => unfold P) end.\n\nTactic Notation \"unfolds\" :=\n unfolds_base.\n\n(** [unfolds in H] unfolds the head definition of hypothesis [H], i.e. if \n [H] has type [P x1 ... xN] then it calls [unfold P in H]. *)\n\nLtac unfolds_in_base H :=\n match type of H with ?G => \n unfolds_callback G ltac:(fun P => unfold P in H) end.\n\nTactic Notation \"unfolds\" \"in\" hyp(H) :=\n unfolds_in_base H.\n\n(** [unfolds P1,..,PN] is a shortcut for [unfold P1,..,PN in *]. *)\n\nTactic Notation \"unfolds\" reference(F1) :=\n unfold F1 in *.\nTactic Notation \"unfolds\" reference(F1) \",\" reference(F2) :=\n unfold F1,F2 in *.\nTactic Notation \"unfolds\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) :=\n unfold F1,F2,F3 in *.\nTactic Notation \"unfolds\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) \",\" reference(F4) :=\n unfold F1,F2,F3,F4 in *.\n\n(** [folds P1,..,PN] is a shortcut for [fold P1 in *; ..; fold PN in *]. *)\n\nTactic Notation \"folds\" constr(H) :=\n fold H in *.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) :=\n folds H1; folds H2.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) \",\" constr(H3) :=\n folds H1; folds H2; folds H3.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) \",\" constr(H3)\n \",\" constr(H4) :=\n folds H1; folds H2; folds H3; folds H4.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) \",\" constr(H3)\n \",\" constr(H4) \",\" constr(H5) :=\n folds H1; folds H2; folds H3; folds H4; folds H5.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Simplification *)\n\n(** [simpls] is a shortcut for [simpl in *]. *)\n\nTactic Notation \"simpls\" :=\n simpl in *.\n\n(** [simpls P1,..,PN] is a shortcut for \n [simpl P1 in *; ..; simpl PN in *]. *)\n\nTactic Notation \"simpls\" reference(F1) :=\n simpl F1 in *.\nTactic Notation \"simpls\" reference(F1) \",\" reference(F2) :=\n simpls F1; simpls F2.\nTactic Notation \"simpls\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) :=\n simpls F1; simpls F2; simpls F3.\nTactic Notation \"simpls\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) \",\" reference(F4) :=\n simpls F1; simpls F2; simpls F3; simpls F4.\n\n(** [unsimpl E] replaces all occurence of [X] by [E], where [X] is \n the result which the tactic [simpl] would give when applied to [E]. \n It is useful to undo what [simpl] has simplified too far. *)\n\nTactic Notation \"unsimpl\" constr(E) := \n let F := (eval simpl in E) in change F with E.\n\n(** [unsimpl E in H] is similar to [unsimpl E] but it applies\n inside a particular hypothesis [H]. *)\n\nTactic Notation \"unsimpl\" constr(E) \"in\" hyp(H) := \n let F := (eval simpl in E) in change F with E in H.\n\n(** [unsimpl E in *] applies [unsimpl E] everywhere possible. *)\n\nTactic Notation \"unsimpl\" constr(E) \"in\" \"*\" := \n let F := (eval simpl in E) in change F with E in *.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Substitution *)\n\n(** [substs] does the same as [subst], except that it does not fail\n when there are circular equalities in the context. *)\n\nTactic Notation \"substs\" :=\n repeat (match goal with H: ?x = ?y |- _ => \n first [ subst x | subst y ] end).\n\n(** Implementation of [substs below]. *)\n\nLtac substs_below limit := \n match goal with H: ?T |- _ =>\n match T with\n | limit => idtac\n | ?x = ?y => \n first [ subst x; substs_below limit\n | subst y; substs_below limit\n | generalizes H; substs_below limit; intro ] \n end end.\n\n(** [substs below body E] applies [subst] on all equalities that appear\n in the context below the first hypothesis whose body is [E].\n If there is no such hypothesis in the context, it is equivalent\n to [subst]. For instance, if [H] is an hypothesis, then \n [substs below H] will substitute equalities below hypothesis [H]. *)\n\nTactic Notation \"substs\" \"below\" \"body\" constr(M) :=\n substs_below M.\n\n(** [substs below H] applies [subst] on all equalities that appear\n in the context below the hypothesis named [H]. Note that \n the current implementation is technically incorrect since it\n will confuse different hypotheses with the same body. *)\n\nTactic Notation \"substs\" \"below\" hyp(H) :=\n match type of H with ?M => substs below body M end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Proving equalities *)\n\n(** [fequal] is a variation on [f_equal] which has a better behaviour\n on equalities between n-ary tuples. *)\n\nLtac fequal_base :=\n let go := f_equal; [ fequal_base | ] in\n match goal with\n | |- (_,_,_) = (_,_,_) => go\n | |- (_,_,_,_) = (_,_,_,_) => go\n | |- (_,_,_,_,_) = (_,_,_,_,_) => go\n | |- (_,_,_,_,_,_) = (_,_,_,_,_,_) => go\n | |- _ => f_equal\n end.\n\nTactic Notation \"fequal\" :=\n fequal_base.\n\n(** [fequals] is the same as [fequal] except that it tries and solve\n all trivial subgoals, using [reflexivity] and [congruence].\n (It applies to goals of the form [f x1 .. xN = f y1 .. yN]\n and may produce subgoals of the form [xi = yi]). *)\n\nLtac fequal_post :=\n first [ reflexivity | congruence | idtac ].\n\nTactic Notation \"fequals\" :=\n fequal; fequal_post.\n\n(** [fequals_rec] calls [fequals] recursively. \n It is equivalent to [repeat (progress fequals)]. *)\n\nTactic Notation \"fequals_rec\" :=\n repeat (progress fequals). \n\n\n\n(* ********************************************************************** *)\n(** * Inversion *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Tools for naming hypotheses generated by inversion *)\n\n(** [ltac_Mark] and [ltac_mark] are dummy definitions used as sentinel\n by tactics. The [ltac_mark] has type [ltac_Mark]. *)\n\nInductive ltac_Mark : Type :=\n | ltac_mark : ltac_Mark.\n\n(** [gen_until_mark] repeats [generalize] on hypotheses from the \n context, starting from the bottom and stopping as soon as reaching\n an hypothesis of type [Mark]. If fails if [Mark] does not\n appear in the context. *)\n\nLtac gen_until_mark :=\n match goal with H: ?T |- _ =>\n match T with \n | ltac_Mark => clear H\n | _ => generalizes H; gen_until_mark\n end end.\n\n(** [intro_until_mark] repeats [intro] until reaching an hypothesis of\n type [Mark]. It throws away the hypothesis [Mark]. \n It fails if [Mark] does not appear as an hypothesis in the \n goal. *)\n\nLtac intro_until_mark :=\n match goal with \n | |- (ltac_Mark -> _) => intros _\n | _ => intro; intro_until_mark\n end.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Basic inversion *)\n\n(** [invert keep H] is same to [inversion H] except that it puts all the\n facts obtained in the goal. The keyword [keep] means that the\n hypothesis [H] should not be removed. *)\n\nTactic Notation \"invert\" \"keep\" hyp(H) :=\n pose ltac_mark; inversion H; gen_until_mark.\n\n(** [invert keep H as X1 .. XN] is the same as [inversion H as ...] except\n that only hypotheses which are not variable need to be named\n explicitely, in a similar fashion as [introv] is used to name\n only hypotheses. *)\n\nTactic Notation \"invert\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) :=\n invert keep H; introv I1. \nTactic Notation \"invert\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n invert keep H; introv I1 I2. \nTactic Notation \"invert\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n invert keep H; introv I1 I2 I3. \n\n(** [invert H] is same to [inversion H] except that it puts all the\n facts obtained in the goal and clears hypothesis [H].\n In other words, it is equivalent to [invert keep H; clear H]. *)\n\nTactic Notation \"invert\" hyp(H) :=\n invert keep H; clear H.\n\n(** [invert H as X1 .. XN] is the same as [invert keep H as X1 .. XN]\n but it also clears hypothesis [H]. *)\n\nTactic Notation \"invert_tactic\" hyp(H) tactic(tac) :=\n let H' := fresh in rename H into H'; tac H'; clear H'.\nTactic Notation \"invert\" hyp(H) \"as\" simple_intropattern(I1) :=\n invert_tactic H (fun H => invert keep H as I1).\nTactic Notation \"invert\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n invert_tactic H (fun H => invert keep H as I1 I2).\nTactic Notation \"invert\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n invert_tactic H (fun H => invert keep H as I1 I2 I3).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inversion with substitution *)\n\n(** Our inversion tactics is able to get rid of dependent equalities\n generated by [inversion], using proof irrelevance. *)\n\nRequire Import Eqdep.\n\nLtac inverts_tactic H i1 i2 i3 i4 i5 :=\n let rec go i1 i2 i3 i4 i5 :=\n match goal with \n | |- (ltac_Mark -> _) => intros _\n | |- (?x = ?y -> _) => let H := fresh in intro H; \n first [ subst x | subst y ]; \n go i1 i2 i3 i4 i5\n | |- (existT ?P ?p ?x = existT ?P ?p ?y -> _) =>\n let H := fresh in intro H; \n generalize (@EqdepTheory.inj_pair2 _ P p x y H);\n clear H; go i1 i2 i3 i4 i5\n | |- (?P -> ?Q) => i1; go i2 i3 i4 i5 ltac:(intro)\n | |- (forall _, _) => intro; go i1 i2 i3 i4 i5\n end in\n generalize ltac_mark; invert keep H; go i1 i2 i3 i4 i5.\n\n(** [inverts keep H] is same to [invert keep H] except that it \n applies [subst] to all the equalities generated by the inversion. *)\n\nTactic Notation \"inverts\" \"keep\" hyp(H) :=\n inverts_tactic H ltac:(intro) ltac:(intro) ltac:(intro) ltac:(intro) ltac:(intro).\n\n(** [inverts keep H as X1 .. XN] is the same as\n [invert keep H as X1 .. XN] except that it applies [subst] to all the \n equalities generated by the inversion *)\n\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) :=\n inverts_tactic H ltac:(intros I1) \n ltac:(intro) ltac:(intro) ltac:(intro) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2)\n ltac:(intro) ltac:(intro) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2) ltac:(intros I3)\n ltac:(intro) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2) ltac:(intros I3)\n ltac:(intros I4) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4)\n simple_intropattern(I5) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2) ltac:(intros I3)\n ltac:(intros I4) ltac:(intros I5).\n\n(** [inverts H] is same to [inverts keep H] except that it \n clears hypothesis [H]. *)\n\nTactic Notation \"inverts\" hyp(H) :=\n inverts keep H; clear H.\n\n(** [inverts H as X1 .. XN] is the same as [inverts keep H as X1 .. XN]\n but it also clears the hypothesis [H]. *)\n\nTactic Notation \"inverts_tactic\" hyp(H) tactic(tac) :=\n let H' := fresh in rename H into H'; tac H'; clear H'.\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) :=\n invert_tactic H (fun H => inverts keep H as I1).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n invert_tactic H (fun H => inverts keep H as I1 I2).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n invert_tactic H (fun H => inverts keep H as I1 I2 I3).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4) :=\n invert_tactic H (fun H => inverts keep H as I1 I2 I3 I4).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4) \n simple_intropattern(I5) :=\n invert_tactic H (fun H => inverts keep H as I1 I2 I3 I4 I5).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Injection with substitution *)\n\n(** Underlying implementation of [injects] *)\n\nLtac injects_tactic H :=\n let rec go _ :=\n match goal with \n | |- (ltac_Mark -> _) => intros _\n | |- (?x = ?y -> _) => let H := fresh in intro H; \n first [ subst x | subst y | idtac ]; \n go tt\n end in\n generalize ltac_mark; injection H; go tt.\n\n(** [injects keep H] takes an hypothesis [H] of the form\n [C a1 .. aN = C b1 .. bN] and substitute all equalities\n [ai = bi] that have been generated. *)\n\nTactic Notation \"injects\" \"keep\" hyp(H) :=\n injects_tactic H.\n\n(** [injects H] is similar to [injects keep H] but clears \n the hypothesis [H]. *)\n\nTactic Notation \"injects\" hyp(H) :=\n injects_tactic H; clear H.\n\n(** [inject H as X1 .. XN] is the same as [injection]\n followed by [intros X1 .. XN] *)\n \nTactic Notation \"inject\" hyp(H) :=\n injection H. \nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) :=\n injection H; intros X1.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) :=\n injection H; intros X1 X2.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) ident(X3) :=\n injection H; intros X1 X2 X3.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) ident(X3) \n ident(X4) :=\n injection H; intros X1 X2 X3 X4.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) ident(X3) \n ident(X4) ident(X5) :=\n injection H; intros X1 X2 X3 X4 X5.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inversion and injection with substitution --rough implementation *)\n\n(** The tactics [inversions] and [injections] provided in this section\n are similar to [inverts] and [injects] except that they perform\n substitution on all equalities from the context and not only\n the ones freshly generated. The counterpart is that they have\n simpler implementations. *)\n\n(** [inversions keep H] is the same as [inversions H] but it does\n not clear hypothesis [H]. *)\n\nTactic Notation \"inversions\" \"keep\" hyp(H) :=\n inversion H; subst.\n\n(** [inversions H] is a shortcut for [inversion H] followed by [subst]\n and [clear H].\n It is a rough implementation of [inverts keep H] which behave\n badly when the proof context already contains equalities. \n It is provided in case the better implementation turns out to be\n too slow. *)\n\nTactic Notation \"inversions\" hyp(H) :=\n inversion H; subst; clear H.\n\n(** [injections keep H] is the same as [injection H] followed\n by [intros] and [subst]. It is a rough implementation of \n [injects keep H] which behave\n badly when the proof context already contains equalities,\n or when the goal starts with a forall or an implication. *)\n\nTactic Notation \"injections\" \"keep\" hyp(H) :=\n injection H; intros; subst.\n\n(** [injections H] is the same as [injection H] followed\n by [intros] and [clear H] and [subst]. It is a rough \n implementation of [injects keep H] which behave\n badly when the proof context already contains equalities,\n or when the goal starts with a forall or an implication. *)\n\nTactic Notation \"injections\" \"keep\" hyp(H) :=\n injection H; clear H; intros; subst.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Case analysis *)\n\n(** [case_if] looks for a pattern of the form [if ?B then ?E1 else ?E2]\n in the goal, and perform a case analysis on [B] by calling \n [destruct B]. It looks in the goal first, and otherwise in the\n first hypothesis that contains and [if] statement. \n [case_if in H] can be used to specify which hypothesis to consider. \n Syntaxes [case_if as Eq] and [case_if in H as Eq] allows to name\n the hypothesis coming from the case analysis. *)\nLtac case_if_on_tactic E Eq :=\n let X := fresh in \n sets_eq <- X Eq: E;\n destruct X.\n\nTactic Notation \"case_if_on\" constr(E) \"as\" simple_intropattern(Eq) :=\n case_if_on_tactic E Eq.\n\nTactic Notation \"case_if\" \"as\" simple_intropattern(Eq) :=\n match goal with \n | |- context [if ?B then _ else _] => case_if_on B as Eq\n | K: context [if ?B then _ else _] |- _ => case_if_on B as Eq\n end.\n\nTactic Notation \"case_if\" \"in\" hyp(H) \"as\" simple_intropattern(Eq) :=\n match type of H with context [if ?B then _ else _] => \n case_if_on B as Eq end.\n\nTactic Notation \"case_if\" :=\n let Eq := fresh in case_if as Eq.\n\nTactic Notation \"case_if\" \"in\" hyp(H) :=\n let Eq := fresh in case_if in H as Eq.\n\n\n(* ********************************************************************** *)\n(** * Induction *)\n\n(** [gen_eq X: E] is a tactic whose purpose is to introduce \n equalities so as to work around the limitation of the [induction]\n tactic which typically loses information. [gen_eq E as X] replaces \n all occurences of term [E] with a fresh variable [X] and the equality\n [X = E] as extra hypothesis to the current conclusion. In other words\n a conclusion [C] will be turned into [(X = E) -> C].\n [gen_eq: E] and [gen_eq: E as X] are also accepted. *)\n\nTactic Notation \"gen_eq\" ident(X) \":\" constr(E) :=\n let EQ := fresh in sets_eq X EQ: E; revert EQ.\nTactic Notation \"gen_eq\" \":\" constr(E) :=\n let X := fresh \"X\" in gen_eq X: E.\nTactic Notation \"gen_eq\" \":\" constr(E) \"as\" ident(X) :=\n gen_eq X: E.\nTactic Notation \"gen_eq\" ident(X1) \":\" constr(E1) \",\"\n ident(X2) \":\" constr(E2) :=\n gen_eq X2: E2; gen_eq X1: E1.\nTactic Notation \"gen_eq\" ident(X1) \":\" constr(E1) \",\"\n ident(X2) \":\" constr(E2) \",\" ident(X3) \":\" constr(E3) :=\n gen_eq X3: E3; gen_eq X2: E2; gen_eq X1: E1.\n\n\n(** [inductions H] is a tactic similar to [induction H] except\n that it is able to introduce equalities in order to avoid\n losing information. The syntax [inductions H gen X1 .. XN end]\n is to be used in order to generalize variables before the \n induction. Syntaxes [inductions H as I] and\n [inductions H as I gen X1 .. XN end] are also available.\n\n For technical reasons, the tactic [inductions] will not introduce\n equalities for constants (e.g. if [H] has type [P 0 x], [inductions]\n will not save the information that the first argument is [0]). \n However, the tactic [inductions'] aggressively introduces equalities\n for all arguments, and will apply. The reason why [inductions'] is not\n the default tactic is that it may introduce more equalities than necessary,\n which slightly pollutes the induction hypotheses.\n*)\n\nLtac gen_eq_for_inductions H E :=\n let X := fresh \"aux\" in\n let HX := fresh \"H\" X in\n set (X := E) in H |-;\n assert (HX : ltac_tag_subst (X = E));\n [ unfold ltac_tag_subst; reflexivity\n | clearbody X; generalizes HX ].\n\n(* [apply_to_all_args T Tac] expects the type [T] to be of the form [P E1 .. En]\n and applies the tactic [Tac] to all the arguments [Ei]. *)\n\nLtac apply_to_all_args T go :=\n match T with\n | ?P ?E1 ?E2 ?E3 ?E4 ?E5 ?E6 => go E1; go E2; go E3; go E4; go E5; go E6\n | ?P ?E1 ?E2 ?E3 ?E4 ?E5 => go E1; go E2; go E3; go E4; go E5\n | ?P ?E1 ?E2 ?E3 ?E4 => go E1; go E2; go E3; go E4\n | ?P ?E1 ?E2 ?E3 => go E1; go E2; go E3\n | ?P ?E1 ?E2 => go E1; go E2\n | ?P ?E1 => go E1\n end.\n\n(* [gens_eqs' H] introduces equalities to name arguments in [H]. *)\n\nTactic Notation \"gen_eqs'\" hyp(H) :=\n let T := type of H in\n let go E := try gen_eq_for_inductions H E in\n apply_to_all_args T go.\n\n(* [gens_eqs H] is same as [gens_eqs' H] but it tries to be slightly more\n clever. As a consequence, it generates fewer equalities, but sometimes\n it forgets some equalities. This happens when some arguments of [H] are\n constants. *)\n\nTactic Notation \"gen_eqs\" hyp(H) :=\n let T := type of H in\n let go E := \n match is_metavar E with\n | true => idtac\n | false => try gen_eq_for_inductions H E\n end in\n apply_to_all_args T go.\n\nLtac intros_head_ltac_tag_subst :=\n try match goal with |- (ltac_tag_subst (?x = ?y) -> ?Q) =>\n let H := fresh \"Aux\" in \n intro H; unfold ltac_tag_subst in H;\n try subst x; intros_head_ltac_tag_subst\n end.\n\nLtac inductions_post :=\n intros_head_ltac_tag_subst; \n unfold ltac_tag_subst in * |-.\n\nTactic Notation \"inductions\" hyp(H) :=\n gen_eqs H; induction H; inductions_post.\nTactic Notation \"inductions\" hyp(H) \"as\" simple_intropattern(I) :=\n gen_eqs H; induction H as I; inductions_post.\nTactic Notation \"inductions\" hyp(H) tactic(Gen) \"end\" :=\n gen_eqs H; Gen; induction H; inductions_post.\nTactic Notation \"inductions\" hyp(H) \"as\" simple_intropattern(I) \n tactic(Gen) \"end\" :=\n gen_eqs H; Gen; induction H as I; inductions_post.\n\nTactic Notation \"inductions'\" hyp(H) :=\n gen_eqs' H; induction H; inductions_post.\nTactic Notation \"inductions'\" hyp(H) \"as\" simple_intropattern(I) :=\n gen_eqs' H; induction H as I; inductions_post.\nTactic Notation \"inductions'\" hyp(H) tactic(Gen) \"end\" :=\n gen_eqs' H; Gen; induction H; inductions_post.\nTactic Notation \"inductions'\" hyp(H) \"as\" simple_intropattern(I) \n tactic(Gen) \"end\" :=\n gen_eqs' H; Gen; induction H as I; inductions_post.\n\n(** [induction_wf IH: E X] is used to apply the well-founded induction\n principle, for a given well-founded relation. It applies to a goal\n [PX] where [PX] is a proposition on [X]. First, it sets up the\n goal in the form [(fun a => P a) X], using [pattern X], and then\n it applies the well-founded induction principle instantiated on [E],\n where [E] is a term of type [well_founded R], and [R] is a binary\n relation.\n Syntaxes [induction_wf: E X] and [induction_wf E X]\n and [induction_wf E X as IH] are also available. *)\n\nTactic Notation \"induction_wf\" ident(IH) \":\" constr(E) ident(X) :=\n pattern X; apply (well_founded_ind E); clear X; intros X IH.\nTactic Notation \"induction_wf\" \":\" constr(E) ident(X) :=\n let IH := fresh \"IH\" in induction_wf IH: E X.\nTactic Notation \"induction_wf\" \":\" constr(E) ident(X) \"as\" ident(IH) :=\n induction_wf IH: E X.\nTactic Notation \"induction_wf\" \":\" constr(E) ident(X) :=\n induction_wf: E X.\n\n\n(* ********************************************************************** *)\n(** * Decidable equality *)\n\n(** [decides_equality] is the same as [decide equality] excepts that it \n is able to unfold definitions at head of the current goal. *)\n\nLtac decides_equality_tactic :=\n first [ decide equality | progress(unfolds); decides_equality_tactic ].\n\nTactic Notation \"decides_equality\" :=\n decides_equality_tactic.\n\n\n(* ********************************************************************** *)\n(** * N-ary Conjunctions and Disjunctions *)\n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Conjunctions Splitting in Goals *)\n\n(** Underlying implementation of [splits]. *)\n\nLtac splits_tactic N :=\n match N with\n | O => fail\n | S O => idtac\n | S ?N' => split; [| splits_tactic N']\n end.\n\nLtac unfold_goal_until_conjunction :=\n match goal with\n | |- _ /\\ _ => idtac\n | _ => progress(unfolds); unfold_goal_until_conjunction\n end.\n\nLtac get_term_conjunction_arity T :=\n match T with\n | _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(8)\n | _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(7)\n | _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(6)\n | _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(5)\n | _ /\\ _ /\\ _ /\\ _ => constr:(4)\n | _ /\\ _ /\\ _ => constr:(3)\n | _ /\\ _ => constr:(2)\n | _ -> ?T' => get_term_conjunction_arity T'\n | _ => let P := get_head T in\n let T' := eval unfold P in T in\n match T' with \n | T => fail 1\n | _ => get_term_conjunction_arity T'\n end\n end.\n\nLtac get_goal_conjunction_arity :=\n match goal with |- ?T => get_term_conjunction_arity T end.\n\n(** [splits] applies to a goal of the form [(T1 /\\ .. /\\ TN)] and\n destruct it into [N] subgoals [T1] .. [TN]. If the goal is not a \n conjunction, then it unfolds the head definition. *)\n\nTactic Notation \"splits\" :=\n unfold_goal_until_conjunction;\n let N := get_goal_conjunction_arity in\n splits_tactic N.\n\n(** [splits N] is similar to [splits], except that it will unfold as many\n definitions as necessary to obtain an [N]-ary conjunction. *)\n\nTactic Notation \"splits\" constr(N) := \n splits_tactic N.\n\n(** [splits_all] will recursively split any conjunction, unfolding\n definitions when necessary. *)\n\nTactic Notation \"splits_all\" := \n repeat split.\n\n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Conjunctions Deconstruction *)\n\n(** Underlying implementation of [destructs]. *)\n\nLtac destructs_conjunction_tactic N T :=\n match N with\n | 2 => destruct T as [? ?]\n | 3 => destruct T as [? [? ?]]\n | 4 => destruct T as [? [? [? ?]]]\n | 5 => destruct T as [? [? [? [? ?]]]]\n | 6 => destruct T as [? [? [? [? [? ?]]]]]\n | 7 => destruct T as [? [? [? [? [? [? ?]]]]]]\n end. \n\n(** [destructs T] allows destructing a term [T] which is a N-ary \n conjunction. It is equivalent to [destruct T as (H1 .. HN)], \n except that it does not require to manually specify N different \n names. *)\n\nTactic Notation \"destructs\" constr(T) :=\n let TT := type of T in\n let N := get_term_conjunction_arity TT in \n destructs_conjunction_tactic N T.\n\n(** [destructs N T] is equivalent to [destruct T as (H1 .. HN)],\n except that it does not require to manually specify N different \n names. Remark that it is not restricted to N-ary conjunctions. *)\n\nTactic Notation \"destructs\" constr(N) constr(T) :=\n destructs_conjunction_tactic N T.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Proving goals which are N-ary disjunctions *)\n\n(** Underlying implementation of [branch]. *)\n\n(*\nLtac branch_tactic K N := \n match constr: (K,N) with\n | (_,0) => fail 1\n | (0,_) => fail 1\n | (1,1) => idtac\n | (1,_) => left\n | (S ?K', S ?N') => right; branch_tactic K' N'\n end.\n*)\n\nLtac unfold_goal_until_disjunction :=\n match goal with\n | |- _ \\/ _ => idtac\n | _ => progress(unfolds); unfold_goal_until_disjunction\n end.\n\nLtac get_term_disjunction_arity T :=\n match T with\n | _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(8)\n | _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(7)\n | _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(6)\n | _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(5)\n | _ \\/ _ \\/ _ \\/ _ => constr:(4)\n | _ \\/ _ \\/ _ => constr:(3)\n | _ \\/ _ => constr:(2)\n | _ -> ?T' => get_term_disjunction_arity T'\n | _ => let P := get_head T in\n let T' := eval unfold P in T in\n match T' with \n | T => fail 1\n | _ => get_term_disjunction_arity T'\n end\n end.\n\nLtac get_goal_disjunction_arity :=\n match goal with |- ?T => get_term_disjunction_arity T end.\n\n(** [branch N] applies to a goal of the form \n [P1 \\/ ... \\/ PK \\/ ... \\/ PN] and leaves the goal [PK].\n It only able to unfold the head definition (if there is one),\n but for more complex unfolding one should use the tactic\n [branch K of N]. *)\n\n(*\nTactic Notation \"branch\" constr(K) :=\n unfold_goal_until_disjunction; \n let N := get_goal_disjunction_arity in\n branch_tactic K N.\n*)\n\n(** [branch K of N] is similar to [branch K] except that the\n arity of the disjunction [N] is given manually, and so this\n version of the tactic is able to unfold definitions.\n In other words, applies to a goal of the form \n [P1 \\/ ... \\/ PK \\/ ... \\/ PN] and leaves the goal [PK]. *)\n\n(*\nTactic Notation \"branch\" constr(K) \"of\" constr(N) :=\n branch_tactic K N.\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Disjunction Deconstruction *)\n\n(** Underlying implementation of [branches]. *)\n\nLtac destructs_disjunction_tactic N T :=\n match N with\n | 2 => destruct T as [? | ?]\n | 3 => destruct T as [? | ? | ?]\n | 4 => destruct T as [? | ? | ? | ?]\n | 5 => destruct T as [? | ? | ? | ? | ?]\n | 6 => destruct T as [? | ? | ? | ? | ? | ?]\n | 7 => destruct T as [? | ? | ? | ? | ? | ? | ?]\n end.\n\n(** [branches T] allows destructing a term [T] which is a N-ary \n disjunction. It is equivalent to [destruct T as [ H1 | .. | HN ] ], \n and produces [N] subgoals corresponding to the [N] possible cases. *)\n\nTactic Notation \"branches\" constr(T) :=\n let TT := type of T in\n let N := get_term_disjunction_arity TT in\n destructs_disjunction_tactic N T.\n\n(** [branches N T] is the same as [branches T] except that the arity is\n forced to [N]. This version is useful to unfold definitions \n on the fly. *)\n\nTactic Notation \"branches\" constr(N) constr(T) :=\n destructs_disjunction_tactic N T.\n \n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Existentials *)\n\n(* Underlying implementation of [exists]. *)\n\nLtac get_term_existential_arity T :=\n match T with\n | exists x1 x2 x3 x4 x5 x6 x7 x8, _ => constr:(8)\n | exists x1 x2 x3 x4 x5 x6 x7, _ => constr:(7)\n | exists x1 x2 x3 x4 x5 x6, _ => constr:(6)\n | exists x1 x2 x3 x4 x5, _ => constr:(5)\n | exists x1 x2 x3 x4, _ => constr:(4)\n | exists x1 x2 x3, _ => constr:(3)\n | exists x1 x2, _ => constr:(2)\n | exists x1, _ => constr:(1)\n | _ -> ?T' => get_term_existential_arity T'\n | _ => let P := get_head T in\n let T' := eval unfold P in T in\n match T' with \n | T => fail 1\n | _ => get_term_existential_arity T'\n end\n end.\n\nLtac get_goal_existential_arity :=\n match goal with |- ?T => get_term_existential_arity T end.\n\n(** [exists T1 ... TN] is a shorthand for [exists T1; ...; exists TN].\n It is intended to prove goals of the form [exist X1 .. XN, P].\n If an argument provided is [__] (double underscore), then an\n evar is introduced. Calling [exists_ N] is short for \n [exists __ ... __] with [N] double-underscores. Last,\n [exists_] is equivalent to calling [exists_ N] for\n the appropriate value of [N]. *)\n\nTactic Notation \"exists_original\" constr(T1) :=\n exists T1.\nTactic Notation \"exists\" constr(T1) :=\n match T1 with\n | ltac_wild => esplit\n | _ => exists T1\n end.\nTactic Notation \"exists\" constr(T1) constr(T2) :=\n exists T1; exists T2.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) :=\n exists T1; exists T2; exists T3.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) constr(T4) :=\n exists T1; exists T2; exists T3; exists T4.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) :=\n exists T1; exists T2; exists T3; exists T4; exists T5.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) constr(T6) :=\n exists T1; exists T2; exists T3; exists T4; exists T5; exists T6.\nTactic Notation \"exists_\" constr(N) :=\n let rec aux N := \n match N with\n | 0 => idtac\n | S ?N' => esplit; aux N'\n end in\n aux N.\nTactic Notation \"exists_\" := \n let N := get_goal_existential_arity in\n exists_ N.\n\n\n(* ********************************************************************** *)\n(** * Tactics to invoke automation *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definitions of automation tactics *)\n\n(** The two following tactics defined the default behaviour of \n \"light automation\" and \"strong automation\". These tactics\n may be redefined at any time using the syntax [Ltac .. ::= ..]. *)\n\n(** [auto_tilde] is the tactic which will be called each time a symbol\n [~] is used after a tactic. *)\n\nLtac auto_tilde := auto.\n\n(** [auto_star] is the tactic which will be called each time a symbol\n [*] is used after a tactic. *)\n\nLtac auto_star := try solve [ auto | intuition eauto ].\n\n(** [auto~] is a notation for tactic [auto_tilde]. It may be followed\n by lemmas (or proofs terms) which auto will be able to use\n for solving the goal. *)\n\nTactic Notation \"auto~\" :=\n auto_tilde.\nTactic Notation \"auto~\" constr(E1) :=\n lets: E1; auto_tilde.\nTactic Notation \"auto~\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_tilde.\nTactic Notation \"auto~\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_tilde.\n\n(** [auto*] is a notation for tactic [auto_star]. It may be followed\n by lemmas (or proofs terms) which auto will be able to use\n for solving the goal. *)\n\nTactic Notation \"auto*\" :=\n auto_star.\nTactic Notation \"auto*\" constr(E1) :=\n lets: E1; auto_star.\nTactic Notation \"auto*\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_star.\nTactic Notation \"auto*\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_star.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definitions for parsing compatibility *)\n\nTactic Notation \"f_equal\" :=\n f_equal.\nTactic Notation \"constructor\" := \n constructor.\nTactic Notation \"simple\" :=\n simpl.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Parsing for light automation *)\n\n(** Any tactic followed by the symbol [~] will have [auto_tilde] called\n on all of its subgoals. Three exceptions:\n - [cuts] and [asserts] only call [auto] on their first subgoal,\n - [apply~] relies on [sapply] rather than [apply],\n - [tryfalse~] is defined as [tryfalse by auto_tilde].\n\n Some builtin tactics are not defined using tactic notations \n and thus cannot be extended, e.g. [simpl] and [unfold].\n For these, notation such as [simpl~] will not be available. *)\n\nTactic Notation \"apply\" \"~\" constr(H) :=\n sapply H; auto_tilde.\nTactic Notation \"applys\" \"~\" constr(H) :=\n sapply H; auto_tilde.\nTactic Notation \"apply_clear\" \"~\" constr(H) :=\n apply_clear H; auto_tilde.\nTactic Notation \"applys_clear\" \"~\" constr(H) :=\n applys_clear H; auto_tilde.\n\nTactic Notation \"destruct\" \"~\" constr(H) :=\n destruct H; auto_tilde.\nTactic Notation \"destruct\" \"~\" constr(H) \"as\" simple_intropattern(I) :=\n destruct H as I; auto_tilde.\nTactic Notation \"f_equal\" \"~\" :=\n f_equal; auto_tilde.\nTactic Notation \"induction\" \"~\" constr(H) :=\n induction H; auto_tilde.\nTactic Notation \"inversion\" \"~\" constr(H) :=\n inversion H; auto_tilde.\nTactic Notation \"constructor\" \"~\" := \n constructor; auto_tilde.\nTactic Notation \"constructors\" \"~\" := \n constructors; auto_tilde.\n\nTactic Notation \"false\" \"~\" :=\n false; auto_tilde.\nTactic Notation \"false\" \"~\" constr(T) :=\n false T by auto_tilde/.\nTactic Notation \"tryfalse\" \"~\" :=\n tryfalse by auto_tilde/.\nTactic Notation \"tryfalse_inv\" \"~\" :=\n first [ tryfalse~ | false_inv ].\n\nTactic Notation \"asserts\" \"~\" simple_intropattern(H) \":\" constr(E) :=\n asserts H: E; [ auto_tilde | idtac ].\nTactic Notation \"cuts\" \"~\" simple_intropattern(H) \":\" constr(E) :=\n cuts H: E; [ auto_tilde | idtac ].\nTactic Notation \"cuts\" \"~\" \":\" constr(E) :=\n cuts: E; [ auto_tilde | idtac ].\n\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) :=\n lets I: E; auto_tilde.\nTactic Notation \"lets\" \"~\" \":\" constr(E1) :=\n lets: E1; auto_tilde.\nTactic Notation \"lets\" \"~\" \":\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_tilde.\nTactic Notation \"lets\" \"~\" \":\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_tilde.\n\nTactic Notation \"applys\" \"~\" constr(E) constr(A) :=\n applys E A; auto_tilde.\nTactic Notation \"specializes\" \"~\" hyp(H) constr(A) :=\n specializes H A; auto_tilde.\n\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) constr(A) :=\n lets I: E A; auto_tilde.\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) :=\n lets I: E A1 A2; auto_tilde.\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) constr(A3) :=\n lets I: E A1 A2 A3; auto_tilde.\n\nTactic Notation \"forwards\" \"~\" simple_intropattern(I) \":\" constr(E) :=\n forwards I: E; auto_tilde. \nTactic Notation \"forwards\" \"~\" \":\" constr(E) := \n forwards: E; auto_tilde. \n\nTactic Notation \"fapply\" \"~\" constr(E) := \n fapply E; auto_tilde.\nTactic Notation \"sapply\" \"~\" constr(E) :=\n sapply E; auto_tilde.\n\nTactic Notation \"intros_all\" \"~\" :=\n intros_all; auto_tilde.\n\nTactic Notation \"unfolds\" \"~\" reference(F1) :=\n unfolds F1; auto_tilde.\nTactic Notation \"unfolds\" \"~\" reference(F1) reference(F2) :=\n unfolds F1, F2; auto_tilde.\nTactic Notation \"unfolds\" \"~\" reference(F1) reference(F2) reference(F3) :=\n unfolds F1, F2, F3; auto_tilde.\nTactic Notation \"unfolds\" \"~\" reference(F1) reference(F2) reference(F3) \n reference(F4) :=\n unfolds F1, F2, F3, F4; auto_tilde.\n\nTactic Notation \"simple\" \"~\" :=\n simpl; auto_tilde.\nTactic Notation \"simple\" \"~\" \"in\" hyp(H) :=\n simpl in H; auto_tilde.\nTactic Notation \"simpls\" \"~\" :=\n simpls; auto_tilde.\nTactic Notation \"substs\" \"~\" :=\n substs; auto_tilde.\n\nTactic Notation \"rewrite\" \"~\" constr(E) :=\n rewrite E; auto_tilde.\nTactic Notation \"rewrite\" \"~\" \"<-\" constr(E) :=\n rewrite <- E; auto_tilde.\nTactic Notation \"rewrite\" \"~\" constr(E) \"in\" hyp(H) :=\n rewrite E in H; auto_tilde.\nTactic Notation \"rewrite\" \"~\" \"<-\" constr(E) \"in\" hyp(H) :=\n rewrite <- E in H; auto_tilde.\n\nTactic Notation \"rewrite_all\" \"~\" constr(E) :=\n rewrite_all E; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" \"<-\" constr(E) :=\n rewrite_all <- E; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" constr(E) \"in\" ident(H) :=\n rewrite_all E in H; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" \"<-\" constr(E) \"in\" ident(H) :=\n rewrite_all <- E in H; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" constr(E) \"in\" \"*\" :=\n rewrite_all E in *; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" \"<-\" constr(E) \"in\" \"*\" :=\n rewrite_all <- E in *; auto_tilde.\n\nTactic Notation \"asserts_rewrite\" \"~\" constr(E) :=\n asserts_rewrite E; auto_tilde.\nTactic Notation \"asserts_rewrite\" \"~\" \"<-\" constr(E) :=\n asserts_rewrite <- E; auto_tilde.\nTactic Notation \"asserts_rewrite\" \"~\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite E in H; auto_tilde.\nTactic Notation \"asserts_rewrite\" \"~\" \"<-\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite <- E in H; auto_tilde.\n\nTactic Notation \"cuts_rewrite\" \"~\" constr(E) :=\n cuts_rewrite E; auto_tilde.\nTactic Notation \"cuts_rewrite\" \"~\" \"<-\" constr(E) :=\n cuts_rewrite <- E; auto_tilde.\nTactic Notation \"cuts_rewrite\" \"~\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite E in H; auto_tilde.\nTactic Notation \"cuts_rewrite\" \"~\" \"<-\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite <- E in H; auto_tilde.\n\nTactic Notation \"fequal\" \"~\" :=\n fequal; auto_tilde.\nTactic Notation \"fequals\" \"~\" :=\n fequals; auto_tilde.\n\nTactic Notation \"invert\" \"~\" hyp(H) :=\n invert H; auto_tilde.\nTactic Notation \"inverts\" \"~\" hyp(H) :=\n inverts H; auto_tilde.\nTactic Notation \"injects\" \"~\" hyp(H) :=\n injects H; auto_tilde.\nTactic Notation \"inversions\" \"~\" hyp(H) :=\n inversions H; auto_tilde.\n\nTactic Notation \"case_if\" \"~\" :=\n case_if; auto_tilde.\nTactic Notation \"case_if\" \"~\" \"in\" hyp(H) :=\n case_if in H; auto_tilde. \n\nTactic Notation \"decides_equality\" \"~\" :=\n decides_equality; auto_tilde.\n\nTactic Notation \"splits\" \"~\" :=\n splits; auto_tilde.\nTactic Notation \"splits\" \"~\" constr(N) := \n splits N; auto_tilde.\n\nTactic Notation \"destructs\" \"~\" constr(T) :=\n destructs T; auto_tilde.\nTactic Notation \"destructs\" \"~\" constr(N) constr(T) :=\n destructs N T; auto_tilde.\n\n(*\nTactic Notation \"branch\" \"~\" constr(N) :=\n branch N; auto_tilde.\nTactic Notation \"branch\" \"~\" constr(K) \"of\" constr(N) :=\n branch K of N; auto_tilde.\n\nTactic Notation \"branches\" \"~\" constr(T) :=\n branches T; auto_tilde.\nTactic Notation \"branches\" \"~\" constr(N) constr(T) :=\n branches N T; auto_tilde.\n*)\n\nTactic Notation \"exists_\" \"~\" :=\n exists_; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) :=\n exists T1; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) :=\n exists T1 T2; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) :=\n exists T1 T2 T3; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) constr(T4) :=\n exists T1 T2 T3 T4; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) :=\n exists T1 T2 T3 T4 T5; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) constr(T6) :=\n exists T1 T2 T3 T4 T5 T6; auto_tilde.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Parsing for strong automation *)\n\n(** Any tactic followed by the symbol [*] will have [auto*] called\n on all of its subgoals. The exceptions to these rules are the\n same as for light automation. \n\n Exception: use [subs*] instead of [subst*] if you \n import the library [Coq.Classes.Equivalence]. *)\n\nTactic Notation \"apply\" \"*\" constr(H) :=\n sapply H; auto_star.\nTactic Notation \"applys\" \"*\" constr(H) :=\n sapply H; auto_star.\nTactic Notation \"apply_clear\" \"*\" constr(H) :=\n applys_clear H; auto_star.\nTactic Notation \"applys_clear\" \"*\" constr(H) :=\n applys_clear H; auto_star.\n\nTactic Notation \"destruct\" \"*\" constr(H) :=\n destruct H; auto_star.\nTactic Notation \"destruct\" \"*\" constr(H) \"as\" simple_intropattern(I) :=\n destruct H as I; auto_star.\nTactic Notation \"f_equal\" \"*\" :=\n f_equal; auto_star.\nTactic Notation \"induction\" \"*\" constr(H) :=\n induction H; auto_star.\nTactic Notation \"inversion\" \"*\" constr(H) :=\n inversion H; auto_star.\nTactic Notation \"subs\" \"*\" :=\n subst; auto_star.\nTactic Notation \"subst\" \"*\" :=\n subst; auto_star.\nTactic Notation \"constructor\" \"*\" := \n constructor; auto_star.\nTactic Notation \"constructors\" \"*\" := \n constructors; auto_star.\n\nTactic Notation \"false\" \"*\" :=\n false; auto_star.\nTactic Notation \"false\" \"*\" constr(T) :=\n false T by auto_star/.\nTactic Notation \"tryfalse\" \"*\" :=\n tryfalse by auto_star/.\nTactic Notation \"tryfalse_inv\" \"*\" :=\n first [ tryfalse* | false_inv ].\n\nTactic Notation \"asserts\" \"*\" simple_intropattern(H) \":\" constr(E) :=\n asserts H: E; [ auto_star | idtac ].\nTactic Notation \"cuts\" \"*\" simple_intropattern(H) \":\" constr(E) :=\n cuts H: E; [ auto_star | idtac ].\nTactic Notation \"cuts\" \"*\" \":\" constr(E) :=\n cuts: E; [ auto_star | idtac ].\n\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) :=\n lets I: E; auto_star.\nTactic Notation \"lets\" \"*\" \":\" constr(E1) :=\n lets: E1; auto_star.\nTactic Notation \"lets\" \"*\" \":\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_star.\nTactic Notation \"lets\" \"*\" \":\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_star.\n\nTactic Notation \"applys\" \"*\" constr(E) constr(A) :=\n applys E A; auto_star.\nTactic Notation \"specializes\" \"*\" hyp(H) constr(A) :=\n specializes H A; auto_star.\n\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) constr(A) :=\n lets I: E A; auto_star.\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) :=\n lets I: E A1 A2; auto_star.\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) constr(A3) :=\n lets I: E A1 A2 A3; auto_star.\n\nTactic Notation \"forwards\" \"*\" simple_intropattern(I) \":\" constr(E) :=\n forwards I: E; auto_star. \nTactic Notation \"forwards\" \"*\" \":\" constr(E) := \n forwards: E; auto_star. \n\nTactic Notation \"fapply\" \"*\" constr(E) := \n fapply E; auto_star.\nTactic Notation \"sapply\" \"*\" constr(E) :=\n sapply E; auto_star.\n\nTactic Notation \"intros_all\" \"*\" :=\n intros_all; auto_star.\n\nTactic Notation \"unfolds\" \"*\" reference(F1) :=\n unfolds F1; auto_star.\nTactic Notation \"unfolds\" \"*\" reference(F1) reference(F2) :=\n unfolds F1, F2; auto_star.\nTactic Notation \"unfolds\" \"*\" reference(F1) reference(F2) reference(F3) :=\n unfolds F1, F2, F3; auto_star.\nTactic Notation \"unfolds\" \"*\" reference(F1) reference(F2) reference(F3) \n reference(F4) :=\n unfolds F1, F2, F3, F4; auto_star.\n\nTactic Notation \"simple\" \"*\" :=\n simpl; auto_star.\nTactic Notation \"simple\" \"*\" \"in\" hyp(H) :=\n simpl in H; auto_star.\nTactic Notation \"simpls\" \"*\" :=\n simpls; auto_star.\nTactic Notation \"substs\" \"*\" :=\n substs; auto_star.\n\nTactic Notation \"rewrite\" \"*\" constr(E) :=\n rewrite E; auto_star.\nTactic Notation \"rewrite\" \"*\" \"<-\" constr(E) :=\n rewrite <- E; auto_star.\nTactic Notation \"rewrite\" \"*\" constr(E) \"in\" hyp(H) :=\n rewrite E in H; auto_star.\nTactic Notation \"rewrite\" \"*\" \"<-\" constr(E) \"in\" hyp(H) :=\n rewrite <- E in H; auto_star.\n\nTactic Notation \"rewrite_all\" \"*\" constr(E) :=\n rewrite_all E; auto_star.\nTactic Notation \"rewrite_all\" \"*\" \"<-\" constr(E) :=\n rewrite_all <- E; auto_star.\nTactic Notation \"rewrite_all\" \"*\" constr(E) \"in\" ident(H) :=\n rewrite_all E in H; auto_star.\nTactic Notation \"rewrite_all\" \"*\" \"<-\" constr(E) \"in\" ident(H) :=\n rewrite_all <- E in H; auto_star.\nTactic Notation \"rewrite_all\" \"*\" constr(E) \"in\" \"*\" :=\n rewrite_all E in *; auto_star.\nTactic Notation \"rewrite_all\" \"*\" \"<-\" constr(E) \"in\" \"*\" :=\n rewrite_all <- E in *; auto_star.\n\nTactic Notation \"asserts_rewrite\" \"*\" constr(E) :=\n asserts_rewrite E; auto_star.\nTactic Notation \"asserts_rewrite\" \"*\" \"<-\" constr(E) :=\n asserts_rewrite <- E; auto_star.\nTactic Notation \"asserts_rewrite\" \"*\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite E; auto_star.\nTactic Notation \"asserts_rewrite\" \"*\" \"<-\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite <- E; auto_star.\n\nTactic Notation \"cuts_rewrite\" \"*\" constr(E) :=\n cuts_rewrite E; auto_star.\nTactic Notation \"cuts_rewrite\" \"*\" \"<-\" constr(E) :=\n cuts_rewrite <- E; auto_star.\nTactic Notation \"cuts_rewrite\" \"*\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite E in H; auto_star.\nTactic Notation \"cuts_rewrite\" \"*\" \"<-\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite <- E in H; auto_star.\n\nTactic Notation \"fequal\" \"*\" :=\n fequal; auto_star.\nTactic Notation \"fequals\" \"*\" :=\n fequals; auto_star.\n\nTactic Notation \"invert\" \"*\" hyp(H) :=\n invert H; auto_star.\nTactic Notation \"inverts\" \"*\" hyp(H) :=\n inverts H; auto_star.\nTactic Notation \"injects\" \"*\" hyp(H) :=\n injects H; auto_star.\nTactic Notation \"inversions\" \"*\" hyp(H) :=\n inversions H; auto_star.\n\nTactic Notation \"case_if\" \"*\" :=\n case_if; auto_star.\nTactic Notation \"case_if\" \"*\" \"in\" hyp(H) :=\n case_if in H; auto_star. \n \nTactic Notation \"decides_equality\" \"*\" :=\n decides_equality; auto_star.\n\nTactic Notation \"splits\" \"*\" :=\n splits; auto_star.\nTactic Notation \"splits\" \"*\" constr(N) := \n splits N; auto_star.\n\nTactic Notation \"destructs\" \"*\" constr(T) :=\n destructs T; auto_star.\nTactic Notation \"destructs\" \"*\" constr(N) constr(T) :=\n destructs N T; auto_star.\n\n(*\nTactic Notation \"branch\" \"*\" constr(N) :=\n branch N; auto_star.\nTactic Notation \"branch\" \"*\" constr(K) \"of\" constr(N) :=\n branch K of N; auto_star.\n\nTactic Notation \"branches\" \"*\" constr(T) :=\n branches T; auto_star.\nTactic Notation \"branches\" \"*\" constr(N) constr(T) :=\n branches N T; auto_star.\n*)\n\nTactic Notation \"exists_\" \"*\" :=\n exists_; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) :=\n exists T1; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) :=\n exists T1 T2; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) :=\n exists T1 T2 T3; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) constr(T4) :=\n exists T1 T2 T3 T4; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) :=\n exists T1 T2 T3 T4 T5; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) constr(T6) :=\n exists T1 T2 T3 T4 T5 T6; auto_star.\n\n\n\n(* ********************************************************************** *)\n(** * Tactics to sort out the proof context *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Sorting hypotheses *)\n\n(** [sort] sorts out hypotheses from the context by moving all the\n propositions (hypotheses of type Prop) to the bottom of the context. *)\n\nLtac sort_tactic :=\n match goal with H: ?T |- _ =>\n match type of T with Prop =>\n generalizes H; (try sort_tactic); intro\n end end.\n\nTactic Notation \"sort\" :=\n sort_tactic.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Clearing hypotheses *)\n\n(** [clears X1 ... XN] is a variation on [clear] which clears\n the variables [X1]..[XN] as well as all the hypotheses which\n depend on them. Contrary to [clear], it never fails. *)\n\nTactic Notation \"clears\" ident(X1) :=\n let rec doit _ :=\n match goal with \n | H:context[X1] |- _ => clear H; try (doit tt)\n | _ => clear X1\n end in doit tt.\nTactic Notation \"clears\" ident(X1) ident(X2) :=\n clears X1; clears X2.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) :=\n clears X1; clears X2; clear X3.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) ident(X4) :=\n clears X1; clears X2; clear X3; clear X4.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) ident(X4) \n ident(X5) :=\n clears X1; clears X2; clear X3; clear X4; clear X5.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) ident(X4)\n ident(X5) ident(X6) :=\n clears X1; clears X2; clear X3; clear X4; clear X5; clear X6.\n\n(** [clears] (without any argument) clears all the unused variables\n from the context. In other words, it removes any variable\n which is not a proposition (i.e. not of type Prop) and which \n does not appear in another hypothesis nor in the goal. *)\n\nLtac clears_tactic :=\n match goal with H: ?T |- _ =>\n match type of T with \n | Prop => generalizes H; (try clears_tactic); intro\n | ?TT => clear H; (try clears_tactic)\n | ?TT => generalizes H; (try clears_tactic); intro\n end end.\n\nTactic Notation \"clears\" :=\n clears_tactic.\n\n(** [clear_last] clears the last hypothesis in the context.\n [clear_last N] clears the last [N] hypothesis in the context. *)\n\nTactic Notation \"clear_last\" := \n match goal with H: ?T |- _ => clear H end.\n\nLtac clear_last_base n :=\n match n with\n | 0 => idtac\n | S ?p => clear_last; clear_last_base p\n end.\n\nTactic Notation \"clear_last\" constr(n) := \n clear_last_base n.\n\n\n(* ********************************************************************** *)\n(** * Tactics for development purposes *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Skipping subgoals *)\n\n(** The [skip] tactic can be used at any time to admit the current\n goal. Using [skip] is much more efficient than using the [Focus] \n top-level command to reach a particular subgoal. \n\n There are two possible implementations of [skip]. The first one \n relies on the use of an existential variable. The second one \n relies on an axiom of type [False]. Remark that the builtin tactic\n [admit] is not applicable if the current goal contains uninstantiated\n variables.\n \n The advantage of the first technique is that a proof using [skip]\n must end with [Admitted], since [Qed] will be rejected with the message\n \"[uninstantiated existential variables]\". It is thereafter clear \n that the development is incomplete.\n \n The advantage of the second technique is exactly the converse: one \n may conclude the proof using [Qed], and thus one saves the pain from\n renaming [Qed] into [Admitted] and vice-versa all the time.\n Note however, that it is still necessary to instantiate all the existential\n variables introduced by other tactics in order for [Qed] to be accepted.\n\n The two implementation are provided, so that you can select the one that\n suits you best. By default [skip'] uses the first implementation, and \n [skip] uses the second implementation.\n*)\n\nLtac skip_with_existential :=\n match goal with |- ?G => \n let H := fresh in evar(H:G); eexact H end.\n\nVariable skip_axiom : False. \nLtac skip_with_axiom :=\n assert False; [ apply skip_axiom | contradiction ]. \n (* todo: apply False_rect skip_axim *)\n\nTactic Notation \"skip\" := \n skip_with_axiom. \nTactic Notation \"skip'\" := \n skip_with_existential. \n\n(** [skip H: T] adds an assumption named [H] of type [T] to the \n current context, blindly assuming that it is true.\n [skip: T] and [skip H_asserts: T] and [skip_asserts: T] \n are other possible syntax. \n Note that H may be an intro pattern. \n The syntax [skip H1 .. HN: T] can be used when [T] is a \n conjunction of [N] items. *)\n\nTactic Notation \"skip\" simple_intropattern(I) \":\" constr(T) :=\n asserts I: T; [ skip | ]. \nTactic Notation \"skip\" \":\" constr(T) :=\n let H := fresh in skip H: T. \n\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(T) :=\n skip [I1 I2]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(T) :=\n skip [I1 [I2 I3]]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(T) :=\n skip [I1 [I2 [I3 I4]]]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(T) :=\n skip [I1 [I2 [I3 [I4 I5]]]]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(T) :=\n skip [I1 [I2 [I3 [I4 [I5 I6]]]]]: T.\n\nTactic Notation \"skip_asserts\" simple_intropattern(I) \":\" constr(T) :=\n skip I: T.\nTactic Notation \"skip_asserts\" \":\" constr(T) :=\n skip: T. \n\n(** [skip_cuts T] simply replaces the current goal with [T]. *)\n\nTactic Notation \"skip_cuts\" constr(T) :=\n cuts: T; [ skip | ]. \n\n(** [skip_goal H] applies to any goal. It simply assumes\n the current goal to be true. The assumption is named \"H\".\n It is useful to set up proof by induction or coinduction.\n Syntax [skip_goal] is also accepted.*)\n\nTactic Notation \"skip_goal\" ident(H) :=\n match goal with |- ?G => skip H: G end.\n\nTactic Notation \"skip_goal\" :=\n let IH := fresh \"IH\" in skip_goal IH.\n\n(** [skip_rewrite T] can be applied when [T] is an equality.\n It blindly assumes this equality to be true, and rewrite it in\n the goal. *)\n\nTactic Notation \"skip_rewrite\" constr(T) :=\n let M := fresh in skip_asserts M: T; rewrite M; clear M.\n\n(** [skip_rewrite T in H] is similar as [rewrite_skip], except that\n it rewrites in hypothesis [H]. *)\n\nTactic Notation \"skip_rewrite\" constr(T) \"in\" hyp(H) :=\n let M := fresh in skip_asserts M: T; rewrite M in H; clear M.\n\n(** [skip_rewrites_all T] is similar as [rewrite_skip], except that\n it rewrites everywhere (goal and all hypotheses). *)\n\nTactic Notation \"skip_rewrite_all\" constr(T) :=\n let M := fresh in skip_asserts M: T; rewrite_all M; clear M.\n\n(** [skip_induction E] applies to any goal. It simply assumes\n the current goal to be true (the assumption is named \"IH\" by\n default), and call [destruct E] instead of [induction E]. \n It is useful to try and set up a proof by induction\n first, and fix the applications of the induction hypotheses\n during a second pass on the proof. *)\n\nTactic Notation \"skip_induction\" constr(E) :=\n let IH := fresh \"IH\" in skip_goal IH; destruct E.\n\n(* TODO: why needed? *)\nTactic Notation \"apply\" \"*\" constr(H) :=\n sapply H; auto_star.\n\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Tactics/LibTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.14223189500989633, "lm_q1q2_score": 0.06391796600341242}} {"text": "(** * Sub: Subtyping *)\n\nRequire Import SfLib.\nRequire Import Maps.\nRequire Import Types.\n\n(* ###################################################### *)\n(** * Concepts *)\n\n(** We now turn to the study of _subtyping_, a key feature\n needed to support the object-oriented programming style. *)\n\n(* ###################################################### *)\n(** ** A Motivating Example *)\n\n(** Suppose we are writing a program involving two record types\n defined as follows:\n\n Person = {name:String, age:Nat}\n Student = {name:String, age:Nat, gpa:Nat}\n\n*)\n\n(** In the simply typed lamdba-calculus with records, the term\n\n (\\r:Person. (r.age)+1) {name=\"Pat\",age=21,gpa=1}\n\n is not typable, since it applies a function that wants a one-field\n record to an argument that actually provides two fields, while the\n [T_App] rule demands that the domain type of the function being\n applied must match the type of the argument precisely.\n\n But this is silly: we're passing the function a _better_ argument\n than it needs! The only thing the body of the function can\n possibly do with its record argument [r] is project the field [age]\n from it: nothing else is allowed by the type, and the presence or\n absence of an extra [gpa] field makes no difference at all. So,\n intuitively, it seems that this function should be applicable to\n any record value that has at least an [age] field.\n\n More generally, a record with more fields is \"at least as good in\n any context\" as one with just a subset of these fields, in the\n sense that any value belonging to the longer record type can be\n used _safely_ in any context expecting the shorter record type. If\n the context expects something with the shorter type but we actually\n give it something with the longer type, nothing bad will\n happen (formally, the program will not get stuck).\n\n The principle at work here is called _subtyping_. We say that \"[S]\n is a subtype of [T]\", written [S <: T], if a value of type [S] can\n safely be used in any context where a value of type [T] is\n expected. The idea of subtyping applies not only to records, but\n to all of the type constructors in the language -- functions,\n pairs, etc. *)\n\n(** ** Subtyping and Object-Oriented Languages *)\n\n(** Subtyping plays a fundamental role in many programming\n languages -- in particular, it is closely related to the notion of\n _subclassing_ in object-oriented languages.\n\n An _object_ in Java, C[#], etc. can be thought of as a record,\n some of whose fields are functions (\"methods\") and some of whose\n fields are data values (\"fields\" or \"instance variables\").\n Invoking a method [m] of an object [o] on some arguments [a1..an]\n roughly consists of projecting out the [m] field of [o] and\n applying it to [a1..an].\n\n The type of an object is called a _class_ -- or, in some\n languages, an _interface_. It describes which methods and which\n data fields the object offers. Classes and interfaces are related\n by the _subclass_ and _subinterface_ relations. An object\n belonging to a subclass (or subinterface) is required to provide\n all the methods and fields of one belonging to a superclass (or\n superinterface), plus possibly some more.\n\n The fact that an object from a subclass can be used in place of\n one from a superclass provides a degree of flexibility that is is\n extremely handy for organizing complex libraries. For example, a\n GUI toolkit like Java's Swing framework might define an abstract\n interface [Component] that collects together the common fields and\n methods of all objects having a graphical representation that can\n be displayed on the screen and interact with the user, such as the\n buttons, checkboxes, and scrollbars of a typical GUI. A method\n that relies only on this common interface can now be applied to\n any of these objects.\n\n Of course, real object-oriented languages include many other\n features besides these. For example, fields can be updated.\n Fields and methods can be declared [private]. Classes can give\n _initializers_ that are used when constructing objects. Code in\n subclasses can cooperate with code in superclasses via\n _inheritance_. Classes can have static methods and fields. Etc.,\n etc.\n\n To keep things simple here, we won't deal with any of these\n issues -- in fact, we won't even talk any more about objects or\n classes. (There is a lot of discussion in [Pierce 2002], if\n you are interested.) Instead, we'll study the core concepts\n behind the subclass / subinterface relation in the simplified\n setting of the STLC. *)\n\n(** ** The Subsumption Rule *)\n\n(** Our goal for this chapter is to add subtyping to the simply typed\n lambda-calculus (with some of the basic extensions from [MoreStlc]).\n This involves two steps:\n\n - Defining a binary _subtype relation_ between types.\n\n - Enriching the typing relation to take subtyping into account.\n\n The second step is actually very simple. We add just a single rule\n to the typing relation: the so-called _rule of subsumption_:\n\n Gamma |- t : S S <: T\n ------------------------- (T_Sub)\n Gamma |- t : T\n\n This rule says, intuitively, that it is OK to \"forget\" some of\n what we know about a term. *)\n\n(** For example, we may know that [t] is a record with two\n fields (e.g., [S = {x:A->A, y:B->B}]), but choose to forget about\n one of the fields ([T = {y:B->B}]) so that we can pass [t] to a\n function that requires just a single-field record. *)\n\n(** ** The Subtype Relation *)\n\n(** The first step -- the definition of the relation [S <: T] -- is\n where all the action is. Let's look at each of the clauses of its\n definition. *)\n\n(** *** Structural Rules *)\n\n(** To start off, we impose two \"structural rules\" that are\n independent of any particular type constructor: a rule of\n _transitivity_, which says intuitively that, if [S] is \n better (richer, safer) than [U] and [U] is better than [T], \n then [S] is better than [T]...\n\n S <: U U <: T\n ---------------- (S_Trans)\n S <: T\n\n ... and a rule of _reflexivity_, since certainly any type [T] is\n as good as itself:\n\n ------ (S_Refl)\n T <: T\n\n*)\n\n(** *** Products *)\n\n(** Now we consider the individual type constructors, one by one,\n beginning with product types. We consider one pair to be a subtype \n of another if each of its components is.\n\n S1 <: T1 S2 <: T2\n -------------------- (S_Prod)\n S1 * S2 <: T1 * T2\n\n*)\n\n(** *** Arrows *)\n\n(** The subtyping rule for arrows is a little less intuitive. \n Suppose we have functions [f] and [g] with these types:\n\n f : C -> Student\n g : (C->Person) -> D\n\n That is, [f] is a function that yields a record of type [Student],\n and [g] is a (higher-order) function that expects its argument to be \n a function yielding a record of type [Person]. Also suppose that\n [Student] is a subtype of [Person]. Then the application [g f] is\n safe even though their types do not match up precisely, because\n the only thing [g] can do with [f] is to apply it to some\n argument (of type [C]); the result will actually be a [Student],\n while [g] will be expecting a [Person], but this is safe because\n the only thing [g] can then do is to project out the two fields\n that it knows about ([name] and [age]), and these will certainly\n be among the fields that are present.\n\n This example suggests that the subtyping rule for arrow types\n should say that two arrow types are in the subtype relation if\n their results are:\n\n S2 <: T2\n ---------------- (S_Arrow_Co)\n S1 -> S2 <: S1 -> T2\n\n\n We can generalize this to allow the arguments of the two arrow\n types to be in the subtype relation as well:\n\n T1 <: S1 S2 <: T2\n -------------------- (S_Arrow)\n S1 -> S2 <: T1 -> T2\n\n But notice that the argument types are subtypes \"the other way round\":\n in order to conclude that [S1->S2] to be a subtype of [T1->T2], it\n must be the case that [T1] is a subtype of [S1]. The arrow\n constructor is said to be _contravariant_ in its first argument\n and _covariant_ in its second.\n\n Here is an example that illustrates this:\n\n f : Person -> C\n g : (Student -> C) -> D\n\n The application [g f] is safe, because the only thing the body of\n [g] can do with [f] is to apply it to some argument of type\n [Student]. Since [f] requires records having (at least) the\n fields of a [Person], this will always work. So [Person -> C] is a\n subtype of [Student -> C] since [Student] is a subtype of\n [Person].\n\n The intuition is that, if we have a function [f] of type [S1->S2],\n then we know that [f] accepts elements of type [S1]; clearly, [f]\n will also accept elements of any subtype [T1] of [S1]. The type of\n [f] also tells us that it returns elements of type [S2]; we can\n also view these results belonging to any supertype [T2] of\n [S2]. That is, any function [f] of type [S1->S2] can also be\n viewed as having type [T1->T2]. *)\n\n(** *** Records *)\n\n(** What about subtyping for record types? *)\n\n(** The basic intuition is that it is always safe to use a \"bigger\"\n record in place of a \"smaller\" one. That is, given a record type,\n adding extra fields will always result in a subtype. If some code\n is expecting a record with fields [x] and [y], it is perfectly safe\n for it to receive a record with fields [x], [y], and [z]; the [z]\n field will simply be ignored. For example,\n\n {name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat}\n {name:String, age:Nat} <: {name:String} {name:String} <: {}\n\n This is known as \"width subtyping\" for records. *)\n\n(** We can also create a subtype of a record type by replacing the type\n of one of its fields with a subtype. If some code is expecting a\n record with a field [x] of type [T], it will be happy with a record\n having a field [x] of type [S] as long as [S] is a subtype of\n [T]. For example,\n\n {x:Student} <: {x:Person}\n\n This is known as \"depth subtyping\". *)\n\n(** Finally, although the fields of a record type are written in a\n particular order, the order does not really matter. For example,\n\n {name:String,age:Nat} <: {age:Nat,name:String}\n\n This is known as \"permutation subtyping\". *)\n\n(** We _could_ formalize these requirements in a single subtyping rule\n for records as follows:\n\n forall jk in j1..jn,\n exists ip in i1..im, such that\n jk=ip and Sp <: Tk\n ---------------------------------- (S_Rcd)\n {i1:S1...im:Sm} <: {j1:T1...jn:Tn}\n\n That is, the record on the left should have all the field labels of\n the one on the right (and possibly more), while the types of the\n common fields should be in the subtype relation. \n\n However, this rule is rather heavy and hard to read, so it is often \n decomposed into three simpler rules, which can be combined using \n [S_Trans] to achieve all the same effects. *)\n\n(** First, adding fields to the end of a record type gives a subtype:\n\n n > m\n --------------------------------- (S_RcdWidth)\n {i1:T1...in:Tn} <: {i1:T1...im:Tm}\n\n We can use [S_RcdWidth] to drop later fields of a multi-field\n record while keeping earlier fields, showing for example that\n [{age:Nat,name:String} <: {name:String}]. *)\n\n(** Second, subtyping can be applied inside the components of a compound\n record type:\n\n S1 <: T1 ... Sn <: Tn\n ---------------------------------- (S_RcdDepth)\n {i1:S1...in:Sn} <: {i1:T1...in:Tn}\n\n For example, we can use [S_RcdDepth] and [S_RcdWidth] together to\n show that [{y:Student, x:Nat} <: {y:Person}]. *)\n\n(** Third, subtyping can reorder fields. For example, we\n want [{name:String, gpa:Nat, age:Nat} <: Person]. (We\n haven't quite achieved this yet: using just [S_RcdDepth] and\n [S_RcdWidth] we can only drop fields from the _end_ of a record\n type.) So we add:\n\n {i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}\n --------------------------------------------------- (S_RcdPerm)\n {i1:S1...in:Sn} <: {i1:T1...in:Tn}\n\n*)\n\n(** It is worth noting that full-blown language designs may choose not\n to adopt all of these subtyping rules. For example, in Java:\n\n - A subclass may not change the argument or result types of a\n method of its superclass (i.e., no depth subtyping or no arrow\n subtyping, depending how you look at it).\n\n - Each class member (field or method) can be assigned a single\n index, adding new indices \"on the right\" as more members are\n added in subclasses (i.e., no permutation for classes).\n\n - A class may implement multiple interfaces -- so-called \"multiple\n inheritance\" of interfaces (i.e., permutation is allowed for\n interfaces). *)\n\n(** **** Exercise: 2 stars, recommended (arrow_sub_wrong) *)\n(** Suppose we had incorrectly defined subtyping as covariant on both\n the right and the left of arrow types:\n\n S1 <: T1 S2 <: T2\n -------------------- (S_Arrow_wrong)\n S1 -> S2 <: T1 -> T2\n\n Give a concrete example of functions [f] and [g] with the following types...\n\n f : Student -> Nat\n g : (Person -> Nat) -> Nat\n\n ... such that the application [g f] will get stuck during\n execution.\n\n[] *)\n\n(** *** Top *)\n\n(** Finally, it is convenient to give the subtype relation a maximum\n element -- a type that lies above every other type and is\n inhabited by all (well-typed) values. We do this by adding to the\n language one new type constant, called [Top], together with a\n subtyping rule that places it above every other type in the\n subtype relation:\n\n -------- (S_Top)\n S <: Top\n\n The [Top] type is an analog of the [Object] type in Java and C[#]. *)\n\n(* ############################################### *)\n(** *** Summary *)\n\n(** In summary, we form the STLC with subtyping by starting with the\n pure STLC (over some set of base types) and then...\n\n - adding a base type [Top],\n\n - adding the rule of subsumption\n\n Gamma |- t : S S <: T\n ------------------------- (T_Sub)\n Gamma |- t : T\n\n to the typing relation, and\n\n - defining a subtype relation as follows:\n\n S <: U U <: T\n ---------------- (S_Trans)\n S <: T\n\n ------ (S_Refl)\n T <: T\n\n -------- (S_Top)\n S <: Top\n\n S1 <: T1 S2 <: T2\n -------------------- (S_Prod)\n S1 * S2 <: T1 * T2\n\n T1 <: S1 S2 <: T2\n -------------------- (S_Arrow)\n S1 -> S2 <: T1 -> T2\n\n n > m\n --------------------------------- (S_RcdWidth)\n {i1:T1...in:Tn} <: {i1:T1...im:Tm}\n\n S1 <: T1 ... Sn <: Tn\n ---------------------------------- (S_RcdDepth)\n {i1:S1...in:Sn} <: {i1:T1...in:Tn}\n\n {i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}\n --------------------------------------------------- (S_RcdPerm)\n {i1:S1...in:Sn} <: {i1:T1...in:Tn}\n\n*)\n\n(* ############################################### *)\n(** ** Exercises *)\n\n(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)\n(** Suppose we have types [S], [T], [U], and [V] with [S <: T]\n and [U <: V]. Which of the following subtyping assertions\n are then true? Write _true_ or _false_ after each one.\n ([A], [B], and [C] here are base types.)\n\n - [T->S <: T->S]\n\n - [Top->U <: S->Top]\n\n - [(C->C) -> (A*B) <: (C->C) -> (Top*B)]\n\n - [T->T->U <: S->S->V]\n\n - [(T->T)->U <: (S->S)->V]\n\n - [((T->S)->T)->U <: ((S->T)->S)->V]\n\n - [S*V <: T*U]\n\n[] *)\n\n(** **** Exercise: 2 stars (subtype_order) *)\n(** The following types happen to form a linear order with respect to subtyping:\n - [Top]\n - [Top -> Student]\n - [Student -> Person]\n - [Student -> Top]\n - [Person -> Student]\n\nWrite these types in order from the most specific to the most general.\n\nWhere does the type [Top->Top->Student] fit into this order?\n\n[] *)\n\n(** **** Exercise: 1 star (subtype_instances_tf_2) *)\n(** Which of the following statements are true? Write _true_ or\n _false_ after each one.\n\n forall S T,\n S <: T ->\n S->S <: T->T\n\n forall S,\n S <: A->A ->\n exists T,\n S = T->T /\\ T <: A\n\n forall S T1 T2,\n (S <: T1 -> T2) ->\n exists S1 S2,\n S = S1 -> S2 /\\ T1 <: S1 /\\ S2 <: T2 \n\n exists S,\n S <: S->S \n\n exists S,\n S->S <: S \n\n forall S T1 T2,\n S <: T1*T2 ->\n exists S1 S2,\n S = S1*S2 /\\ S1 <: T1 /\\ S2 <: T2 \n\n[] *)\n\n(** **** Exercise: 1 star (subtype_concepts_tf) *)\n(** Which of the following statements are true, and which are false?\n - There exists a type that is a supertype of every other type.\n\n - There exists a type that is a subtype of every other type.\n\n - There exists a pair type that is a supertype of every other\n pair type.\n\n - There exists a pair type that is a subtype of every other\n pair type.\n\n - There exists an arrow type that is a supertype of every other\n arrow type.\n\n - There exists an arrow type that is a subtype of every other\n arrow type.\n\n - There is an infinite descending chain of distinct types in the\n subtype relation---that is, an infinite sequence of types\n [S0], [S1], etc., such that all the [Si]'s are different and\n each [S(i+1)] is a subtype of [Si].\n\n - There is an infinite _ascending_ chain of distinct types in\n the subtype relation---that is, an infinite sequence of types\n [S0], [S1], etc., such that all the [Si]'s are different and\n each [S(i+1)] is a supertype of [Si].\n\n[] *)\n\n(** **** Exercise: 2 stars (proper_subtypes) *)\n(** Is the following statement true or false? Briefly explain your\n answer.\n\n forall T,\n ~(exists n, T = TBase n) ->\n exists S,\n S <: T /\\ S <> T\n\n[] *)\n\n\n(** **** Exercise: 2 stars (small_large_1) *)\n(**\n - What is the _smallest_ type [T] (\"smallest\" in the subtype\n relation) that makes the following assertion true? (Assume we\n have [Unit] among the base types and [unit] as a constant of this\n type.)\n\n empty |- (\\p:T*Top. p.fst) ((\\z:A.z), unit) : A->A\n\n\n - What is the _largest_ type [T] that makes the same assertion true?\n\n[] *)\n\n(** **** Exercise: 2 stars (small_large_2) *)\n(**\n - What is the _smallest_ type [T] that makes the following\n assertion true?\n\n empty |- (\\p:(A->A * B->B). p) ((\\z:A.z), (\\z:B.z)) : T\n\n\n - What is the _largest_ type [T] that makes the same assertion true?\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (small_large_3) *)\n(**\n - What is the _smallest_ type [T] that makes the following\n assertion true?\n\n a:A |- (\\p:(A*T). (p.snd) (p.fst)) (a , \\z:A.z) : A\n\n\n - What is the _largest_ type [T] that makes the same assertion true?\n\n[] *)\n\n(** **** Exercise: 2 stars (small_large_4) *)\n(**\n - What is the _smallest_ type [T] that makes the following\n assertion true?\n\n exists S,\n empty |- (\\p:(A*T). (p.snd) (p.fst)) : S\n\n\n - What is the _largest_ type [T] that makes the same\n assertion true?\n\n[] *)\n\n(** **** Exercise: 2 stars (smallest_1) *)\n(** What is the _smallest_ type [T] that makes the following\n assertion true?\n\n exists S, exists t,\n empty |- (\\x:T. x x) t : S\n]] \n[] *)\n\n(** **** Exercise: 2 stars (smallest_2) *)\n(** What is the _smallest_ type [T] that makes the following\n assertion true?\n\n empty |- (\\x:Top. x) ((\\z:A.z) , (\\z:B.z)) : T\n]] \n[] *)\n\n(** **** Exercise: 3 stars, optional (count_supertypes) *)\n(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,\n how many different types [T] are there such that [{x:A, y:C->C} <:\n T]? (We consider two types to be different if they are written\n differently, even if each is a subtype of the other. For example,\n [{x:A,y:B}] and [{y:B,x:A}] are different.)\n\n[] *)\n\n(** **** Exercise: 2 stars (pair_permutation) *)\n(** The subtyping rule for product types\n\n S1 <: T1 S2 <: T2\n -------------------- (S_Prod)\n S1*S2 <: T1*T2\n\n intuitively corresponds to the \"depth\" subtyping rule for records. \n Extending the analogy, we might consider adding a \"permutation\" rule\n\n --------------\n T1*T2 <: T2*T1\n\n for products. Is this a good idea? Briefly explain why or why not.\n\n[] *)\n\n(* ###################################################### *)\n(** * Formal Definitions *)\n\n(** Most of the definitions needed to formalize what we've discussed\n above -- in particular, the syntax and operational semantics of\n the language -- are identical to what we saw in the last chapter.\n We just need to extend the typing relation with the subsumption\n rule and add a new [Inductive] definition for the subtyping\n relation. Let's first do the identical bits. *)\n\n(* ###################################################### *)\n(** ** Core Definitions *)\n\n(* ################################### *)\n(** *** Syntax *)\n\n(** In the rest of the chapter, we formalize just base types,\n booleans, arrow types, [Unit], and [Top], omitting record types\n and leaving product types as an exercise. For the sake of more\n interesting examples, we'll add an arbitrary set of base types\n like [String], [Float], etc. (Since they are just for examples,\n we won't bother adding any operations over these base types, but\n we could easily do so.) *)\n\nInductive ty : Type :=\n | TTop : ty\n | TBool : ty\n | TBase : id -> ty\n | TArrow : ty -> ty -> ty\n | TUnit : ty\n.\n\nInductive tm : Type :=\n | tvar : id -> tm\n | tapp : tm -> tm -> tm\n | tabs : id -> ty -> tm -> tm\n | ttrue : tm\n | tfalse : tm\n | tif : tm -> tm -> tm -> tm\n | tunit : tm \n.\n\n(* ################################### *)\n(** *** Substitution *)\n\n(** The definition of substitution remains exactly the same as for the\n pure STLC. *)\n\nFixpoint subst (x:id) (s:tm) (t:tm) : tm :=\n match t with\n | tvar y =>\n if beq_id x y then s else t\n | tabs y T t1 =>\n tabs y T (if beq_id x y then t1 else (subst x s t1))\n | tapp t1 t2 =>\n tapp (subst x s t1) (subst x s t2)\n | ttrue =>\n ttrue\n | tfalse =>\n tfalse\n | tif t1 t2 t3 =>\n tif (subst x s t1) (subst x s t2) (subst x s t3)\n | tunit =>\n tunit \n end.\n\nNotation \"'[' x ':=' s ']' t\" := (subst x s t) (at level 20).\n\n(* ################################### *)\n(** *** Reduction *)\n\n(** Likewise the definitions of the [value] property and the [step]\n relation. *)\n\nInductive value : tm -> Prop :=\n | v_abs : forall x T t,\n value (tabs x T t)\n | v_true :\n value ttrue\n | v_false :\n value tfalse\n | v_unit :\n value tunit\n.\n\nHint Constructors value.\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n | ST_AppAbs : forall x T t12 v2,\n value v2 ->\n (tapp (tabs x T t12) v2) ==> [x:=v2]t12\n | ST_App1 : forall t1 t1' t2,\n t1 ==> t1' ->\n (tapp t1 t2) ==> (tapp t1' t2)\n | ST_App2 : forall v1 t2 t2',\n value v1 ->\n t2 ==> t2' ->\n (tapp v1 t2) ==> (tapp v1 t2')\n | ST_IfTrue : forall t1 t2,\n (tif ttrue t1 t2) ==> t1\n | ST_IfFalse : forall t1 t2,\n (tif tfalse t1 t2) ==> t2\n | ST_If : forall t1 t1' t2 t3,\n t1 ==> t1' ->\n (tif t1 t2 t3) ==> (tif t1' t2 t3)\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n\n(* ###################################################################### *)\n(** ** Subtyping *)\n\n(** Now we come to the interesting part. We begin by defining\n the subtyping relation and developing some of its important\n technical properties. *)\n\n(** The definition of subtyping is just what we sketched in the\n motivating discussion. *)\n\nReserved Notation \"T '<:' U\" (at level 40).\n\nInductive subtype : ty -> ty -> Prop :=\n | S_Refl : forall T,\n T <: T\n | S_Trans : forall S U T,\n S <: U ->\n U <: T ->\n S <: T\n | S_Top : forall S,\n S <: TTop\n | S_Arrow : forall S1 S2 T1 T2,\n T1 <: S1 ->\n S2 <: T2 ->\n (TArrow S1 S2) <: (TArrow T1 T2)\nwhere \"T '<:' U\" := (subtype T U).\n\n(** Note that we don't need any special rules for base types: they are\n automatically subtypes of themselves (by [S_Refl]) and [Top] (by\n [S_Top]), and that's all we want. *)\n\nHint Constructors subtype.\n\nModule Examples.\n\nNotation x := (Id 0).\nNotation y := (Id 1).\nNotation z := (Id 2).\n\nNotation A := (TBase (Id 6)).\nNotation B := (TBase (Id 7)).\nNotation C := (TBase (Id 8)).\n\nNotation String := (TBase (Id 9)).\nNotation Float := (TBase (Id 10)).\nNotation Integer := (TBase (Id 11)).\n\nExample subtyping_example_0 :\n (TArrow C TBool) <: (TArrow C TTop).\n (* C->Bool <: C->Top *)\nProof. auto. Qed.\n\n(** **** Exercise: 2 stars, optional (subtyping_judgements) *)\n(** (Wait to do this exercise after you have added product types to the\n language -- see exercise [products] -- at least up to this point \n in the file).\n\n Recall that, in chapter [MoreStlc], the optional section \"Encoding\n Records\" describes how records can be encoded as pairs.\n Using this encoding, define pair types representing the following \n record types:\n\n Person := { name : String }\n Student := { name : String ;\n gpa : Float }\n Employee := { name : String ;\n ssn : Integer }\n\n*)\nDefinition Person : ty :=\n(* FILL IN HERE *) admit.\nDefinition Student : ty :=\n(* FILL IN HERE *) admit.\nDefinition Employee : ty :=\n(* FILL IN HERE *) admit.\n\n(** Now use the definition of the subtype relation to prove the following: *)\n\nExample sub_student_person :\n Student <: Person.\nProof.\n(* FILL IN HERE *) Admitted.\n\nExample sub_employee_person :\n Employee <: Person.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The following facts are mostly easy to prove in Coq. To get\n full benefit from the exercises, make sure you also\n understand how to prove them on paper! *)\n\n(** **** Exercise: 1 star, optional (subtyping_example_1) *)\nExample subtyping_example_1 :\n (TArrow TTop Student) <: (TArrow (TArrow C C) Person).\n (* Top->Student <: (C->C)->Person *)\nProof with eauto.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (subtyping_example_2) *)\nExample subtyping_example_2 :\n (TArrow TTop Person) <: (TArrow Person TTop).\n (* Top->Person <: Person->Top *)\nProof with eauto.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd Examples.\n\n(* ###################################################################### *)\n(** ** Typing *)\n\n(** The only change to the typing relation is the addition of the rule\n of subsumption, [T_Sub]. *)\n\nDefinition context := partial_map ty.\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n\nInductive has_type : context -> tm -> ty -> Prop :=\n (* Same as before *)\n | T_Var : forall Gamma x T,\n Gamma x = Some T ->\n Gamma |- (tvar x) \\in T\n | T_Abs : forall Gamma x T11 T12 t12,\n (update Gamma x T11) |- t12 \\in T12 ->\n Gamma |- (tabs x T11 t12) \\in (TArrow T11 T12)\n | T_App : forall T1 T2 Gamma t1 t2,\n Gamma |- t1 \\in (TArrow T1 T2) ->\n Gamma |- t2 \\in T1 ->\n Gamma |- (tapp t1 t2) \\in T2\n | T_True : forall Gamma,\n Gamma |- ttrue \\in TBool\n | T_False : forall Gamma,\n Gamma |- tfalse \\in TBool\n | T_If : forall t1 t2 t3 T Gamma,\n Gamma |- t1 \\in TBool ->\n Gamma |- t2 \\in T ->\n Gamma |- t3 \\in T ->\n Gamma |- (tif t1 t2 t3) \\in T\n | T_Unit : forall Gamma,\n Gamma |- tunit \\in TUnit\n (* New rule of subsumption *)\n | T_Sub : forall Gamma t S T,\n Gamma |- t \\in S ->\n S <: T ->\n Gamma |- t \\in T\n\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nHint Constructors has_type.\n\n(** The following hints help [auto] and [eauto] construct typing\n derivations. (See chapter [UseAuto] for more on hints.) *)\n\nHint Extern 2 (has_type _ (tapp _ _) _) =>\n eapply T_App; auto.\nHint Extern 2 (_ = _) => compute; reflexivity.\n\nModule Examples2.\nImport Examples.\n\n(** Do the following exercises after you have added product types to\n the language. For each informal typing judgement, write it as a\n formal statement in Coq and prove it. *)\n\n(** **** Exercise: 1 star, optional (typing_example_0) *)\n(* empty |- ((\\z:A.z), (\\z:B.z))\n : (A->A * B->B) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (typing_example_1) *)\n(* empty |- (\\x:(Top * B->B). x.snd) ((\\z:A.z), (\\z:B.z))\n : B->B *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (typing_example_2) *)\n(* empty |- (\\z:(C->C)->(Top * B->B). (z (\\x:C.x)).snd)\n (\\z:C->C. ((\\z:A.z), (\\z:B.z)))\n : B->B *)\n(* FILL IN HERE *)\n(** [] *)\n\nEnd Examples2.\n\n(* ###################################################################### *)\n(** * Properties *)\n\n(** The fundamental properties of the system that we want to\n check are the same as always: progress and preservation. Unlike\n the extension of the STLC with references (chapter [References]),\n we don't need to change the _statements_ of these properties to\n take subtyping into account. However, their proofs do become a\n little bit more involved. *)\n\n(* ###################################################################### *)\n(** ** Inversion Lemmas for Subtyping *)\n\n(** Before we look at the properties of the typing relation, we need\n to establish a couple of critical structural properties of the\n subtype relation:\n - [Bool] is the only subtype of [Bool], and\n - every subtype of an arrow type is itself an arrow type. *)\n\n(** These are called _inversion lemmas_ because they play a\n similar role in proofs as the built-in [inversion] tactic: given a\n hypothesis that there exists a derivation of some subtyping\n statement [S <: T] and some constraints on the shape of [S] and/or\n [T], each inversion lemma reasons about what this derivation must\n look like to tell us something further about the shapes of [S] and\n [T] and the existence of subtype relations between their parts. *)\n\n(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)\nLemma sub_inversion_Bool : forall U,\n U <: TBool ->\n U = TBool.\nProof with auto.\n intros U Hs.\n remember TBool as V.\n (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)\nLemma sub_inversion_arrow : forall U V1 V2,\n U <: (TArrow V1 V2) ->\n exists U1, exists U2,\n U = (TArrow U1 U2) /\\ (V1 <: U1) /\\ (U2 <: V2).\nProof with eauto.\n intros U V1 V2 Hs.\n remember (TArrow V1 V2) as V.\n generalize dependent V2. generalize dependent V1.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ########################################## *)\n(** ** Canonical Forms *)\n\n(** The proof of the progress theorem -- that a well-typed\n non-value can always take a step -- doesn't need to change too\n much: we just need one small refinement. When we're considering\n the case where the term in question is an application [t1 t2]\n where both [t1] and [t2] are values, we need to know that [t1] has\n the _form_ of a lambda-abstraction, so that we can apply the\n [ST_AppAbs] reduction rule. In the ordinary STLC, this is\n obvious: we know that [t1] has a function type [T11->T12], and\n there is only one rule that can be used to give a function type to\n a value -- rule [T_Abs] -- and the form of the conclusion of this\n rule forces [t1] to be an abstraction.\n\n In the STLC with subtyping, this reasoning doesn't quite work\n because there's another rule that can be used to show that a value\n has a function type: subsumption. Fortunately, this possibility\n doesn't change things much: if the last rule used to show [Gamma\n |- t1 : T11->T12] is subsumption, then there is some\n _sub_-derivation whose subject is also [t1], and we can reason by\n induction until we finally bottom out at a use of [T_Abs].\n\n This bit of reasoning is packaged up in the following lemma, which\n tells us the possible \"canonical forms\" (i.e., values) of function\n type. *)\n\n(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)\nLemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,\n Gamma |- s \\in (TArrow T1 T2) ->\n value s ->\n exists x, exists S1, exists s2,\n s = tabs x S1 s2.\nProof with eauto.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Similarly, the canonical forms of type [Bool] are the constants\n [true] and [false]. *)\n\nLemma canonical_forms_of_Bool : forall Gamma s,\n Gamma |- s \\in TBool ->\n value s ->\n (s = ttrue \\/ s = tfalse).\nProof with eauto.\n intros Gamma s Hty Hv.\n remember TBool as T.\n induction Hty; try solve by inversion...\n - (* T_Sub *)\n subst. apply sub_inversion_Bool in H. subst...\nQed.\n\n\n(* ########################################## *)\n(** ** Progress *)\n\n(** The proof of progress now proceeds just like the one for the\n pure STLC, except that in several places we invoke canonical forms\n lemmas... *)\n\n(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-\n t : T] then [t] is a value or [t ==> t'] for some term [t'].\n\n _Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed\n by induction on the typing derivation.\n\n The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are\n immediate because abstractions, [unit], [true], and [false] are\n already values. The [T_Var] case is vacuous because variables\n cannot be typed in the empty context. The remaining cases are\n more interesting:\n\n - If the last step in the typing derivation uses rule [T_App],\n then there are terms [t1] [t2] and types [T1] and [T2] such that\n [t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-\n t2 : T1]. Moreover, by the induction hypothesis, either [t1] is\n a value or it steps, and either [t2] is a value or it steps.\n There are three possibilities to consider:\n\n - Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2]\n by [ST_App1].\n\n - Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].\n Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a\n value.\n\n - Finally, suppose [t1] and [t2] are both values. By the lemma \n about canonical forms for arrow types, we know that [t1] has the\n form [\\x:S1.s2] for some [x], [S1], and [s2]. But then\n [(\\x:S1.s2) t2 ==> [x:=t2]s2] by [ST_AppAbs], since [t2] is a\n value.\n\n - If the final step of the derivation uses rule [T_If], then there\n are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else\n t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and\n [empty |- t3 : T]. Moreover, by the induction hypothesis,\n either [t1] is a value or it steps.\n\n - If [t1] is a value, then by the canonical forms lemma for\n booleans, either [t1 = true] or [t1 = false]. In either\n case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].\n\n - If [t1] can step, then so can [t], by rule [ST_If].\n\n - If the final step of the derivation is by [T_Sub], then there is\n a type [S] such that [S <: T] and [empty |- t : S]. The desired\n result is exactly the induction hypothesis for the typing\n subderivation. *)\n\nTheorem progress : forall t T,\n empty |- t \\in T ->\n value t \\/ exists t', t ==> t'.\nProof with eauto.\n intros t T Ht.\n remember empty as Gamma.\n revert HeqGamma.\n induction Ht;\n intros HeqGamma; subst...\n - (* T_Var *)\n inversion H.\n - (* T_App *)\n right.\n destruct IHHt1; subst...\n + (* t1 is a value *)\n destruct IHHt2; subst...\n * (* t2 is a value *)\n destruct (canonical_forms_of_arrow_types empty t1 T1 T2)\n as [x [S1 [t12 Heqt1]]]...\n subst. exists ([x:=t2]t12)...\n * (* t2 steps *)\n inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n + (* t1 steps *)\n inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n - (* T_If *)\n right.\n destruct IHHt1.\n + (* t1 is a value *) eauto.\n + assert (t1 = ttrue \\/ t1 = tfalse)\n by (eapply canonical_forms_of_Bool; eauto).\n inversion H0; subst...\n + inversion H. rename x into t1'. eauto.\n\nQed.\n\n(* ########################################## *)\n(** ** Inversion Lemmas for Typing *)\n\n(** The proof of the preservation theorem also becomes a little more\n complex with the addition of subtyping. The reason is that, as\n with the \"inversion lemmas for subtyping\" above, there are a\n number of facts about the typing relation that are immediate from\n the definition in the pure STLC (formally: that can be obtained\n directly from the [inversion] tactic) but that require real proofs\n in the presence of subtyping because there are multiple ways to\n derive the same [has_type] statement.\n\n The following inversion lemma tells us that, if we have a\n derivation of some typing statement [Gamma |- \\x:S1.t2 : T] whose\n subject is an abstraction, then there must be some subderivation\n giving a type to the body [t2]. *)\n\n(** _Lemma_: If [Gamma |- \\x:S1.t2 : T], then there is a type [S2]\n such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].\n\n (Notice that the lemma does _not_ say, \"then [T] itself is an arrow\n type\" -- this is tempting, but false!)\n\n _Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as\n described. Proceed by induction on the derivation of [Gamma |-\n \\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those\n rules cannot be used to give a type to a syntactic abstraction.\n\n - If the last step of the derivation is a use of [T_Abs] then\n there is a type [T12] such that [T = S1 -> T12] and [Gamma,\n x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we\n need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].\n\n - If the last step of the derivation is a use of [T_Sub] then\n there is a type [S] such that [S <: T] and [Gamma |- \\x:S1.t2 :\n S]. The IH for the typing subderivation tell us that there is\n some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :\n S2]. Picking type [S2] gives us what we need, since [S1 -> S2\n <: T] then follows by [S_Trans]. *)\n\nLemma typing_inversion_abs : forall Gamma x S1 t2 T,\n Gamma |- (tabs x S1 t2) \\in T ->\n (exists S2, (TArrow S1 S2) <: T\n /\\ (update Gamma x S1) |- t2 \\in S2).\nProof with eauto.\n intros Gamma x S1 t2 T H.\n remember (tabs x S1 t2) as t.\n induction H;\n inversion Heqt; subst; intros; try solve by inversion.\n - (* T_Abs *)\n exists T12...\n - (* T_Sub *)\n destruct IHhas_type as [S2 [Hsub Hty]]...\n Qed.\n\n(** Similarly... *)\n\nLemma typing_inversion_var : forall Gamma x T,\n Gamma |- (tvar x) \\in T ->\n exists S,\n Gamma x = Some S /\\ S <: T.\nProof with eauto.\n intros Gamma x T Hty.\n remember (tvar x) as t.\n induction Hty; intros;\n inversion Heqt; subst; try solve by inversion.\n - (* T_Var *)\n exists T...\n - (* T_Sub *)\n destruct IHHty as [U [Hctx HsubU]]... Qed.\n\nLemma typing_inversion_app : forall Gamma t1 t2 T2,\n Gamma |- (tapp t1 t2) \\in T2 ->\n exists T1,\n Gamma |- t1 \\in (TArrow T1 T2) /\\\n Gamma |- t2 \\in T1.\nProof with eauto.\n intros Gamma t1 t2 T2 Hty.\n remember (tapp t1 t2) as t.\n induction Hty; intros;\n inversion Heqt; subst; try solve by inversion.\n - (* T_App *)\n exists T1...\n - (* T_Sub *)\n destruct IHHty as [U1 [Hty1 Hty2]]...\nQed.\n\nLemma typing_inversion_true : forall Gamma T,\n Gamma |- ttrue \\in T ->\n TBool <: T.\nProof with eauto.\n intros Gamma T Htyp. remember ttrue as tu.\n induction Htyp;\n inversion Heqtu; subst; intros...\nQed.\n\nLemma typing_inversion_false : forall Gamma T,\n Gamma |- tfalse \\in T ->\n TBool <: T.\nProof with eauto.\n intros Gamma T Htyp. remember tfalse as tu.\n induction Htyp;\n inversion Heqtu; subst; intros...\nQed.\n\nLemma typing_inversion_if : forall Gamma t1 t2 t3 T,\n Gamma |- (tif t1 t2 t3) \\in T ->\n Gamma |- t1 \\in TBool\n /\\ Gamma |- t2 \\in T\n /\\ Gamma |- t3 \\in T.\nProof with eauto.\n intros Gamma t1 t2 t3 T Hty.\n remember (tif t1 t2 t3) as t.\n induction Hty; intros;\n inversion Heqt; subst; try solve by inversion.\n - (* T_If *)\n auto.\n - (* T_Sub *)\n destruct (IHHty H0) as [H1 [H2 H3]]...\nQed.\n\nLemma typing_inversion_unit : forall Gamma T,\n Gamma |- tunit \\in T ->\n TUnit <: T.\nProof with eauto.\n intros Gamma T Htyp. remember tunit as tu.\n induction Htyp;\n inversion Heqtu; subst; intros...\nQed.\n\n(** The inversion lemmas for typing and for subtyping between arrow\n types can be packaged up as a useful \"combination lemma\" telling\n us exactly what we'll actually require below. *)\n\nLemma abs_arrow : forall x S1 s2 T1 T2,\n empty |- (tabs x S1 s2) \\in (TArrow T1 T2) ->\n T1 <: S1\n /\\ (update empty x S1) |- s2 \\in T2.\nProof with eauto.\n intros x S1 s2 T1 T2 Hty.\n apply typing_inversion_abs in Hty.\n inversion Hty as [S2 [Hsub Hty1]].\n apply sub_inversion_arrow in Hsub.\n inversion Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].\n inversion Heq; subst... Qed.\n\n(* ########################################## *)\n(** ** Context Invariance *)\n\n(** The context invariance lemma follows the same pattern as in the\n pure STLC. *)\n\nInductive appears_free_in : id -> tm -> Prop :=\n | afi_var : forall x,\n appears_free_in x (tvar x)\n | afi_app1 : forall x t1 t2,\n appears_free_in x t1 -> appears_free_in x (tapp t1 t2)\n | afi_app2 : forall x t1 t2,\n appears_free_in x t2 -> appears_free_in x (tapp t1 t2)\n | afi_abs : forall x y T11 t12,\n y <> x ->\n appears_free_in x t12 ->\n appears_free_in x (tabs y T11 t12)\n | afi_if1 : forall x t1 t2 t3,\n appears_free_in x t1 ->\n appears_free_in x (tif t1 t2 t3)\n | afi_if2 : forall x t1 t2 t3,\n appears_free_in x t2 ->\n appears_free_in x (tif t1 t2 t3)\n | afi_if3 : forall x t1 t2 t3,\n appears_free_in x t3 ->\n appears_free_in x (tif t1 t2 t3)\n.\n\nHint Constructors appears_free_in.\n\nLemma context_invariance : forall Gamma Gamma' t S,\n Gamma |- t \\in S ->\n (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n Gamma' |- t \\in S.\nProof with eauto.\n intros. generalize dependent Gamma'.\n induction H;\n intros Gamma' Heqv...\n - (* T_Var *)\n apply T_Var... rewrite <- Heqv...\n - (* T_Abs *)\n apply T_Abs... apply IHhas_type. intros x0 Hafi.\n unfold update, t_update. destruct (beq_idP x x0)...\n - (* T_If *)\n apply T_If...\n\nQed.\n\nLemma free_in_context : forall x t T Gamma,\n appears_free_in x t ->\n Gamma |- t \\in T ->\n exists T', Gamma x = Some T'.\nProof with eauto.\n intros x t T Gamma Hafi Htyp.\n induction Htyp;\n subst; inversion Hafi; subst...\n - (* T_Abs *)\n destruct (IHHtyp H4) as [T Hctx]. exists T.\n unfold update, t_update in Hctx.\n rewrite <- beq_id_false_iff in H2.\n rewrite H2 in Hctx... Qed.\n\n(* ########################################## *)\n(** ** Substitution *)\n\n(** The _substitution lemma_ is proved along the same lines as\n for the pure STLC. The only significant change is that there are\n several places where, instead of the built-in [inversion] tactic,\n we need to use the inversion lemmas that we proved above to\n extract structural information from assumptions about the\n well-typedness of subterms. *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n (update Gamma x U) |- t \\in S ->\n empty |- v \\in U ->\n Gamma |- ([x:=v]t) \\in S.\nProof with eauto.\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n induction t; intros; simpl.\n - (* tvar *)\n rename i into y.\n destruct (typing_inversion_var _ _ _ Htypt)\n as [T [Hctx Hsub]].\n unfold update, t_update in Hctx.\n destruct (beq_idP x y) as [Hxy|Hxy]; eauto;\n subst.\n inversion Hctx; subst. clear Hctx.\n apply context_invariance with empty...\n intros x Hcontra.\n destruct (free_in_context _ _ S empty Hcontra)\n as [T' HT']...\n inversion HT'.\n - (* tapp *)\n destruct (typing_inversion_app _ _ _ _ Htypt)\n as [T1 [Htypt1 Htypt2]].\n eapply T_App...\n - (* tabs *)\n rename i into y. rename t into T1.\n destruct (typing_inversion_abs _ _ _ _ _ Htypt)\n as [T2 [Hsub Htypt2]].\n apply T_Sub with (TArrow T1 T2)... apply T_Abs...\n destruct (beq_idP x y) as [Hxy|Hxy].\n + (* x=y *)\n eapply context_invariance...\n subst.\n intros x Hafi. unfold update, t_update.\n destruct (beq_id y x)...\n + (* x<>y *)\n apply IHt. eapply context_invariance...\n intros z Hafi. unfold update, t_update.\n destruct (beq_idP y z)...\n subst.\n rewrite <- beq_id_false_iff in Hxy. rewrite Hxy...\n - (* ttrue *)\n assert (TBool <: S)\n by apply (typing_inversion_true _ _ Htypt)...\n - (* tfalse *)\n assert (TBool <: S)\n by apply (typing_inversion_false _ _ Htypt)...\n - (* tif *)\n assert ((update Gamma x U) |- t1 \\in TBool\n /\\ (update Gamma x U) |- t2 \\in S\n /\\ (update Gamma x U) |- t3 \\in S)\n by apply (typing_inversion_if _ _ _ _ _ Htypt).\n inversion H as [H1 [H2 H3]].\n apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.\n auto.\n - (* tunit *)\n assert (TUnit <: S)\n by apply (typing_inversion_unit _ _ Htypt)... \nQed.\n\n(* ########################################## *)\n(** ** Preservation *)\n\n(** The proof of preservation now proceeds pretty much as in earlier\n chapters, using the substitution lemma at the appropriate point\n and again using inversion lemmas from above to extract structural\n information from typing assumptions. *)\n\n(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type\n such that [empty |- t : T] and [t ==> t'], then [empty |- t' :\n T].\n\n _Proof_: Let [t] and [T] be given such that [empty |- t : T]. We\n proceed by induction on the structure of this typing derivation,\n leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and\n [T_False] cases are vacuous because abstractions and constants\n don't step. Case [T_Var] is vacuous as well, since the context is\n empty.\n\n - If the final step of the derivation is by [T_App], then there\n are terms [t1] and [t2] and types [T1] and [T2] such that\n [t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and\n [empty |- t2 : T1].\n\n By the definition of the step relation, there are three ways\n [t1 t2] can step. Cases [ST_App1] and [ST_App2] follow\n immediately by the induction hypotheses for the typing\n subderivations and a use of [T_App].\n\n Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =\n \\x:S.t12] for some type [S] and term [t12], and [t' =\n [x:=t2]t12].\n\n By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].\n It then follows by the substitution lemma\n ([substitution_preserves_typing]) that [empty |- [x:=t2]\n t12 : T2] as desired.\n\n - If the final step of the derivation uses rule [T_If], then\n there are terms [t1], [t2], and [t3] such that [t = if t1 then\n t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :\n T] and [empty |- t3 : T]. Moreover, by the induction\n hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].\n There are three cases to consider, depending on which rule was\n used to show [t ==> t'].\n\n - If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2\n else t3] with [t1 ==> t1']. By the induction hypothesis,\n [empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].\n\n - If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then\n either [t' = t2] or [t' = t3], and [empty |- t' : T]\n follows by assumption.\n\n - If the final step of the derivation is by [T_Sub], then there\n is a type [S] such that [S <: T] and [empty |- t : S]. The\n result is immediate by the induction hypothesis for the typing\n subderivation and an application of [T_Sub]. [] *)\n\nTheorem preservation : forall t t' T,\n empty |- t \\in T ->\n t ==> t' ->\n empty |- t' \\in T.\nProof with eauto.\n intros t t' T HT.\n remember empty as Gamma. generalize dependent HeqGamma.\n generalize dependent t'.\n induction HT;\n intros t' HeqGamma HE; subst; inversion HE; subst...\n - (* T_App *)\n inversion HE; subst...\n + (* ST_AppAbs *)\n destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].\n apply substitution_preserves_typing with T... \nQed.\n\n(** ** Records, via Products and Top *)\n\n(** This formalization of the STLC with subtyping omits record\n types for brevity. If we want to deal with them more seriously,\n we have two choices.\n\n First, we can treat them as part of the core language, writing\n down proper syntax, typing, and subtyping rules for them. Chapter\n [RecordSub] shows how this extension works.\n\n On the other hand, if we are treating them as a derived form that\n is desugared in the parser, then we shouldn't need any new rules:\n we should just check that the existing rules for subtyping product\n and [Unit] types give rise to reasonable rules for record\n subtyping via this encoding. To do this, we just need to make one\n small change to the encoding described earlier: instead of using\n [Unit] as the base case in the encoding of tuples and the \"don't\n care\" placeholder in the encoding of records, we use [Top]. So:\n\n {a:Nat, b:Nat} ----> {Nat,Nat} i.e., (Nat,(Nat,Top))\n {c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e., (Nat,(Top,(Nat,Top)))\n\n The encoding of record values doesn't change at all. It is\n easy (and instructive) to check that the subtyping rules above are\n validated by the encoding. *)\n\n(* ###################################################### *)\n(** ** Exercises *)\n\n(** **** Exercise: 2 stars (variations) *)\n(** Each part of this problem suggests a different way of changing the\n definition of the STLC with Unit and subtyping. (These changes\n are not cumulative: each part starts from the original language.)\n In each part, list which properties (Progress, Preservation, both,\n or neither) become false. If a property becomes false, give a\n counterexample.\n\n - Suppose we add the following typing rule:\n\n Gamma |- t : S1->S2 \n S1 <: T1 T1 <: S1 S2 <: T2\n ----------------------------------- (T_Funny1)\n Gamma |- t : T1->T2\n\n\n - Suppose we add the following reduction rule:\n\n -------------------- (ST_Funny21) \n unit ==> (\\x:Top. x)\n\n\n - Suppose we add the following subtyping rule:\n\n ---------------- (S_Funny3) \n Unit <: Top->Top\n\n\n - Suppose we add the following subtyping rule:\n\n ---------------- (S_Funny4) \n Top->Top <: Unit\n\n\n - Suppose we add the following reduction rule:\n\n --------------------- (ST_Funny5) \n (unit t) ==> (t unit)\n\n\n - Suppose we add the same reduction rule _and_ a new typing rule:\n\n --------------------- (ST_Funny5) \n (unit t) ==> (t unit)\n\n ------------------------ (T_Funny6) \n empty |- Unit : Top->Top\n\n\n - Suppose we _change_ the arrow subtyping rule to:\n\n S1 <: T1 S2 <: T2\n ----------------- (S_Arrow') \n S1->S2 <: T1->T2\n\n \n[] *)\n\n(* ###################################################################### *)\n(** * Exercise: Adding Products *)\n\n(** **** Exercise: 4 stars (products) *)\n(** Adding pairs, projections, and product types to the system we have\n defined is a relatively straightforward matter. Carry out this\n extension:\n\n - Add constructors for pairs, first and second projections, and\n product types to the definitions of [ty] and [tm]. (Don't\n forget to add corresponding cases to [T_cases] and [t_cases].)\n\n - Extend the substitution function and value relation as in\n chapter [MoreSTLC].\n\n - Extend the operational semantics with the same reduction rules\n as in chapter [MoreSTLC].\n\n - Extend the subtyping relation with this rule:\n\n S1 <: T1 S2 <: T2\n --------------------- (Sub_Prod)\n S1 * S2 <: T1 * T2\n\n - Extend the typing relation with the same rules for pairs and\n projections as in chapter [MoreSTLC].\n\n - Extend the proofs of progress, preservation, and all their\n supporting lemmas to deal with the new constructs. (You'll also\n need to add some completely new lemmas.)\n[] *)\n\n\n(** $Date: 2016-05-26 17:51:14 -0400 (Thu, 26 May 2016) $ *)\n\n", "meta": {"author": "colinmccabe", "repo": "software-foundations", "sha": "d581e89d47978ed9acc9e2a64ba6209a614fd9f1", "save_path": "github-repos/coq/colinmccabe-software-foundations", "path": "github-repos/coq/colinmccabe-software-foundations/software-foundations-d581e89d47978ed9acc9e2a64ba6209a614fd9f1/Sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12765261370630576, "lm_q1q2_score": 0.06332767397553321}} {"text": "(** * Lecture 4: Tactics in UniMath *)\n(** by Ralph Matthes, CNRS, IRIT, Univ. Toulouse, France *)\n\n(** This is the extended version of a presentation at the\n UniMath school 2019 in Birmingham, meant for self-study\n and for exploring the UniMath library.\n\n The material is based on the extended version of the\n presentation at the UniMath school 2017 in Birmingham,\n but slightly enriched and later updated to fit with the\n changes in UniMath.\n\n Works with UniMath current as of mid-March 2019.\n*)\n\n\n(** Compiles with the command\n[[\ncoqc -type-in-type lecture_tactics_long_version.v\n]]\nwhen placed into the UniMath library or with UniMath\ninstalled into the current Coq. The option is crucial. *)\n\n(** Can be transformed into HTML documentation with the command\n[[\ncoqdoc -utf8 lecture_tactics_long_version.v\n]]\n*)\n\n(** In Coq, one can define concepts by directly giving well-typed\n terms, but one can also be helped in the construction by the\n interactive mode.\n*)\n\nRequire Import UniMath.Foundations.Preamble.\n\n(** ** define a concept interactively: *)\n\nLocate bool. (** a separate definition - [Init.Dataypes.bool] is in the Coq library *)\n\nDefinition myfirsttruthvalue: bool.\n (** only the identifier and its type given, not the definiens *)\n\n (** This opens the interactive mode.\n\n The ##UniMath style guide##\n asks us to start what follows with [Proof.] in a separate line.\n In vanilla Coq, this would be optional (it is anyway a \"nop\"). *)\nProof.\n (** Now we still have to give the term, but we are in interactive mode. *)\n (** If you want to see everything that *involves* booleans, then do *)\n Search bool.\n (** If you only want to find library elements that *yield* booleans, then try *)\n SearchPattern bool.\n (** [true] does not take an argument, and it is already a term we can take as definiens. *)\n exact true.\n (** [exact] is a tactic which takes the term as argument and informs Coq in the proof mode to\n finish the current goal with that term. *)\n\n (** We see in the response buffer: \"No more subgoals.\"\n Hence, there is nothing more to do, except for leaving the proof mode properly. *)\nDefined.\n\n(** [Defined.] instructs Coq to complete the whole interactive construction of a term,\n verify it and to associate it with the given identifer, here [myfirsttruthvalue].\n This may go wrong for different reasons, including implementation errors of the Coq\n system - that will not affect trustworthiness of the library. *)\nSearch bool.\n(** The new definition appears at the beginning of the list. *)\nPrint myfirsttruthvalue.\n(** [myfirsttruthvalue relies on an unsafe universe hierarchy] is output to indicate\n that we are using Coq with option [-type-in-type]. *)\n\n(** *** a more compelling example *)\nDefinition mysecondtruthvalue: bool.\nProof.\n Search bool.\n apply negb.\n (** applies the function [negb] to obtain the required boolean,\n thus the system has to ask for its argument *)\n exact myfirsttruthvalue.\nDefined.\n\nPrint mysecondtruthvalue.\n(**\n[[\nmysecondtruthvalue = negb myfirsttruthvalue\n : bool\n]]\n*)\n\n(** the definition is \"as is\", evaluation can be done subsequently: *)\nEval compute in mysecondtruthvalue.\n(**\n[[\n = false\n : bool\n]]\n*)\n\n(** Again, not much has been gained by the interactive mode. *)\n\n(** Here, we see a copy of the definition from the Coq library: *)\nDefinition andb (b1 b2:bool) : bool := if b1 then b2 else false.\n(** only for illustration purposes - it would be better to define\n it according to UniMath style *)\n\nDefinition mythirdtruthvalue: bool.\nProof.\n Search bool.\n apply andb.\n (** [apply andb.] applies the function [andb] to obtain the required boolean,\n thus the system has to ask for its TWO arguments, one by one. *)\n\n (** This follows the proof pattern of \"backward chaining\" that tries to\n attack goals instead of building up evidence. In the course of action,\n more goals can be generated. The proof effort is over when no more\n goal remains. *)\n\n (** UniMath coding style asks you to use proof structuring syntax,\n while vanilla Coq would allow you to write formally verified\n \"spaghetti code\". *)\n\n (** We tell Coq that we start working on the first subgoal. *)\n -\n (** only the \"focused\" subgoal is now on display *)\n apply andb.\n (** this again spawns two subgoals *)\n\n (** we tell Coq that we start working on the first subgoal *)\n +\n (** normally, one would not leave the \"bullet symbol\" isolated in a line *)\n exact mysecondtruthvalue.\n + exact myfirsttruthvalue.\n (** The response buffer signals:\n[[\nThis subproof is complete, but there are some unfocused goals.\n Focus next goal with bullet -.\n]]\n *)\n - exact true.\nDefined.\n\n(** The usual \"UniMath bullet order\" is -, +, *, --, ++, **, ---, +++, ***,\n and so on (all the ones shown are being used).\n\n Coq does not impose any order, so one can start with, e.g., *****,\n if need be for the sake of experimenting with a proof.\n\n Reuse of bullets even on one branch is possible by enclosing subproofs\n in curly braces {}.\n*)\n\nPrint mythirdtruthvalue.\nEval compute in mythirdtruthvalue.\n\n(** You only saw the tactics [exact] and [apply] at work, and there was no context. *)\n\n(** ** doing Curry-Howard logic *)\n\n(** Interactive mode is more wide-spread when it comes to carrying out proofs\n (the command [Proof.] is reminiscent of that). *)\n\n(** Disclaimer: this section has a logical flavour, but the \"connectives\"\n are not confined to the world of propositional or predicate logic.\n In particular, there is no reference to the sort Prop of Coq.\n Prop is not used at all in UniMath!\n\n On first reading, it is useful to focus on the logical meaning. *)\n\n\nLocate \"->\". (** non-dependent product, can be seen as implication *)\nLocate \"∅\".\nPrint empty. (** an inductive type that has no constructor *)\nLocate \"¬\". (** we need to refer to the UniMath library more explicitly *)\n\nRequire Import UniMath.Foundations.PartA.\n(** Do not write the import statements in the middle of a vernacular file.\n Here, it is done to show the order of appearance, but this is only for\n reasons of pedagogy.\n*)\n\nLocate \"¬\".\nPrint neg.\n(** Negation is not a native concept; it is reduced to implication,\n as is usual in constructive logic. *)\n\nLocate \"×\".\nPrint dirprod. (** non-dependent sum, can be seen as conjunction *)\n\nDefinition combinatorS (A B C: UU): (A × B -> C) × (A -> B) × A -> C.\nProof.\n (** how to infer an implication? *)\n intro Hyp123.\n set (Hyp1 := pr1 Hyp123).\n (** This is already a bit of \"forward chaining\" which is a fact-building process. *)\n set (Hyp23 := pr2 Hyp123).\n cbn in Hyp23.\n (** [cbn] simplifies a goal, and [cbn in H] does this for hypothesis [H];\n note that [simpl] has the same high-level description but should better\n be avoided in new developments. *)\n set (Hyp2 := pr1 Hyp23).\n set (Hyp3 := pr2 Hyp23).\n cbn in Hyp3.\n apply Hyp1.\n apply tpair. (** could be done with [split.] as well *)\n - assumption. (** instruct Coq to look into the current context *)\n\n (** this could be done with [exact Hyp3.] as well *)\n - apply Hyp2.\n assumption.\nDefined.\n\nPrint combinatorS.\nEval compute in combinatorS.\n\nLocal Definition combinatorS_intro_pattern (A B C: UU):\n (A × B -> C) × (A -> B) × A -> C.\nProof.\n intros [Hyp1 [Hyp2 Hyp3]]. (** deconstruct the hypothesis at the time of introduction;\n notice that [×] associates to the right;\n [intros] can also introduce multiple hypotheses, see below *)\n apply Hyp1.\n split.\n - assumption.\n - apply Hyp2.\n assumption.\nDefined.\n\nPrint combinatorS_intro_pattern.\n\n(** the two definitions are even convertible: *)\nEval compute in combinatorS_intro_pattern.\n\nLocal Lemma combinatorS_intro_pattern_is_the_same:\n combinatorS = combinatorS_intro_pattern.\nProof.\n apply idpath.\nDefined.\n\n(** In late 2017, [combinatorS_intro_pattern] would have contained [match] constructs,\n but now, the introduction patterns use less overhead when possible. The UniMath\n style guide still does not want them to be used with square brackets. *)\n\n(** another style to make life easier: *)\nLocal Definition combinatorS_destruct (A B C: UU):\n (A × B -> C) × (A -> B) × A -> C.\nProof.\n intro Hyp123.\n destruct Hyp123 as [Hyp1 Hyp23]. (** deconstruct the hypothesis when needed *)\n apply Hyp1.\n destruct Hyp23 as [Hyp2 Hyp3]. (** deconstruct the hypothesis when needed *)\n split.\n - assumption.\n - apply Hyp2.\n assumption.\nDefined.\n\nPrint combinatorS_destruct.\n\n(** Again, the definition is definitionally equal to the first one: *)\nEval compute in combinatorS_destruct.\n\nLocal Lemma combinatorS_destruct_is_the_same: combinatorS = combinatorS_destruct.\nProof.\n apply idpath.\nDefined.\n\n(** In late 2017, [combinatorS_destruct] would also have contained [match] constructs,\n which is why [destruct] is forbidden in the UniMath style guide. Now, this is fine\n in our example. *)\n\n(** The (hitherto) preferred idiom: *)\nDefinition combinatorS_induction (A B C: UU): (A × B -> C) × (A -> B) × A -> C.\nProof.\n intro Hyp123.\n induction Hyp123 as [Hyp1 Hyp23].\n apply Hyp1.\n induction Hyp23 as [Hyp2 Hyp3].\n split.\n - assumption.\n - apply Hyp2.\n assumption.\nDefined.\n\nPrint combinatorS_induction.\nEval compute in combinatorS_induction.\n\nDefinition combinatorS_curried (A B C: UU): (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n (** use [intro] three times or rather [intros] once; reasonable coding style\n gives names to all hypotheses that are not already present\n in the goal formula, see also the next definition *)\n intros H1 H2 H3.\n apply H1.\n - assumption.\n - set (proofofB := H2 H3).\n (** set up abbreviations that can make use of the current context;\n will be considered as an extra element of the context: *)\n assumption.\nDefined.\n\nPrint combinatorS_curried.\n(** We see that [set] gives rise to [let]-expressions that are known\n from functional programming languages, in other words: the use of\n [set] is not a \"macro\" facility to ease typing. *)\n\n(** [let]-bindings disappear when computing the normal form of a term: *)\nEval compute in combinatorS_curried.\n\n(** [set] can only be used if the term of the desired type is provided,\n but we can also work interactively as follows: *)\nDefinition combinatorS_curried_with_assert (A B C: UU):\n (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n intros H1 H2 H3.\n (** we can momentarily forget about our goal and build up knowledge: *)\n assert (proofofB : B).\n (** the current goal [C] becomes the second sub-goal, and the new current goal is [B] *)\n\n (** It is not wise to handle this situation by \"bullets\" since many assertions\n can appear in a linearly thought argument. It would pretend a tree structure\n although it would rather be a comb. The proof of the assertion should\n be packaged by enclosing it in curly braces like so: *)\n { apply H2.\n assumption.\n }\n (** Now, [proofofB] is in the context with type [B]. *)\n apply H1.\n - assumption.\n - assumption.\nDefined.\n\n(** the wildcard [?] for [intros] *)\nDefinition combinatorS_curried_variant (A B C: UU):\n (A -> B -> C) -> (A -> B) -> forall H7:A, C.\nProof.\n intros H1 H2 ?.\n(** a question mark instructs Coq to use the corresponding identifier\n from the goal formula *)\n exact (H1 H7 (H2 H7)).\nDefined.\n(** the wildcard [_] for [intros] forgets the respective hypothesis *)\n\nLocate \"⨿\". (** this symbol is harder to type in with Agda input\n mode: use backslash union and then choose the right symbol with\n arrow down key: the symbol might only appear in the menu to\n choose from after having hit the arrow down key! *)\nPrint coprod. (** defined in UniMath preamble as inductive type,\n can be seen as disjunction *)\n\nLocate \"∏\".\n(** company-coq shows the result with universal quantifiers,\n but that is only the \"prettified\" version of \"forall\" which\n is a basic syntactic element of the language of Coq. *)\n\nLocate \"=\". (** the identity type of UniMath *)\nPrint paths.\n\n(** A word of warning for those who read \"Coq in a Hurry\": [SearchRewrite]\n does not find equations w.r.t. this notion, only w.r.t. Coq's built-in\n propositional equality. *)\nSearchPattern (paths _ _).\n(** Among the search results is [maponpathsinv0] that has [idpath] in its conclusion. *)\nSearchRewrite idpath.\n(** No result! *)\n\n(** *** How to decompose formulas *)\n\n(** In \"Coq in a Hurry\", Yves Bertot gives recipes for decomposing the usual logical\n connectives. Crucially, one has to distinguish between decomposition of the goal\n or decomposition of a hypothesis in the context.\n\n Here, we do it alike.\n*)\n\n(** **** Decomposition of goal formulas:\n\n A1,...,An -> B: tactic [intro] or [intros]\n\n [¬ A]: idem (negation is defined through implication)\n\n Π-type: idem (implication is a special case of product)\n\n [×]: [apply dirprodpair], less specifically [apply tpair] or [split]\n\n Σ-type: [use tpair] or [exists] or [split with], see explanations below\n\n [A ⨿ B]: [apply ii1] or [apply ii2], but this constitutes a choice\n of which way to go\n\n [A = B]: [apply idpath], however this only works when the expressions\n are convertible\n\n [nat]: [exact 1000], for example (a logical reading is not\n useful for this type); beware that UniMath knows only 27 numerals,\n [Goal nat. Fail exact 2019.] leads to\n[[\nThe command has indeed failed with message: No interpretation for numeral 2019.\n]]\n*)\n\n(** **** Decomposition of formula of hypothesis [H]:\n\n [∅]: [induction H]\n\n This terminates a goal. (It corresponds to ex falso quodlibet.)\n\n There is naturally no recipe for getting rid of [∅] in the conclusion.\n But [apply fromempty] allows to replace any goal by [∅].\n\n A1,...,An -> B: [apply H], but the formula has to fit with the goal\n\n\n [×]: [induction H as [H1 H2]]\n\n As seen above, this introduces names of hypotheses for the two components.\n\n Σ-type: idem, but rather more asymmetric as [induction H as [x H']]\n\n [A ⨿ B]: [induction H as [H1 | H2]]\n\n This introduces names for the hypotheses in the two branches.\n\n [A = B]: [induction H]\n\n The supposedly equal [A] and [B] become the same [A] in the goal.\n\n This is the least intuitive rule for the non-expert in type theory.\n\n [nat]: [induction n as [ | n IH]]\n\n Here, we assume that the hypothesis has the name [n] which\n is more idiomatic than [H], and there is no extra name in\n the base case, while in the step case, the preceding number\n is now given the name [n] and the induction hypothesis is\n named [IH].\n*)\n\n(** ** Handling unfinished proofs *)\n\n(** In the middle of a proof effort - not in the UniMath library - you can use\n [admit] to abandon the current goal. *)\nLocal Lemma badex1 (A: UU): ∅ × (A -> A).\nProof.\n split.\n - (** seems difficult in the current context *)\n admit.\n\n (** we continue with decent proof work: *)\n - intro H.\n assumption.\nAdmitted.\n\n(** This is strictly forbidden to commit to UniMath! [admit] allows to pursue the other goals,\n while [Admitted.] makes the lemma available for further proofs. A warning is shown that\n [badex1] has been assumed as axiom. *)\n\n(** An alternative to interrupt work on a proof: *)\nLemma badex2 (A: UU): ∅ × (A -> A).\nProof.\n split.\n -\nAbort.\n(** [badex2] is not in the symbol table. *)\n\n(** [Abort.] is a way of documenting a problem with proving a result.\n At least, Coq can check the partial proof up to the [Abort.] command. *)\n\n(** ** Working with holes in proofs *)\n\n(** Our previous proofs were particularly clear because the goal formulas\n and all hypotheses were fully given by the system.\n*)\n\nPrint pathscomp0.\n(** This is the UniMath proof of transitivity of equality. *)\n\n(** The salient feature of transitivity is that the intermediate\n expression cannot be deduced from the equation to be proven. *)\nLemma badex3 (A B C D: UU) : ((A × B) × (C × D)) = (A × (B × C) × D).\n(** Notice that the outermost parentheses are needed here. *)\nProof.\n Fail apply pathscomp0.\n(**\n[[\nThe command has indeed failed with message:\nCannot infer the implicit parameter b of pathscomp0 whose type is\n\"Type\" in environment:\nA, B, C, D : UU\n]]\n(When using the standard setup of UniMath with ProofGeneral,\nthis message appears only when starting emacs at the root of the\nUniMath library.)\n\n[Fail] announces failure and therefore allows to continue with\nthe interpretation of the vernacular file.\n\nWe need to help Coq with the argument [b] to [pathscomp0].\n*)\n apply (pathscomp0 (b := A × (B × (C × D)))).\n - (** is this not just associativity with third argument [C × D]? *)\n SearchPattern(_ × _).\n (** No hope at all - we can only hope for weak equivalence. *)\nAbort.\n\nSearchPattern(_ ≃ _).\nPrint weqcomp.\nPrint weqdirprodasstor.\nPrint weqdirprodasstol.\nPrint weqdirprodf.\nPrint idweq.\n\nLemma assocex (A B C D: UU) : ((A × B) × (C × D)) ≃ (A × (B × C) × D).\nProof.\n Fail apply weqcomp.\n eapply weqcomp.\n(** [eapply] generates \"existential variables\" for the expressions\n it cannot infer from applying a lemma.\n\n The further proof will narrow on those variables and finally\n make them disappear - otherwise, the proof is not considered\n completed.\n *)\n - (** We recall that on this side, only associativity was missing. *)\n apply weqdirprodasstor.\n - (** The subgoal is now fully given. *)\n\n (** The missing link is associativity, but only on the\n right-hand side of the top [×] symbol. *)\n apply weqdirprodf.\n + apply idweq.\n + apply weqdirprodasstol.\nDefined.\n\n(** Warning: tactic [exact] does not work if there are existential\n variables in the goal, but [eexact] can then be tried. *)\n\nLemma sumex (A: UU) (P Q: A -> UU):\n (∑ x:A, P x × Q x) -> (∑ x:A, P x) × ∑ x:A, Q x.\nProof.\n (** decompose the implication: *)\n intro H.\n (** decompose the Σ-type: *)\n induction H as [x H'].\n (** decompose the pair: *)\n induction H' as [H1 H2].\n (** decompose the pair in the goal *)\n split.\n - Fail split.\n (**\n[[\nThe command has indeed failed with message:\n Unable to find an instance for the variable pr1.\n]]\n *)\n Fail (apply tpair).\n (** A simple way out, by providing the first component: *)\n split with x. (** [exists x] does the same *)\n assumption.\n - (** or use [eapply] and create an existential variable: *)\n eapply tpair.\n Fail assumption. (** the assumption [H2] does not agree with the goal *)\n eexact H2.\nDefined.\n(** Notice that [eapply tpair] is not used in the UniMath library,\n since [use tpair] normally comes in handier, see below. *)\n\n(** *** Warning on existential variables *)\n(** It may happen that the process of instantiating existential variables\n is not completed when all goals have been treated.\n *)\n\n(** an example adapted from one by Arnaud Spiwack, ~2007 *)\n\nAbout unit. (** from the UniMath preamble *)\n\nLocal Definition P (x:nat) := unit.\n\nLemma uninstex: unit.\nProof.\n refine ((fun x:P _ => _) _).\n (** [refine] is like [exact], but one can leave holes with the wildcard \"_\".\n This tactic should hardly be needed since most uses in UniMath\n can be replaced by a use of the \"tactic\" [use], see further down\n on this tactic notation for an Ltac definition.\n\n Still, [refine] can come to rescue in difficult situations,\n in particular during proof development. Its simpler variant\n [simple refine] is captured by the [use] \"tactic\".\n*)\n - exact tt.\n - exact tt.\n (** Now, Coq presents a subgoal that pops up from the \"shelved goals\".\n\n Still, no more \"-\" bullets can be used.\n\n[[ -\nError: Wrong bullet - : No more subgoals.\n]]\n *)\n\nShow Existentials.\n(** a natural number is still being asked for *)\nUnshelve.\n(** Like this, we can focus on the remaining goal. *)\nexact 0.\nDefined.\n\n(** one can also name the existential variables in [refine]: *)\nLemma uninstexnamed: unit.\n Proof.\n refine ((fun x:P ?[n] => _) _). (** give a name to the existential variable *)\n - exact tt.\n - exact tt.\nShow Existentials.\nUnshelve.\ninstantiate (n := 0). (** more symbols to type but better to grasp *)\nDefined.\n\n(** ** a bit more on equational reasoning *)\n\nSection homot.\n(** A section allows to introduce local variables/parameters\n that will be bound outside of the section. *)\n\nLocate \"~\".\n(** printing ~ #~# *)\n\nPrint homot. (** this is just pointwise equality *)\nPrint idfun. (** the identity function *)\nLocate \"∘\".\nPrint funcomp.\n(** plain function composition in diagrammatic order, i.e.,\n first the first argument, then the second argument;\n the second argument may even have a dependent type *)\n\nVariables A B: UU.\n(* makes good sense in a section *)\n\nDefinition interestingstatement : UU :=\n ∏ (v w : A → B) (v' w' : B → A),\n w ∘ w' ~ idfun B → v' ∘ v ~ idfun A → v' ~ w' → v ~ w.\n\nCheck (isinjinvmap': interestingstatement).\n\nLemma ourisinjinvmap': interestingstatement.\nProof.\n intros. (** is a nop since the formula structure is not analyzed *)\n unfold interestingstatement. (** [unfold] unfolds a definition *)\n intros ? ? ? ? homoth1 homoth2 hyp a.\n (** the extra element [a] triggers Coq to unfold the formula further;\n [unfold interestingstatement] was there only for illustration! *)\n\n (** we want to use transitivity that is expressed by [pathscomp0] and\n instruct Coq to take a specific intermediate term *)\nSet Printing All.\nPrint Ltac intermediate_path.\n(** reveals that there is an abbreviation for the tactic call we have in mind *)\nUnset Printing All.\n intermediate_path (w (w' (v a))).\n - apply pathsinv0. (** apply symmetry of equality *)\n unfold homot in homoth1.\n unfold funcomp in homoth1.\n unfold idfun in homoth1.\n apply homoth1. (** all the [unfold] were only for illustration! *)\n -\n Print maponpaths.\n apply maponpaths.\n unfold homot in hyp.\n (** we use the equation in [hyp] from right to left, i.e., backwards: *)\n rewrite <- hyp.\n (** remark: for a forward rewrite, use [rewrite] without directional\n argument *)\n (** beautify the current goal: *)\n change ((v' ∘ v) a = idfun A a).\n (** just for illustration of [change] that allows to replace the goal\n by a convertible expression; also works for hypotheses, e.g.: *)\n change (v' ~ w') in hyp.\n (** since [hyp] was no longer necessary, we should rather have deleted it: *)\n clear hyp.\n apply homoth2.\nDefined.\n\nVariables v w: A -> B.\nVariables v' w': B → A.\n\nEval compute in (ourisinjinvmap' v w v' w').\n\nOpaque ourisinjinvmap'.\nEval compute in (ourisinjinvmap' v w v' w').\n(** [Opaque] made the definition opaque in the sense that the identifier\n is still in the symbol table, together with its type, but that it does\n not evaluate to anything but itself.\n\n If inhabitants of a type are irrelevant (for example if it is known\n that there is at most one inhabitant, and if one therefore is not interested\n in computing with that inhabitant), then opaqueness is an asset to make\n the subsequent proof process lighter.\n\n [Opaque] can be undone with [Transparent]:\n *)\nTransparent ourisinjinvmap'.\nEval compute in (ourisinjinvmap' v w v' w').\n\n(** If one uses [Compute] in place of [Eval compute in], then [Opaque] has no effect. *)\n\n(** Full and irreversible opaqueness is obtained for a construction\n in interactive mode by completing it with [Qed.] in place of [Defined.]\n\n Using [Qed.] is discouraged by the UniMath style guide. In Coq,\n most lemmas, theorems, etc. (nearly every assertion in [Prop]) are\n made opaque in this way. In UniMath, many lemmas enter subsequent\n computation, and one should have good reasons for not closing an\n interactive construction with [Defined.]\n*)\n\nEnd homot.\nCheck ourisinjinvmap'.\n(** The section variables [A] and [B] are abstracted away after the end\n of the section - only the relevant ones. *)\n\n(** [assert] is a \"chameleon\" w.r.t. to opaqueness: *)\nDefinition combinatorS_curried_with_assert2 (A B C: UU):\n (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n intros H1 H2 H3.\n assert (proofofB : B).\n { apply H2.\n assumption.\n }\n (** [proofofB] is just an identifier and not associated to the\n construction we gave. Hence, the proof is opaque for us. *)\n apply H1.\n - assumption.\n - assumption.\nDefined.\nPrint combinatorS_curried_with_assert2.\n(** We see that [proofofB] is there with its definition, so it is\n transparent.\n\n See much further below for [transparent assert] that is like\n [assert], but consistently transparent.\n*)\n\n(** ** composing tactics *)\n\n(** Up to now, we \"composed\" tactics in two ways: we gave them sequentially,\n separated by periods, or we introduced a tree structure through the\n \"bullet\" notation. We did not think of these operations as composition\n of tactics, in particular since we had to trigger each of them separately\n in interactive mode. However, we can also explicitly compose them, like so:\n *)\nDefinition combinatorS_induction_in_one_step (A B C: UU):\n (A × B -> C) × (A -> B) × A -> C.\nProof.\n intro Hyp123;\n induction Hyp123 as [Hyp1 Hyp23];\n apply Hyp1;\n induction Hyp23 as [Hyp2 Hyp3];\n split;\n [ assumption\n | apply Hyp2;\n assumption].\nDefined.\n\n(** The sequential composition is written by (infix) semicolon, and the two branches\n created by [split] are treated in the |-separated list of arguments to the brackets. *)\n\n(** Why would we want to do such compositions? There are at least four good reasons:\n\n (1) We indicate that the intermediate results are irrelevant for someone who\n executes the script so as to understand how and why the construction /\n the proof works.\n\n (2) The same tactic (expression) can uniformly treat all sub-goals stemming\n from the preceding tactic application, as will be shown next.\n *)\nDefinition combinatorS_curried_with_assert_in_one_step (A B C: UU):\n (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n intros H1 H2 H3;\n assert (proofofB : B) by\n ( apply H2;\n assumption\n );\n apply H1;\n assumption.\nDefined.\n\n(** This illustrates the grouping of tactic expressions by parentheses, the variant\n [assert by] of [assert] used when only one tactic expression forms the proof of\n the assertion, and also point (2): the last line is simpler than the expected line\n[[\n[assumption | assumption].\n]]\n*)\n\n(** Why would we want to do such compositions (cont'd)?\n\n (3) We want to capture recurring patterns of construction / proof by tactics into\n reusable Ltac definitions, see below.\n\n (4) We want to make use of the [abstract] facility, explained now.\n *)\n\nDefinition combinatorS_induction_with_abstract (A B C: UU):\n (A × B -> C) × (A -> B) × A -> C.\nProof.\n intro Hyp123;\n induction Hyp123 as [Hyp1 Hyp23];\n apply Hyp1;\n induction Hyp23 as [Hyp2 Hyp3].\n (** Now imagine that the following proof was very complicated but had no computational\n relevance, i.e., could also be packed into a lemma whose proof would be finished\n by [Qed]. We can encapsulate it into [abstract]: *)\n abstract (split;\n [ assumption\n | apply Hyp2;\n assumption]).\nDefined.\n\nPrint combinatorS_induction_with_abstract.\n(** The term features an occurrence of [combinatorS_induction_with_abstract_subproof]\n that contains the abstracted part; using the latter name is forbidden by the\n UniMath style guide. Note that [abstract] is used hundreds of times in the\n UniMath library. *)\n\n(** *** Ltac language for defining tactics *)\n\n(** Disclaimer: Ltac can do more than that, in fact Ltac is the name of the\n whole tactic language of Coq. *)\n\n(** Ltac definitions can associate identifiers for tactics with tactic expressions.\n\n We have already used one such identifier: [intermediate_path] in the [Foundations]\n package of UniMath. In file [PartA.v], we have the code\n[[\nLtac intermediate_path x := apply (pathscomp0 (b := x)).\n]]\n*)\nPrint Ltac intermediate_path.\n(** does not show the formal argument [x] in the right-hand side. Remedy: *)\nSet Printing All.\nPrint Ltac intermediate_path.\nUnset Printing All.\n(** The problem with these Ltac definitions is that they are barely typed, they\n behave rather like LaTeX macros. *)\nLocal Ltac intermediate_path_wrong x := apply (pathscomp0 (X := x)(b := x)).\n(** This definition confounds the type argument [X] and its element [b].\n The soundness of Coq is not at stake here, but the errors only appear\n at runtime, as we will see below. Normal printing output hides the difference\n with the correct tactic definition: *)\nPrint Ltac intermediate_path_wrong.\n\nSection homot2.\nVariables A B: UU.\nLemma ourisinjinvmap'_failed_proof: interestingstatement A B.\n Proof.\n intros ? ? ? ? homoth1 homoth2 hyp a.\n Fail intermediate_path_wrong (w (w' (v a))).\n (** The message does not point to the problem that argument [x] appears\n a second time in the Ltac definition with a different needed type. *)\nAbort.\nEnd homot2.\n(** See ##[https://github.com/UniMath/UniMath/blob/master/UniMath/PAdics/frac.v#L23]##\n for a huge Ltac definition in the UniMath library to appreciate the lack\n of type information. *)\n\n(** The UniMath library provides some Ltac definitions for general use: *)\nPrint Ltac etrans. (** no need to explain - rather an abbreviation *)\nSet Printing All.\nPrint Ltac intermediate_weq. (** analogous to [intermediate_path] *)\nUnset Printing All.\n\n(** for the next tactic *)\nRequire Import UniMath.MoreFoundations.Tactics.\n\nSet Printing All.\nPrint Ltac show_id_type.\n(**\n[[\nLtac show_id_type :=\n match goal with\n | |- @paths ?ID _ _ => set (TYPE := ID); simpl in TYPE\n end\n]]\nHardly ever present in proofs in the library, but it can be an excellent tool\nwhile trying to prove an equation: it puts the index of the path space\ninto the context. This index is invisible in the notation with an equals\nsign that one normally sees as the goal, and coercions can easily give a wrong\nimpression about that index. *)\nUnset Printing All.\n\n(** **** The most useful Ltac definition of UniMath *)\nPrint Ltac simple_rapply.\n(** It applies the [simple refine] tactic with zero up to fifteen unknown\n arguments. *)\n\n(** This tactic must not be used in UniMath since a \"tactic notation\"\n is favoured: [Foundations/Preamble.v] contains the definition\n[[\nTactic Notation \"use\" uconstr(p) := simple_rapply p.\n]]\n\nUse of [use]:\n*)\nLemma sumex_with_use (A: UU) (P Q: A -> UU):\n (∑ x:A, P x × Q x) -> (∑ x:A, P x) × ∑ x:A, Q x.\nProof.\n intro H; induction H as [x H']; induction H' as [H1 H2].\n split.\n - use tpair.\n + assumption.\n + cbn. (** this is often necessary since [use] does as little as possible *)\n assumption.\n - (** to remind the version where the \"witness\" is given explicitly: *)\n exists x; assumption.\nDefined.\n(** To conclude: [use tpair] is the right idiom for an interactive\n construction of inhabitants of Σ-types. Note that the second\n generated sub-goal may need [cbn] to make further tactics\n applicable.\n\n If the first component of the inhabitant is already at hand,\n then the \"exists\" tactic yields a leaner proof script.\n\n [use] is not confined to Σ-types. Whenever one would be\n inclined to start trying to apply a lemma [H] with a varying\n number of underscores, [use H] may be a better option.\n*)\n\n(** There is another recommendable tactic notation that is also by\n Jason Gross:\n[[\nTactic Notation \"transparent\" \"assert\"\n \"(\" ident(name) \":\" constr(type) \")\" :=\n simple refine (let name := (_ : type) in _).\n]]\n*)\nDefinition combinatorS_curried_with_transparent_assert (A B C: UU):\n (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n intros H1 H2 H3.\n transparent assert (proofofB : B).\n { apply H2; assumption. } (** There is no [transparent assert by]. *)\n\n (** Now, [proofB] is present with the constructed proof of [B]. *)\nAbort.\n(** To conclude: [transparent assert] is a replacement for [assert]\n if the construction of the assertion is needed in the rest of\n the proof.\n*)\n\n(** ** a final word, just on searching the library *)\n\n(** [SearchPattern] searches for the given pattern in what the library\n gives as *conclusions* of definitions, lemmas, etc., and the current\n hypotheses.\n\n [Search] searches in the (full) types of all the library elements (and\n the current hypotheses). It may provide too many irrelevant result\n for your question. At least, it will also show all the relevant ones.\n*)\n\n(** ** List of tactics that were mentioned *)\n(**\n[[\nexact\napply\nintro\nset\ncbn / cbn in (old form: simpl / simpl in)\nassumption\nintros (with pattern, with wild cards)\nsplit / split with / exists\ndestruct as --- not desirable in UniMath\ninduction / induction as\nadmit --- only during proof development\neapply\neexact\nrefine --- first consider \"use\" instead\ninstantiate\nunfold / unfold in\nintermediate_path (Ltac def.)\nrewrite / rewrite <-\nchange / change in\nclear\nassert {} / assert by\nabstract\netrans (Ltac def.)\nintermediate_weq (Ltac def.)\nshow_id_type (Ltac def.)\nsimple_rapply (Ltac def., not to be used)\nuse (Ltac notation)\ntransparent assert (Ltac notation)\n]]\n*)\n\n(* End of file *)\n", "meta": {"author": "UniMath", "repo": "Schools", "sha": "ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b", "save_path": "github-repos/coq/UniMath-Schools", "path": "github-repos/coq/UniMath-Schools/Schools-ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b/2019-04-Birmingham/Part4_Tactics_UniMath/lecture_tactics_long_version.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.12940273998528942, "lm_q1q2_score": 0.06318520924060118}} {"text": "(** * Extraction: Extracting ML from Coq *)\n\n(* ################################################################# *)\n(** * Basic Extraction *)\n\n(** In its simplest form, extracting an efficient program from one\n written in Coq is completely straightforward. \n\n First we say what language we want to extract into. Options are\n OCaml (the most mature), Haskell (which mostly works), and\n Scheme (a bit out of date). *)\n\nExtraction Language Ocaml.\n\n(** Now we load up the Coq environment with some definitions, either\n directly or by importing them from other modules. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import ImpCEvalFun.\n\n(** Finally, we tell Coq the name of a definition to extract and the\n name of a file to put the extracted code into. *)\n\nExtraction \"imp1.ml\" ceval_step.\n\n(** When Coq processes this command, it generates a file [imp1.ml]\n containing an extracted version of [ceval_step], together with\n everything that it recursively depends on. Compile the present\n [.v] file and have a look at [imp1.ml] now. *)\n\n(* ################################################################# *)\n(** * Controlling Extraction of Specific Types *)\n\n(** We can tell Coq to extract certain [Inductive] definitions to\n specific OCaml types. For each one, we must say\n - how the Coq type itself should be represented in OCaml, and\n - how each constructor should be translated. *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\n\n(** Also, for non-enumeration types (where the constructors take\n arguments), we give an OCaml expression that can be used as a\n \"recursor\" over elements of the type. (Think Church numerals.) *)\n\nExtract Inductive nat => \"int\"\n [ \"0\" \"(fun x -> x + 1)\" ]\n \"(fun zero succ n ->\n if n=0 then zero () else succ (n-1))\".\n\n(** We can also extract defined constants to specific OCaml terms or\n operators. *)\n\nExtract Constant plus => \"( + )\".\nExtract Constant mult => \"( * )\".\nExtract Constant beq_nat => \"( = )\".\n\n(** Important: It is entirely _your responsibility_ to make sure that\n the translations you're proving make sense. For example, it might\n be tempting to include this one\n\n Extract Constant minus => \"( - )\".\n\n but doing so could lead to serious confusion! (Why?)\n*)\n\nExtraction \"imp2.ml\" ceval_step.\n\n(** Have a look at the file [imp2.ml]. Notice how the fundamental\n definitions have changed from [imp1.ml]. *)\n\n(* ################################################################# *)\n(** * A Complete Example *)\n\n(** To use our extracted evaluator to run Imp programs, all we need to\n add is a tiny driver program that calls the evaluator and prints\n out the result.\n\n For simplicity, we'll print results by dumping out the first four\n memory locations in the final state.\n\n Also, to make it easier to type in examples, let's extract a\n parser from the [ImpParser] Coq module. To do this, we need a few\n magic declarations to set up the right correspondence between Coq\n strings and lists of OCaml characters. *)\n\nRequire Import Ascii String.\nExtract Inductive ascii => char\n[\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))\"\n]\n\"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))\".\nExtract Constant zero => \"'\\000'\".\nExtract Constant one => \"'\\001'\".\nExtract Constant shift =>\n \"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)\".\nExtract Inlined Constant ascii_dec => \"(=)\".\n\n(** We also need one more variant of booleans. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\n\n(** The extraction is the same as always. *)\n\nRequire Import Imp.\nRequire Import ImpParser.\nExtraction \"imp.ml\" empty_state ceval_step parse.\n\n(** Now let's run our generated Imp evaluator. First, have a look at\n [impdriver.ml]. (This was written by hand, not extracted.)\n\n Next, compile the driver together with the extracted code and\n execute it, as follows.\n\n ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml\n ./impdriver\n\n (The [-w] flags to [ocamlc] are just there to suppress a few\n spurious warnings.) *)\n\n(* ################################################################# *)\n(** * Discussion *)\n\n(** Since we've proved that the [ceval_step] function behaves the same\n as the [ceval] relation in an appropriate sense, the extracted\n program can be viewed as a _certified_ Imp interpreter. Of\n course, the parser we're using is not certified, since we didn't\n prove anything about it! *)\n\n(** $Date: 2016-07-13 12:41:41 -0400 (Wed, 13 Jul 2016) $ *)\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.1347759261111811, "lm_q1q2_score": 0.06265753783397018}} {"text": "(**************************************************************************\n* Useful General-Purpose Tactics for Coq *\n* Arthur Chargu\\u00e9raud *\n* Distributed under the terms of the LGPL-v3 license *\n***************************************************************************)\n\n\n(** This file contains a set of tactics that extends the set of builtin\n tactics provided with the standard distribution of Coq. It intends\n to overcome a number of limitations of the standard set of tactics,\n and thereby to help user to write shorter and more robust scripts. \n \n Hopefully, Coq tactics will be improved as time goes by, and this \n file should ultimately be useless. In the meanwhile, you will \n probably find it very useful. \n*)\n\n(** The main features offered are:\n - More convenient syntax for naming hypotheses, with tactics for\n introduction and inversion that take as input only the name of\n hypotheses of type [Prop], rather than the name of all variables. \n - Tactics providing true support for manipulating N-ary conjunctions, \n disjunctions and existentials, hidding the fact that the underlying \n implementation is based on binary predicates.\n - Convenient support for automation: tactic followed with the symbol\n \"~\" or \"*\" will call automation on the generated subgoals. \n Symbol \"~\" stands for [auto] and \"*\" for [intuition eauto].\n These bindings can be customized.\n - Forward-chaining tactics are provided to instantiate lemmas\n either with variable or hypotheses or a mix of both.\n - A more powerful implementation of [apply] is provided (it is based\n on [refine] and thus behaves better with respect to conversion).\n - An improved inversion tactic which substitutes equalities on variables\n generated by the standard inversion mecanism. Moreover, it supports\n the elimination of dependently-typed equalities (requires axiom [K],\n which is a weak form of Proof Irrelevance).\n - An improved induction tactic that saves the relevant information\n by introducing equalities before doing the induction and \n substitutes these equality in each subgoal generated by [induction].\n - Tactics for saving time when writing proofs, with tactics to\n asserts hypotheses or sub-goals, and improved tactics for\n clearing, renaming, and sorting hypotheses.\n*)\n\n(** External credits:\n - thanks to Xavier Leroy for providing with the idea of tactic [forward],\n - thanks to Georges Gonthier for the implementation trick in [applys],\n - thanks to Hugo Herbelin for useful feedback on several tactics.\n*)\n\nSet Implicit Arguments.\n\n(* ********************************************************************** *)\n(** * Additional notations for Coq *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** N-ary Existentials *)\n\n(** [exists T1 ... TN, P] is a shorthand for \n [exists T1, ..., exists TN, P]. Note that\n [Coq.Program.Syntax] already defines exists\n for arity up to 4. *)\n\nNotation \"'exists' x1 ',' P\" :=\n (exists x1, P)\n (at level 200, x1 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 ',' P\" :=\n (exists x1, exists x2, P)\n (at level 200, x1 ident, x2 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 ',' P\" :=\n (exists x1, exists x2, exists x3, P)\n (at level 200, x1 ident, x2 ident, x3 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, \n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 x6 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, exists x6, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n x6 ident,\n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 x6 x7 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, exists x6, \n exists x7, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n x6 ident, x7 ident,\n right associativity) : type_scope. \nNotation \"'exists' x1 x2 x3 x4 x5 x6 x7 x8 ',' P\" :=\n (exists x1, exists x2, exists x3, exists x4, exists x5, exists x6, \n exists x7, exists x8, P)\n (at level 200, x1 ident, x2 ident, x3 ident, x4 ident, x5 ident,\n x6 ident, x7 ident, x8 ident,\n right associativity) : type_scope. \n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Partial application of equality *)\n\n(** [= x] is a unary predicate which holds of values equal to [x].\n It simply denotes the partial application of equality. *)\n\nNotation \"'=' x\" := (fun y => y = x) (at level 71).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Notation for projections *)\n\nNotation \"'proj21' P\" := (proj1 P) (at level 69, only parsing).\nNotation \"'proj22' P\" := (proj2 P) (at level 69, only parsing).\n\nNotation \"'proj31' P\" := (proj1 P) (at level 69).\nNotation \"'proj32' P\" := (proj1 (proj2 P)) (at level 69).\nNotation \"'proj33' P\" := (proj2 (proj2 P)) (at level 69).\n\nNotation \"'proj41' P\" := (proj1 P) (at level 69).\nNotation \"'proj42' P\" := (proj1 (proj2 P)) (at level 69).\nNotation \"'proj43' P\" := (proj1 (proj2 (proj2 P))) (at level 69).\nNotation \"'proj44' P\" := (proj2 (proj2 (proj2 P))) (at level 69).\n\nNotation \"'proj51' P\" := (proj1 P) (at level 69).\nNotation \"'proj52' P\" := (proj1 (proj2 P)) (at level 69).\nNotation \"'proj53' P\" := (proj1 (proj2 (proj2 P))) (at level 69).\nNotation \"'proj54' P\" := (proj1 (proj2 (proj2 (proj2 P)))) (at level 69).\nNotation \"'proj55' P\" := (proj2 (proj2 (proj2 (proj2 P)))) (at level 69).\n\n\n\n(* ********************************************************************** *)\n(** * Tools for programming with Ltac *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Programming tactics *)\n\n(** [ltac_no_arg] is a constant that can be used to simulate \n optional arguments in tactic definitions. \n Use [mytactic ltac_no_arg] on the tactic invokation,\n and use [match arg with ltac_no_arg => ..] or\n [match type of arg with ltac_No_arg => ..] to\n test whether an argument was provided. *)\n\nInductive ltac_No_arg : Set := \n | ltac_no_arg : ltac_No_arg.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Returning values *)\n\n(** Ltac tactics are not allowed to both perform side-effect on the goal\n and return a value in the same time. To work around this limitation,\n we can use either the current goal or the proof context as a stack \n to place return values. To avoid interferences, we box the return\n values.\n\n When the goal is used as stack, we use [ltac_tag_result] to box values.\n When the context is used, we use the type [Carrier] to box values. *) \n\nDefinition ltac_tag_result (A:Type) (x:A) := x.\n\n(** [build_result E] changes the goal from [G] to \n [ltac_tag_result T -> G] where [T] is the type of [E]. *)\n\nLtac build_result t :=\n match type of t with ?T =>\n let H := fresh \"TEMP\" in\n assert (H : ltac_tag_result T); \n [ unfold ltac_tag_result; exact t | generalize H; clear H ]\n end.\n\n(** [if_is_result] is the identity on a goal of the form [ltac_tag_result T -> G] \n and fails otherwise. *)\n\nLtac if_is_result :=\n match goal with |- ltac_tag_result _ -> _ => idtac end.\n\n(** [name_result H] expects a of the form [ltac_tag_result T -> G] \n and changes the goal to [G] by introducing an hypothesis [H:T]. *)\n\nTactic Notation \"name_result\" simple_intropattern(H) :=\n match goal with |- ltac_tag_result _ -> _ =>\n unfold ltac_tag_result at 1; \n first [ intros H\n | let H' := fresh \"NameAlreadyUsed\" in intros H'] end.\n\n(** With the type [Carrier], we implement the three following tactics:\n - [_put x] is used to return a value (leaving it on the stack)\n - [_get] is used to obtain the last returned value \n - [_rem] is used to remove the last returned value from the \n context. \n The typicall usage is: [mytactic args; let result := _get in _rem; ...].\n *)\n\nInductive Carrier : forall A, A -> Type :=\n | carrier : forall A x, @Carrier A x.\n\n(** [_put x] adds on hypothesis of type [Carrier x].\n [_put2 x y] and [_put3 x y z] can be used for functions\n that return pairs or triples of values. *)\n\nLtac _put x :=\n generalize (carrier x); intro.\nLtac _put2 x y :=\n _put y; _put x.\nLtac _put3 x y z :=\n _put z; _put y; _put x.\n\n(** [_get] returns the value [x] contained in the last hypothesis of \n type [Carrier x] available in the context. If fails if there\n is no such hypothesis. *)\n\nLtac _get :=\n match goal with H: Carrier ?t |- _ => t end.\n\n(** [_rem] clears the last hypothesis of type [Carrier _]. \n If fails if there is no such hypothesis. *)\n\nLtac _rem :=\n match goal with H: Carrier ?t |- _ => clear H end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** List of arguments for tactics *)\n\nRequire Import List.\n\n(** [ltac_wild] is a constant that can be used to simulate \n wildcard arguments in tactic definitions. Notation is [__]. *)\n\nInductive ltac_Wild : Set := \n | ltac_wild : ltac_Wild.\n\nNotation \"'__'\" := ltac_wild : ltac_scope.\n\n(** [ltac_wilds] is another constant that can be used to simulate \n a sequence of [N] wildcards, with [N] chosen appropriately \n depending on the context. Notation is [___]. *)\n\nInductive ltac_Wilds : Set := \n | ltac_wilds : ltac_Wilds.\n\nNotation \"'___'\" := ltac_wilds : ltac_scope.\n\n(** [Boxer] is a datatype such that the type [list Boxer] can be used \n to manipulate list of values in ltac. *)\n\nInductive Boxer : Type :=\n | boxer : forall (A:Type), A -> Boxer.\n\nNotation \"'>>>'\" :=\n (@nil Boxer)\n (at level 0)\n : ltac_scope.\nNotation \"'>>>' v1\" :=\n ((boxer v1)::nil)\n (at level 0, v1 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2\" :=\n ((boxer v1)::(boxer v2)::nil)\n (at level 0, v1 at level 0, v2 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4 v5\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::(boxer v5)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0, v5 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4 v5 v6\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::(boxer v5)\n ::(boxer v6)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0, v5 at level 0, v6 at level 0)\n : ltac_scope.\nNotation \"'>>>' v1 v2 v3 v4 v5 v6 v7\" :=\n ((boxer v1)::(boxer v2)::(boxer v3)::(boxer v4)::(boxer v5)\n ::(boxer v6)::(boxer v7)::nil)\n (at level 0, v1 at level 0, v2 at level 0, v3 at level 0,\n v4 at level 0, v5 at level 0, v6 at level 0, v7 at level 0)\n : ltac_scope.\n\nOpen Scope ltac_scope.\n\n(** [ltac_inst] is a datatype that describes the four instantiation\n modes that can be used in tactics [specializes], [lets],\n [applys] and [forwards]. \n - [Args]: all arguments are to be provided,\n - [Hyps]: only hypotheses are to be provided\n (hypotheses = arguments not used dependently)\n - [Vars]: only variables are to be provided\n (variables = arguments used dependently)\n - [Hnts]: the arguments provided are used as hints and are\n affected to the first argument of matching type.\n *)\n\nInductive ltac_inst : Set :=\n | Args : ltac_inst\n | Hyps : ltac_inst\n | Vars : ltac_inst\n | Hnts : ltac_inst.\n\n(** [ltac_args] inputs a term [E] and returns a term of type \"list boxer\":\n - if [E] is already of type \"list Boxer\" that starts with the\n value of an instantiation mode, it returns [E],\n - otherwise if [E] is already of type \"list Boxer\", it returns\n [(boxer Hnts)::E], in other words, mode [Hnts] is the default,\n - otherwise, it returns the list containing \n [(boxer Hnts)::(boxer E)::nil], describing the fact that there\n is only one argument provided, in the mode [Hnts]. *)\n\nLtac ltac_args E := \n match type of E with \n | List.list Boxer => \n match E with\n | (@boxer ltac_inst _)::_ => constr:(E)\n | _ => constr:((boxer Hnts)::E)\n end\n | _ => constr:((boxer Hnts)::(boxer E)::nil)\n end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Numbers as arguments *)\n\n(** When tactic takes a natural number as argument, it may be\n parsed as a relative number. In order for tactics to convert\n their arguments into natural numbers, we provide a conversion\n tactic that behaves appropriately when the module LibInt is\n loaded. *)\n \nLtac nat_from_number N := constr:(N).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Testing tactics *)\n\n(** [show tac] executes a tactic [tac] that produces a result (not \n performing any side-effect on the goal) and then display its result. *)\n\nTactic Notation \"show\" tactic(tac) :=\n let R := tac in pose R.\n\n(** [dup N] produces [N] copies of the current goal. It is useful\n for building examples on which to illustrate behaviour of tactics.\n [dup] is short for [dup 2]. *)\n\nLemma dup_lemma : forall P, P -> P -> P.\nProof. auto. Qed.\n\nLtac dup_tactic N :=\n match nat_from_number N with\n | 0 => idtac\n | S 0 => idtac\n | S ?N' => apply dup_lemma; [ | dup_tactic N' ]\n end.\n\nTactic Notation \"dup\" constr(N) := \n dup_tactic N.\nTactic Notation \"dup\" := \n dup 2.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Deconstructing terms *)\n\n(** [get_head E] is a tactic that returns the head constant of the \n term [E], ie, when applied to a term of the form [P x1 ... xN] \n it returns [P]. If [E] is not an application, it returns [E]. *)\n\nLtac get_head E :=\n match E with\n | ?P _ _ _ _ _ _ _ _ _ => constr:(P)\n | ?P _ _ _ _ _ _ _ _ => constr:(P) \n | ?P _ _ _ _ _ _ _ => constr:(P)\n | ?P _ _ _ _ _ _ => constr:(P)\n | ?P _ _ _ _ _ => constr:(P) \n | ?P _ _ _ _ => constr:(P) \n | ?P _ _ _ => constr:(P) \n | ?P _ _ => constr:(P) \n | ?P _ => constr:(P)\n | ?P => constr:(P)\n end.\n\n(* [is_metavar E] returns whether E is a meta-variable.\n However, its implementation is approximative, since it\n returns [true] also for constants (i.e. not-applicative terms). *)\n\nLtac is_metavar E :=\n match E with\n | ?P _ _ _ _ _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ _ _ _ _ => constr:(false) \n | ?P _ _ _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ _ => constr:(false)\n | ?P _ _ _ _ => constr:(false)\n | ?P _ _ _ => constr:(false)\n | ?P _ _ => constr:(false)\n | ?P _ => constr:(false)\n | ?P => constr:(true)\n end.\n\n\n(* ********************************************************************** *)\n(** * Backward and forward chaining *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Adding assumptions *)\n\n(** [lets H: E] adds an hypothesis [H : T] to the context, where [T] is \n the type of term [E]. If [H] is an introduction pattern, it will\n destruct [H] according to the pattern. *)\n\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E) :=\n generalize E; intros I.\n\n(** [lets H1 .. HN : E] is the same as \n [lets \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]:E], and thus equivalent to\n [destruct E as \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]]. *)\n\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(E) :=\n lets [I1 I2]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(E) :=\n lets [I1 [I2 I3]]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(E) :=\n lets [I1 [I2 [I3 I4]]]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(E) :=\n lets [I1 [I2 [I3 [I4 I5]]]]: E.\nTactic Notation \"lets\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(E) :=\n lets [I1 [I2 [I3 [I4 [I5 I6]]]]]: E.\n\n(** [lets_simpl H: E] is the same as [lets H: E] excepts that it\n calls [simpl] on the hypothesis H. *)\n\nTactic Notation \"lets_simpl\" ident(H) \":\" constr(E) :=\n lets H: E; simpl in H.\n\n(** [lets_hnf H: E] is the same as [lets H: E] excepts that it\n calls [hnf] to set the definition in head normal form. *)\n\nTactic Notation \"lets_hnf\" ident(H) \":\" constr(E) :=\n lets H: E; hnf in H.\n\n(** [lets: E] is equivalent to [lets H: E], only the name [H] is\n automatically chosen by Coq. It is useful to type-check a\n term (like the top-level command [Check]), but also to add\n facts that are going to be used by automation. \n Syntax [lets: E1 .. EN] is short for [lets: E1; ..; lets: EN]. *)\n\nTactic Notation \"lets\" \":\" constr(E1) :=\n generalize E1; intro.\nTactic Notation \"lets\" \":\" constr(E1) constr(E2) :=\n lets: E1; lets: E2.\nTactic Notation \"lets\" \":\" constr(E1) constr(E2) constr(E3) :=\n lets: E1; lets: E2; lets: E3.\n\n(** [lets_simpl: E] is the same as [lets_simpl H: E] with \n the name [H] being choosed automatically. *)\n\nTactic Notation \"lets_simpl\" \":\" constr(T) :=\n let H := fresh in lets_simpl H: T.\n\n(** [lets_hnf: E] is the same as [lets_hnf H: E] with \n the name [H] being choosed automatically. *)\n\nTactic Notation \"lets_hnf\" \":\" constr(T) :=\n let H := fresh in lets_hnf H: T.\n\n(** [put X: E] is a synonymous for [pose (X := E)].\n Other syntaxes are [put: E]. *)\n\nTactic Notation \"put\" ident(X) \":\" constr(E) :=\n pose (X := E).\nTactic Notation \"put\" \":\" constr(E) :=\n let X := fresh \"X\" in pose (X := E).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Application *)\n\n(** [applys] is a tactic similar to [eapply] except that it is\n based on the [refine] tactics, and thus is strictly more \n powerful (at least in theory :). In short, it is able to perform\n on-the-fly conversions when required for arguments to match,\n and it is able to instantiate existentials when required. *)\n\nTactic Notation \"applys\" constr(t) :=\n first \n [ refine (@t)\n | refine (@t _) \n | refine (@t _ _) \n | refine (@t _ _ _)\n | refine (@t _ _ _ _)\n | refine (@t _ _ _ _ _)\n | refine (@t _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _ _ _)\n | refine (@t _ _ _ _ _ _ _ _ _ _ _ _ _)\n ].\n\n(** The tactics [applys_N T], where [N] is a natural number,\n provides a more efficient way of using [applys T]. It avoids\n trying out all possible arities, by specifying explicitely\n the arity of function [T]. This version is to be preferred\n for programming intensively-used tactics. *)\n\nTactic Notation \"applys_0\" constr(t) :=\n refine (@t).\nTactic Notation \"applys_1\" constr(t) :=\n refine (@t _).\nTactic Notation \"applys_2\" constr(t) :=\n refine (@t _ _).\nTactic Notation \"applys_3\" constr(t) :=\n refine (@t _ _ _).\nTactic Notation \"applys_4\" constr(t) :=\n refine (@t _ _ _ _).\nTactic Notation \"applys_5\" constr(t) :=\n refine (@t _ _ _ _ _).\nTactic Notation \"applys_6\" constr(t) :=\n refine (@t _ _ _ _ _ _).\nTactic Notation \"applys_7\" constr(t) :=\n refine (@t _ _ _ _ _ _ _).\nTactic Notation \"applys_8\" constr(t) :=\n refine (@t _ _ _ _ _ _ _ _).\nTactic Notation \"applys_9\" constr(t) :=\n refine (@t _ _ _ _ _ _ _ _ _).\nTactic Notation \"applys_10\" constr(t) :=\n refine (@t _ _ _ _ _ _ _ _ _ _).\n\n(** [applys_to H E] transform the type of hypothesis [H] by \n replacing it by the result of the application of the term \n [E] to [H]. Intuitively, it is equivalent to [lets H: (E H)]. *)\n\nTactic Notation \"applys_to\" hyp(H) constr(E) :=\n let H' := fresh in rename H into H';\n (first [ lets H: (E H') \n | lets H: (E _ H') \n | lets H: (E _ _ H') \n | lets H: (E _ _ _ H') \n | lets H: (E _ _ _ _ H') \n | lets H: (E _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ _ _ H') \n | lets H: (E _ _ _ _ _ _ _ _ _ H') ]\n ); clear H'.\n\n(** [applys_in H E] transform the hypothesis [H] by replacing it\n by the result of the application of [H] to the term [E]\n Intuitively, it is equivalent to [lets H: (H E)]. \n DEPRECATED: use [specializes H E] instead. *)\n\nTactic Notation \"applys_in\" hyp(H) constr(E) :=\n let H' := fresh in rename H into H';\n (first [ lets H: (H' E) \n | lets H: (H' _ E) \n | lets H: (H' _ _ E) \n | lets H: (H' _ _ _ E) \n | lets H: (H' _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ _ _ E) \n | lets H: (H' _ _ _ _ _ _ _ _ _ E) ]\n ); clear H'.\n\n(** [applys_clear E] performs [applys E] and then calls [clear] on\n the head term of [E]. It fails if this head term is not an hypothesis\n or if it used dependently. *)\n\nTactic Notation \"applys_clear\" constr(E) :=\n applys E; let H := get_head E in clear E.\nTactic Notation \"apply_clear\" constr(E) :=\n applys_clear E.\n\n(** [constructors] calls [constructor] or [econstructor]. *)\n(* TODO: is [econstructor] stricly more powerful than\n [constructor]? *)\n\nTactic Notation \"constructors\" :=\n first [ constructor | econstructor ].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Assertions *)\n\n(** [false_goal] replaces any goal by the goal [False]. \n Contrary to the tactic [false] (below), it does not try to do\n anything else *)\n\nTactic Notation \"false_goal\" :=\n elimtype False.\n (* alternative implementation:\n assert False; [ | contradiction ]. *)\n\n(** [false] replaces any goal by the goal [False].\n Furthermore, it discharges the obligation if the context contains \n [False] or an hypothesis of the form [C x1 .. xN = D y1 .. yM]. *)\n\nTactic Notation \"false\" :=\n false_goal; try assumption; try discriminate.\n\n(** [tryfalse] tries to solve a goal by contradiction, and leaves\n the goal unchanged if it cannot solve it.\n It is equivalent to [try solve \\[ false \\]]. *)\n\nTactic Notation \"tryfalse\" :=\n try solve [ false ].\n\n(** [tryfalse by tac /] is that same as [tryfalse] except that\n it tries to solve the goal using tactic [tac] if [assumption]\n and [discriminate] do not apply.\n It is equivalent to [try solve \\[ false; tac \\]]. *)\n\nTactic Notation \"tryfalse\" \"by\" tactic(tac) \"/\" :=\n try solve [ false; tac ].\n\n(** [false T] is equivalent to [false; apply T]. It also \n solves the goal if [T] has type [C x1 .. xN = D y1 .. yM]. *)\n\nTactic Notation \"false\" constr(T) \"by\" tactic(tac) \"/\" :=\n false_goal; first \n [ first [ apply T | eapply T | applys T]; tac\n | let H := fresh in lets H: T; discriminate H ].\n\nTactic Notation \"false\" constr(T) :=\n false T by idtac/.\n\n(** [false_inv] proves any goal provided there is an\n hypothesis [H] in the context that can be proved absurd\n by calling [inversion H]. *)\nLtac false_inv_tactic :=\n match goal with H:_ |- _ =>\n solve [ inversion H\n | clear H; false_inv_tactic\n | fail 2 ] end.\n\nTactic Notation \"false_inv\" :=\n false_inv_tactic.\n\n(** [tryfalse_inv] tries to prove the goal using\n [false] or [false_inv], and leaves the goal\n unchanged if it does not succeed. *)\n\nTactic Notation \"tryfalse_inv\" :=\n try solve [ false | false_inv ].\n\n(** [asserts H: T] is another syntax for [assert (H : T)], which\n also works with introduction patterns. For instance, we can write:\n [asserts \\[x P\\] (exists n, n = 3)], or \n [asserts \\[H|H\\] (n = 0 \\/ n = 1). *)\n\nTactic Notation \"asserts\" simple_intropattern(I) \":\" constr(T) :=\n let H := fresh in assert (H : T); \n [ | generalize H; clear H; intros I ].\n\n(** [asserts H1 .. HN: T] is the same as \n [asserts \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]: T]. *)\n\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(T) :=\n asserts [I1 I2]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(T) :=\n asserts [I1 [I2 I3]]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(T) :=\n asserts [I1 [I2 [I3 I4]]]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(T) :=\n asserts [I1 [I2 [I3 [I4 I5]]]]: T.\nTactic Notation \"asserts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(T) :=\n asserts [I1 [I2 [I3 [I4 [I5 I6]]]]]: T.\n\n(** [asserts: T as H] is another syntax for [asserts H: T] *)\n\nTactic Notation \"asserts\" \":\" constr(T) \"as\" simple_intropattern(I) :=\n asserts I : T.\n\n(** [asserts: T] is [asserts H: T] with [H] being chosen automatically. *)\n\nTactic Notation \"asserts\" \":\" constr(T) :=\n let H := fresh in asserts H : T.\n\n(** [cuts H: T] is the same as [asserts H: T] except that the two subgoals\n generated are swapped: the subgoal [T] comes second. Note that contrary\n to [cut], it introduces the hypothesis. *)\n\nTactic Notation \"cuts\" simple_intropattern(I) \":\" constr(T) :=\n cut (T); [ intros I | idtac ].\n\n(** [cuts: T] is [cuts H: T] with [H] being chosen automatically. *)\n\nTactic Notation \"cuts\" \":\" constr(T) :=\n let H := fresh in cuts H: T.\n\n(** [cuts H1 .. HN: T] is the same as \n [cuts \\[H1 \\[H2 \\[.. HN\\]\\]\\]\\]: T]. *)\n\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(T) :=\n cuts [I1 I2]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(T) :=\n cuts [I1 [I2 I3]]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(T) :=\n cuts [I1 [I2 [I3 I4]]]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(T) :=\n cuts [I1 [I2 [I3 [I4 I5]]]]: T.\nTactic Notation \"cuts\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(T) :=\n cuts [I1 [I2 [I3 [I4 [I5 I6]]]]]: T.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Instantiation and forward-chaining *)\n\n(** The instantiation tactics are used to instantiate a lemma [E]\n (whose type is a product) on some arguments. The type of [E] is\n made of implications and universal quantifications, e.g.\n [forall x, P x -> forall y z, Q x y z -> R z].\n \n The first possibility is to provide arguments in order: first [x],\n then a proof of [P x], then [y] etc... In this mode, called \"Args\",\n all the arguments are to be provided. If a wildcard is provided\n (written [__]), then an existential variable will be introduced in\n place of the argument.\n\n It often saves a lot of time to give only the dependent variables,\n (here [x], [y] and [z]), and have the hypotheses generated as \n subgoals. In this \"Vars\" mode, only variables are to be provided. \n For instance, lemma [E] applied to [3] and [4] is a term\n of type [forall z, Q 3 4 z -> R z], and [P 3] is a new subgoal.\n It is possible to use wildcards to introduce existential variables.\n\n However, there are situations where some of the hypotheses already\n exists, and it saves time to instantiate the lemma [E] using the \n hypotheses. For instance, suppose [F] is a term of type [P 2]. \n Then the application of [E] to [F] in this \"Hyps\" mode is a term of type\n [forall y z, Q 2 y z -> R z]. Each wildcard use\n will generate an assertion instead, for instance if [G] has type\n [Q 2 3 4], then the application of [E] to a wildcard and to [G] \n in mode-h is a term of type [R 4], and [P 2] is a new subgoal.\n\n It is very convenient to give some arguments the lemma should be\n instantiated on, and let the tactic find out automatically where\n underscores should be insterted. The technique is simple: try to\n place an argument, and if it does not work insert an underscore.\n In this \"Hints\" mode ([Hnts] for short), underscore [__] would be useless,\n since they can be omitted. So, we interpret underscore as follows:\n an underscore means that we want to skip the argument that has the\n same type as the next real argument provided (real means not an\n underscore). If there is no real argument after underscore, then the\n the underscore is used for the first possible argument.\n\n There are four modes of instantiation:\n - \"Args\": give all arguments,\n - \"Vars\": give only variables,\n - \"Hyps\": give only hypotheses,\n - \"Hnts\": give some arguments.\n \n The general syntax is [tactic (>>>Mode E1 .. EN)] where [tactic] is\n the name of the tactic (possibly with some arguments) and [Mode]\n is the name of the mode, and [Ei] are the arguments.\n If [Mode] is omitted, [Hnts] will be inserted.\n If [>>>Mode] is omitted, [>>>Hnts] will be inserted.\n Moreover, some tactics accept the syntax [tactic E1 .. EN]\n as short for [tactic (>>>Hnts E1 .. EN)].\n\n Finally, if the argument [EN] given is a triple-underscore [___],\n then it is equivalent to providing a list of wildcards, with\n the appropriate number of wildcards. This means that all\n the remaining arguments of the lemma will be instantiated.\n\n*)\n\n(* Underlying implementation *)\n\n(* -- to be used once v8.1pl4 is no longer supported\nLtac app_darg t A v cont :=\n let x := fresh \"TEMP\" in\n evar (x:A); \n instantiate (1:=v) in (Value of x);\n let t' := constr:(t x) in\n let t'' := (eval unfold x in t') in\n subst x; cont t''.\n*)\n\nLtac app_arg t P v cont :=\n let H := fresh \"TEMP\" in\n assert (H : P); [ apply v | cont(t H); try clear H ].\n\nLtac app_assert t P cont :=\n let H := fresh \"TEMP\" in\n assert (H : P); [ | cont(t H); clear H ].\n\nLtac app_evar t A cont :=\n let x := fresh \"TEMP\" in\n evar (x:A); \n let t' := constr:(t x) in\n let t'' := (eval unfold x in t') in\n subst x; cont t''.\n\nLtac build_app_alls t final :=\n let rec go t :=\n match type of t with \n | ?P -> ?Q => app_assert t P go\n | forall _:?A, _ => app_evar t A go\n | _ => final t\n end in \n go t.\n\nLtac build_app_args t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' => \n let cont t' := go t' vs' in\n match v with\n | ltac_wild => \n match type of t with \n | ?P -> ?Q => first [ app_assert t P cont | fail 3 ]\n | forall _:?A, _ => first [ app_evar t A cont | fail 3 ] \n end\n | _ => \n match type of t with \n | ?P -> ?Q => first [ app_arg t P v cont | fail 3 ]\n | forall _:?A, _ => first [ cont (t v) | fail 3 ]\n (*todo: v8.2, use: app_darg t A v cont *)\n end\n end\n end in\n go t vs.\n\nLtac build_app_vars t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' =>\n match type of t with\n | ?P -> ?Q => \n let cont t' := go t' vs in\n first [ app_assert t P cont | fail 3 ]\n | forall _:?A, _ => \n let cont t' := go t' vs' in\n match v with\n | ltac_wild => first [ app_evar t A cont | fail 3 ]\n | _ => first [ cont(t v) | fail 3 ]\n end\n end\n end in\n go t vs.\n\nLtac build_app_hyps t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' =>\n match type of t with\n | ?P -> ?Q => \n let cont t' := go t' vs' in\n match v with\n | ltac_wild => first [ app_assert t P cont | fail 3 ]\n | _ => first [ app_arg t P v cont | fail 3 ]\n (* if mismatch is authorized\n first [ app_arg t P v cont\n | let cont' t' := go t' vs in\n app_assert t P cont' ] *) \n end \n | forall _:?A, _ => \n let cont t' := go t' vs in\n first [ app_evar t A cont | fail 3 ]\n end\n end in\n go t vs.\n\nLtac boxerlist_next_type vs :=\n match vs with\n | nil => constr:(ltac_wild)\n | (boxer ltac_wild)::?vs' => boxerlist_next_type vs'\n | (boxer ltac_wilds)::_ => constr:(ltac_wild)\n | (@boxer ?T _)::_ => constr:(T)\n end.\n\nLtac build_app_hnts t vs final :=\n let rec go t vs :=\n match vs with\n | nil => first [ final t | fail 1 ]\n | (boxer ltac_wilds)::_ => first [ build_app_alls t final | fail 1 ]\n | (boxer ?v)::?vs' => \n let cont t' := go t' vs in\n let cont' t' := go t' vs' in\n match v with\n | ltac_wild => \n first [ let T := boxerlist_next_type vs' in\n match T with\n | ltac_wild =>\n match type of t with \n | ?P -> ?Q => first [ app_assert t P cont' | fail 3 ]\n | forall _:?A, _ => first [ app_evar t A cont' | fail 3 ] \n end \n | _ =>\n match type of t with (* should test T for unifiability *)\n | T -> ?Q => first [ app_assert t T cont' | fail 3 ]\n | forall _:T, _ => first [ app_evar t T cont' | fail 3 ] \n | ?P -> ?Q => first [ app_assert t P cont | fail 3 ]\n | forall _:?A, _ => first [ app_evar t A cont | fail 3 ] \n end \n end\n | fail 2 ]\n | _ => \n match type of t with \n | ?P -> ?Q => first [ app_arg t P v cont'\n | app_assert t P cont\n | fail 3 ]\n | forall _:?A, _ => first [ cont' (t v) \n | app_evar t A cont\n | fail 3 ]\n end\n end\n end in\n go t vs.\n\n\nLtac build_app Ei final := \n let args := ltac_args Ei in \n first [ \n match args with (boxer ?mode)::(boxer ?t)::?vs => \n match mode with\n | Hnts => build_app_hnts t vs final\n | Args => build_app_args t vs final \n | Vars => build_app_vars t vs final\n | Hyps => build_app_hyps t vs final\n end end\n | fail 1 \"Instantiation fails for:\" args].\n\n\n(** [lets H: (>>> Mode E0 E1 .. EN)] will instantiate lemma [E0]\n on the arguments [Ei] (which may be wildcards [__]),\n and name [H] the resulting term. [H] may be an introduction\n pattern, or a sequence of introduction patterns [I1 I2 IN],\n or empty. \n Syntax [lets H: E0 E1 .. EN] is available for mode Hnts.\n The keyword \"ok\" may be replaced with \"of_vars\" or \"of_hyps\" \n for providing only variables or only hypotheses. If the last\n argument [EN] is [___] (triple-underscore), then all\n arguments of [H] will be instantiated. *)\n\nLtac lets_build I Ei :=\n build_app Ei ltac:(fun R => lets I: R).\n\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E) :=\n lets_build I E.\nTactic Notation \"lets\" \":\" constr(E) :=\n let H := fresh in lets H: E.\n\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n \":\" constr(E) :=\n lets [I1 I2]: E.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) \":\" constr(E) :=\n lets [I1 [I2 I3]]: E.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) \":\" constr(E) :=\n lets [I1 [I2 [I3 I4]]]: E.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5) \n \":\" constr(E) :=\n lets [I1 [I2 [I3 [I4 I5]]]]: E.\n \nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) :=\n lets I: (>>> E0 A1).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) :=\n lets I: (>>> E0 A1 A2).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) :=\n lets I: (>>> E0 A1 A2 A3).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) :=\n lets I: (>>> E0 A1 A2 A3 A4).\nTactic Notation \"lets\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n lets I: (>>> E0 A1 A2 A3 A4 A5).\n\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) :=\n lets [I1 I2]: E0 A1.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) :=\n lets [I1 I2]: E0 A1 A2.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) :=\n lets [I1 I2]: E0 A1 A2 A3.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) :=\n lets [I1 I2]: E0 A1 A2 A3 A4.\nTactic Notation \"lets\" simple_intropattern(I1) simple_intropattern(I2) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n lets [I1 I2]: E0 A1 A2 A3 A4 A5.\n\n\n(** [forwards H: (>>> Mode E0 E1 .. EN)] is short for \n [forwards H: (>>> Mode E0 E1 .. EN ___)]. \n The arguments [Ei] can be wildcards [__] (except [E0]).\n [H] may be an introduction pattern, or a sequence of\n introduction pattern, or empty. \n Syntax [forwards H: E0 E1 .. EN] is available for mode Hnts. *)\n\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E) :=\n let E' := ltac_args E in\n let E'' := (eval simpl in (E' ++ ((boxer ___)::nil))) in\n lets I: E''.\n\nTactic Notation \"forwards\" \":\" constr(E) := \n let H := fresh in forwards H: E.\n\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n \":\" constr(E) :=\n forwards [I1 I2]: E.\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) \":\" constr(E) :=\n forwards [I1 [I2 I3]]: E.\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) \":\" constr(E) :=\n forwards [I1 [I2 [I3 I4]]]: E.\nTactic Notation \"forwards\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5) \n \":\" constr(E) :=\n forwards [I1 [I2 [I3 [I4 I5]]]]: E.\n\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) :=\n forwards I: (>>> E0 A1).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) :=\n forwards I: (>>> E0 A1 A2).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) :=\n forwards I: (>>> E0 A1 A2 A3).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) :=\n forwards I: (>>> E0 A1 A2 A3 A4).\nTactic Notation \"forwards\" simple_intropattern(I) \":\" constr(E0) \n constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n forwards I: (>>> E0 A1 A2 A3 A4 A5).\n\n\n(** [applys (>>> Mode E0 E1 .. EN)] instantiates lemma [E0]\n on the arguments [Ei] (which may be wildcards [__]),\n and apply the resulting term to the current goal,\n using the tactic [applys] defined earlier on.\n [applys E0 E1 E2 .. EN] is short \n for [applys (>>>Hnts E0 E1 E2 .. EN)]. *)\n\nLtac applys_build Ei :=\n build_app Ei ltac:(fun R =>\n first [ apply R | eapply R | applys R ]).\n\nTactic Notation \"applys\" constr(E0) :=\n match type of E0 with\n | list Boxer => applys_build E0 \n | _ => applys E0\n end.\nTactic Notation \"applys\" constr(E0) constr(A1) :=\n applys (>>> E0 A1).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) :=\n applys (>>> E0 A1 A2).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) constr(A3) :=\n applys (>>> E0 A1 A2 A3).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) constr(A3) constr(A4) :=\n applys (>>> E0 A1 A2 A3 A4).\nTactic Notation \"applys\" constr(E0) constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n applys (>>> E0 A1 A2 A3 A4 A5).\n\n(** [specializes H (>>>Mode E1 E2 .. EN)] will instantiate hypothesis [H]\n on the arguments [Ei] (which may be wildcards [__]).\n The keyword \"ok\" may be replaced with \"of_vars\" or \"of_hyps\" \n for providing only variables or only hypotheses. If the last\n argument [EN] is [___] (triple-underscore), then all\n arguments of [H] will be instantiated. *)\n\nLtac specializes_build H Ei :=\n let H' := fresh \"TEMP\" in rename H into H';\n let Ei' := ltac_args Ei in\n match Ei' with (boxer ?mode)::?vs => \n let Ei'' := constr:((boxer mode)::(boxer H')::vs) in\n build_app Ei'' ltac:(fun R => lets H: R);\n clear H'\n end.\n \nTactic Notation \"specializes\" hyp(H) constr(A) :=\n specializes_build H A.\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) :=\n specializes H (>>> A1 A2).\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) constr(A3) :=\n specializes H (>>> A1 A2 A3).\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) constr(A3) constr(A4) :=\n specializes H (>>> A1 A2 A3 A4).\nTactic Notation \"specializes\" hyp(H) constr(A1) constr(A2) constr(A3) constr(A4) constr(A5) :=\n specializes H (>>> A1 A2 A3 A4 A5).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Experimental tactics for application *)\n\n(** [fapply] is a version of [apply] based on [forwards]. *)\n\nTactic Notation \"fapply\" constr(E) := \n let H := fresh in forwards H: E; \n first [ apply H | eapply H | hnf; apply H \n | hnf; eapply H | applys H ].\n\n(** [sapply] stands for \"super apply\". It tries\n [apply], [eapply], [applys] and [fapply],\n plus [hnf;apply] and [hnf;eapply]. *)\n\nTactic Notation \"sapply\" constr(H) :=\n first [ apply H | eapply H | applys H \n | hnf; apply H | hnf; eapply H | hnf; applys H\n | fapply H ].\n\n\n(* ********************************************************************** *)\n(** * Introduction and generalization *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Introduction *)\n\nDefinition ltac_tag_subst (A:Type) (x:A) := x.\n\n(** [introv] iterates [intro] on all universally-quantified \"variables\"\n at the head of the goal. More precisely, it introduces only the \n dependently-used variables. For example, [introv] applied\n to the goal [forall x y, P x -> Q] introduces [x] and [y] but not\n the hypothesis [P x]. If the goal is a definition, then it will\n unfold this definition. \n \n [introv H1 .. HN] calls [introv] then introduces an hypothesis as [H1],\n then call [introv] again and introduces an hypothesis as [H2], \n and so on.\n It provides a convenient way of introducing all the arguments of a\n theorem and name only the non-dependent hypotheses. *)\n \nLtac introv_rec :=\n match goal with\n | |- (ltac_tag_subst (?x = ?y) -> ?Q) =>\n let H := fresh \"Aux\" in \n intro H; unfold ltac_tag_subst in H;\n try subst x; introv_rec\n | |- ?P -> ?Q => idtac\n | |- forall _, _ => intro; introv_rec\n | |- _ => idtac\n end.\n\nLtac introv_to :=\n match goal with\n | |- (ltac_tag_subst (?x = ?y) -> ?Q) =>\n let H := fresh \"Aux\" in \n intro H; unfold ltac_tag_subst in H;\n try subst x; introv_to\n | |- ?P -> ?Q => idtac\n | |- forall _, _ => intro; introv_to\n | |- ?G => let P := get_head G in progress (unfold P); introv_to\n end.\n\nLtac introv_base :=\n match goal with\n | |- forall _, _ => introv_rec\n | |- ?G => let P := get_head G in unfold P; introv_rec\n end.\n\nTactic Notation \"introv\" :=\n introv_base.\nTactic Notation \"introv\" simple_intropattern(I) :=\n introv_to; intros I.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) :=\n introv_to; intros I1; introv_to; intros I2.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) :=\n introv; intros I1; introv; intros I2; introv; intros I3.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) :=\n introv; intros I1; introv; intros I2; introv; intros I3;\n introv; intros I4.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5) :=\n introv; intros I1; introv; intros I2; introv; intros I3;\n introv; intros I4; introv; intros I5.\nTactic Notation \"introv\" simple_intropattern(I1) simple_intropattern(I2) \n simple_intropattern(I3) simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) :=\n introv; intros I1; introv; intros I2; introv; intros I3;\n introv; intros I4; introv; intros I5; introv; intros I6.\n\n(** [intros_all] repeats [intro] as long as possible. Contrary to [intros],\n it unfolds any definition on the way. Remark that it also unfolds the\n definition of negation, so applying [introz] to a goal of the form\n [forall x, P x -> ~Q] will introduce [x] and [P x] and [Q], and will\n leave [False] in the goal. *)\n\nTactic Notation \"intros_all\" :=\n repeat intro.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Generalization *)\n\n(** [gen X1 .. XN] is a shorthand for calling [generalize dependent] \n successively on variables [XN]...[X1]. Note that the variables\n are generalized in reverse order, following the convention of\n the [generalize] tactic: it means that [X1] will be the first\n quantified variable in the resulting goal. *) \n\nTactic Notation \"gen\" ident(X1) :=\n generalize dependent X1.\nTactic Notation \"gen\" ident(X1) ident(X2) :=\n gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) :=\n gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) :=\n gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) :=\n gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) \n ident(X6) :=\n gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) \n ident(X6) ident(X7) :=\n gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) \n ident(X6) ident(X7) ident(X8) :=\n gen X8; gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\n\n(** [generalizes X] is a shorthand for calling [generalize X; clear X]. \n It is weaker than tactic [gen X] since it does not support\n dependencies. It is mainly intended for writing tactics. *) \n \nTactic Notation \"generalizes\" hyp(X) :=\n generalize X; clear X.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Naming *)\n\n(** [sets X: E] is the same as [set (X := E) in *], that is,\n it replaces all occurences of [E] by a fresh meta-variable [X]\n whose definition is [E]. *)\n\nTactic Notation \"sets\" ident(X) \":\" constr(E) :=\n set (X := E) in *.\n\n(** [def_to_eq E X H] applies when [X := E] is a local \n definition. It adds an assumption [H: X = E] \n and then clears the definition of [X].\n [def_to_eq_sym] is similar except that it generates\n the equality [H: E = X]. *)\n\nLtac def_to_eq X HX E :=\n assert (HX : X = E) by reflexivity; clearbody X.\nLtac def_to_eq_sym X HX E :=\n assert (HX : E = X) by reflexivity; clearbody X.\n\n(** [set_eq X H: E] generates the equality [H: X = E],\n for a fresh name [X], and replaces [E] by [X] in the\n current goal. Syntaxes [set_eq X: E] and\n [set_eq: E] are also available. Similarly,\n [set_eq <- X H: E] generates the equality [H: E = X]. \n\n [sets_eq X HX: E] does the same but replaces [E] by [X]\n everywhere in the goal. [sets_eq X HX: E in H] replaces in [H].\n [set_eq X HX: E in |-] performs no substitution at all. *)\n\nTactic Notation \"set_eq\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E); def_to_eq X HX E.\nTactic Notation \"set_eq\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in set_eq X HX: E.\nTactic Notation \"set_eq\" \":\" constr(E) :=\n let X := fresh \"X\" in set_eq X: E.\n\nTactic Notation \"set_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E); def_to_eq_sym X HX E.\nTactic Notation \"set_eq\" \"<-\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in set_eq <- X HX: E.\nTactic Notation \"set_eq\" \"<-\" \":\" constr(E) :=\n let X := fresh \"X\" in set_eq <- X: E.\n\nTactic Notation \"sets_eq\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E) in *; def_to_eq X HX E.\nTactic Notation \"sets_eq\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in sets_eq X HX: E.\nTactic Notation \"sets_eq\" \":\" constr(E) :=\n let X := fresh \"X\" in sets_eq X: E.\n\nTactic Notation \"sets_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) :=\n set (X := E) in *; def_to_eq_sym X HX E.\nTactic Notation \"sets_eq\" \"<-\" ident(X) \":\" constr(E) :=\n let HX := fresh \"EQ\" X in sets_eq <- X HX: E.\nTactic Notation \"sets_eq\" \"<-\" \":\" constr(E) :=\n let X := fresh \"X\" in sets_eq <- X: E.\n\nTactic Notation \"set_eq\" ident(X) ident(HX) \":\" constr(E) \"in\" hyp(H) :=\n set (X := E) in H; def_to_eq X HX E.\nTactic Notation \"set_eq\" ident(X) \":\" constr(E) \"in\" hyp(H) :=\n let HX := fresh \"EQ\" X in set_eq X HX: E in H.\nTactic Notation \"set_eq\" \":\" constr(E) \"in\" hyp(H) :=\n let X := fresh \"X\" in set_eq X: E in H.\n\nTactic Notation \"set_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) \"in\" hyp(H) :=\n set (X := E) in H; def_to_eq_sym X HX E.\nTactic Notation \"set_eq\" \"<-\" ident(X) \":\" constr(E) \"in\" hyp(H) :=\n let HX := fresh \"EQ\" X in set_eq <- X HX: E in H.\nTactic Notation \"set_eq\" \"<-\" \":\" constr(E) \"in\" hyp(H) :=\n let X := fresh \"X\" in set_eq <- X: E in H.\n\nTactic Notation \"set_eq\" ident(X) ident(HX) \":\" constr(E) \"in\" \"|-\" :=\n set (X := E) in |-; def_to_eq X HX E.\nTactic Notation \"set_eq\" ident(X) \":\" constr(E) \"in\" \"|-\" :=\n let HX := fresh \"EQ\" X in set_eq X HX: E in |-.\nTactic Notation \"set_eq\" \":\" constr(E) \"in\" \"|-\" :=\n let X := fresh \"X\" in set_eq X: E in |-.\n\nTactic Notation \"set_eq\" \"<-\" ident(X) ident(HX) \":\" constr(E) \"in\" \"|-\" :=\n set (X := E) in |-; def_to_eq_sym X HX E.\nTactic Notation \"set_eq\" \"<-\" ident(X) \":\" constr(E) \"in\" \"|-\" :=\n let HX := fresh \"EQ\" X in set_eq <- X HX: E in |-.\nTactic Notation \"set_eq\" \"<-\" \":\" constr(E) \"in\" \"|-\" :=\n let X := fresh \"X\" in set_eq <- X: E in |-.\n\n\n\n(* ********************************************************************** *)\n(** * Rewriting *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Pattern *)\n\n(** [ltac_pattern E at K] is the same as [pattern E at K] except that\n [K] is a Coq natural rather than a Ltac integer. Syntax \n [ltac_pattern E as K in H] is also available. *)\n\nTactic Notation \"ltac_pattern\" constr(E) \"at\" constr(K) :=\n match K with\n | 1 => pattern E at 1\n | 2 => pattern E at 2\n | 3 => pattern E at 3\n | 4 => pattern E at 4\n | 5 => pattern E at 5\n | 6 => pattern E at 6\n | 7 => pattern E at 7\n | 8 => pattern E at 8\n end.\n\nTactic Notation \"ltac_pattern\" constr(E) \"at\" constr(K) \"in\" hyp(H) :=\n match K with\n | 1 => pattern E at 1 in H\n | 2 => pattern E at 2 in H\n | 3 => pattern E at 3 in H\n | 4 => pattern E at 4 in H\n | 5 => pattern E at 5 in H\n | 6 => pattern E at 6 in H\n | 7 => pattern E at 7 in H\n | 8 => pattern E at 8 in H\n end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Action at occurence and action not at occurence *)\n\n(** [ltac_action_at K of E do Tac] isolates the [K]-th occurence of [E] in the\n goal, setting it in the form [P E] for some named pattern [P],\n then calls tactic [Tac], and finally unfolds [P]. Syntax\n [ltac_action_at K of E in H do Tac] is also available. *)\n\nTactic Notation \"ltac_action_at\" constr(K) \"of\" constr(E) \"do\" tactic(Tac) :=\n let p := fresh in ltac_pattern E at K;\n match goal with |- ?P _ => set (p:=P) end;\n Tac; unfold p; clear p.\n\nTactic Notation \"ltac_action_at\" constr(K) \"of\" constr(E) \"in\" hyp(H) \"do\" tactic(Tac) :=\n let p := fresh in ltac_pattern E at K in H;\n match type of H with ?P _ => set (p:=P) in H end;\n Tac; unfold p in H; clear p.\n\n(** [protects E do Tac] temporarily assigns a name to the expression [E] \n so that the execution of tactic [Tac] will not modify [E]. This is\n useful for instance to restrict the action of [simpl]. *)\n\nTactic Notation \"protects\" constr(E) \"do\" tactic(T) :=\n let x := fresh in sets_eq x: E; T; subst x.\n\nTactic Notation \"protects\" constr(E) \"do\" tactic(T) \"/\" :=\n protects E do T.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Rewriting *)\n\n(** [rewrite_all E] iterates version of [rewrite E] as long as possible. \n Warning: this tactic can easily get into an infinite loop. \n Syntax for rewriting from right to left and/or into an hypothese\n is similar to the one of [rewrite]. *)\n\nTactic Notation \"rewrite_all\" constr(E) :=\n repeat rewrite E.\nTactic Notation \"rewrite_all\" \"<-\" constr(E) :=\n repeat rewrite <- E.\nTactic Notation \"rewrite_all\" constr(E) \"in\" ident(H) :=\n repeat rewrite E in H.\nTactic Notation \"rewrite_all\" \"<-\" constr(E) \"in\" ident(H) :=\n repeat rewrite <- E in H.\nTactic Notation \"rewrite_all\" constr(E) \"in\" \"*\" :=\n repeat rewrite E in *.\nTactic Notation \"rewrite_all\" \"<-\" constr(E) \"in\" \"*\" :=\n repeat rewrite <- E in *.\n\n(** [asserts_rewrite E] asserts that an equality [E] holds (generating a \n corresponding subgoal) and rewrite it straight away in the current \n goal. It avoids giving a name to the equality and later clearing it. \n Syntax for rewriting from right to left and/or into an hypothese\n is similar to the one of [rewrite]. Note: the tactic [replaces] \n plays a similar role. *)\n\nLtac asserts_rewrite_tactic E action :=\n let EQ := fresh in (assert (EQ : E);\n [ idtac | action EQ; clear EQ ]).\n\nTactic Notation \"asserts_rewrite\" constr(E) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite EQ).\nTactic Notation \"asserts_rewrite\" \"<-\" constr(E) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ).\nTactic Notation \"asserts_rewrite\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite EQ in H).\nTactic Notation \"asserts_rewrite\" \"<-\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ in H).\n\n(** [cuts_rewrite E] is the same as [asserts_rewrite E] except\n that subgoals are permuted. *)\n\nLtac cuts_rewrite_tactic E action :=\n let EQ := fresh in (cuts EQ: E; \n [ action EQ; clear EQ | idtac ]).\n\nTactic Notation \"cuts_rewrite\" constr(E) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite EQ).\nTactic Notation \"cuts_rewrite\" \"<-\" constr(E) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ).\nTactic Notation \"cuts_rewrite\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite EQ in H).\nTactic Notation \"cuts_rewrite\" \"<-\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite_tactic E ltac:(fun EQ => rewrite <- EQ in H).\n\n(** [rewrite_except H EQ] rewrites equality [EQ] everywhere\n but in hypothesis [H]. *)\n\nLtac rewrite_except H EQ :=\n let K := fresh in let T := type of H in \n set (K := T) in H;\n rewrite EQ in *; unfold K in H; clear K.\n\n(** [rewrites E at K] applies when [E] is of the form [T1 = T2]\n rewrites the equality [E] at the [K]-th occurence of [T1]\n in the current goal. \n Syntaxes [rewrites <- E at K] and [rewrites E at K in H]\n are also available. *)\n\nTactic Notation \"rewrites\" constr(E) \"at\" constr(K) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T1 do (rewrite E) end.\nTactic Notation \"rewrites\" \"<-\" constr(E) \"at\" constr(K) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T2 do (rewrite <- E) end.\nTactic Notation \"rewrites\" constr(E) \"at\" constr(K) \"in\" hyp(H) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T1 in H do (rewrite E in H) end.\nTactic Notation \"rewrites\" \"<-\" constr(E) \"at\" constr(K) \"in\" hyp(H) :=\n match type of E with ?T1 = ?T2 =>\n ltac_action_at K of T2 in H do (rewrite <- E in H) end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Replace *)\n\n(** [replaces E with F] is the same as [replace E with F] except that\n the equality [E = F] is generated as first subgoal. Syntax\n [replaces E with F in H] is also available. Note that contrary to\n [replace], [replaces] does not try to solve the equality \n by [assumption]. Note: [asserts_rewrite] plays a similar role. *)\n\nTactic Notation \"replaces\" constr(E) \"with\" constr(F) :=\n let T := fresh in assert (T: E = F); [ | replace E with F; clear T ].\n\nTactic Notation \"replaces\" constr(E) \"with\" constr(F) \"in\" hyp(H) :=\n let T := fresh in assert (T: E = F); [ | replace E with F in H; clear T ].\n\n(** [replaces E at K with F] replaces the [K]-th occurence of [E]\n with [F] in the current goal. Syntax [replaces E at K with F in H]\n is also available. *)\n\nTactic Notation \"replaces\" constr(E) \"at\" constr(K) \"with\" constr(F) :=\n let T := fresh in assert (T: E = F); [ | rewrites T at K; clear T ].\n \nTactic Notation \"replaces\" constr(E) \"at\" constr(K) \"with\" constr(F) \"in\" hyp(H) :=\n let T := fresh in assert (T: E = F); [ | rewrites T at K in H; clear T ].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Renaming *)\n\n(** [renames X1 to Y1, ..., XN to YN] is a shorthand for a sequence of\n renaming operations [rename Xi into Yi]. *)\n\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) :=\n rename X1 into Y1.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) :=\n renames X1 to Y1; renames X2 to Y2.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) \",\"\n ident(X4) \"to\" ident(Y4) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3, X4 to Y4.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) \",\"\n ident(X4) \"to\" ident(Y4) \",\" ident(X5) \"to\" ident(Y5) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3, X4 to Y4, X5 to Y5.\nTactic Notation \"renames\" ident(X1) \"to\" ident(Y1) \",\"\n ident(X2) \"to\" ident(Y2) \",\" ident(X3) \"to\" ident(Y3) \",\"\n ident(X4) \"to\" ident(Y4) \",\" ident(X5) \"to\" ident(Y5) \",\"\n ident(X6) \"to\" ident(Y6) :=\n renames X1 to Y1; renames X2 to Y2, X3 to Y3, X4 to Y4, X5 to Y5, X6 to Y6.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Unfolding *)\n\n(** [unfolds] unfolds the head definition in the goal, i.e. if the\n goal has form [P x1 ... xN] then it calls [unfold P].\n If the goal is not in this form, it tries and call [intros] first. *)\n\nLtac unfolds_callback E cont :=\n let go E := let P := get_head E in cont P in\n match E with\n | ?A = ?B => first [ go A | go B ]\n | ?A => go A \n end.\n\nLtac unfolds_base :=\n match goal with |- ?G => \n unfolds_callback G ltac:(fun P => unfold P) end.\n\nTactic Notation \"unfolds\" :=\n unfolds_base.\n\n(** [unfolds in H] unfolds the head definition of hypothesis [H], i.e. if \n [H] has type [P x1 ... xN] then it calls [unfold P in H]. *)\n\nLtac unfolds_in_base H :=\n match type of H with ?G => \n unfolds_callback G ltac:(fun P => unfold P in H) end.\n\nTactic Notation \"unfolds\" \"in\" hyp(H) :=\n unfolds_in_base H.\n\n(** [unfolds P1,..,PN] is a shortcut for [unfold P1,..,PN in *]. *)\n\nTactic Notation \"unfolds\" reference(F1) :=\n unfold F1 in *.\nTactic Notation \"unfolds\" reference(F1) \",\" reference(F2) :=\n unfold F1,F2 in *.\nTactic Notation \"unfolds\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) :=\n unfold F1,F2,F3 in *.\nTactic Notation \"unfolds\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) \",\" reference(F4) :=\n unfold F1,F2,F3,F4 in *.\n\n(** [folds P1,..,PN] is a shortcut for [fold P1 in *; ..; fold PN in *]. *)\n\nTactic Notation \"folds\" constr(H) :=\n fold H in *.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) :=\n folds H1; folds H2.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) \",\" constr(H3) :=\n folds H1; folds H2; folds H3.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) \",\" constr(H3)\n \",\" constr(H4) :=\n folds H1; folds H2; folds H3; folds H4.\nTactic Notation \"folds\" constr(H1) \",\" constr(H2) \",\" constr(H3)\n \",\" constr(H4) \",\" constr(H5) :=\n folds H1; folds H2; folds H3; folds H4; folds H5.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Simplification *)\n\n(** [simpls] is a shortcut for [simpl in *]. *)\n\nTactic Notation \"simpls\" :=\n simpl in *.\n\n(** [simpls P1,..,PN] is a shortcut for \n [simpl P1 in *; ..; simpl PN in *]. *)\n\nTactic Notation \"simpls\" reference(F1) :=\n simpl F1 in *.\nTactic Notation \"simpls\" reference(F1) \",\" reference(F2) :=\n simpls F1; simpls F2.\nTactic Notation \"simpls\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) :=\n simpls F1; simpls F2; simpls F3.\nTactic Notation \"simpls\" reference(F1) \",\" reference(F2) \n \",\" reference(F3) \",\" reference(F4) :=\n simpls F1; simpls F2; simpls F3; simpls F4.\n\n(** [unsimpl E] replaces all occurence of [X] by [E], where [X] is \n the result which the tactic [simpl] would give when applied to [E]. \n It is useful to undo what [simpl] has simplified too far. *)\n\nTactic Notation \"unsimpl\" constr(E) := \n let F := (eval simpl in E) in change F with E.\n\n(** [unsimpl E in H] is similar to [unsimpl E] but it applies\n inside a particular hypothesis [H]. *)\n\nTactic Notation \"unsimpl\" constr(E) \"in\" hyp(H) := \n let F := (eval simpl in E) in change F with E in H.\n\n(** [unsimpl E in *] applies [unsimpl E] everywhere possible. *)\n\nTactic Notation \"unsimpl\" constr(E) \"in\" \"*\" := \n let F := (eval simpl in E) in change F with E in *.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Substitution *)\n\n(** [substs] does the same as [subst], except that it does not fail\n when there are circular equalities in the context. *)\n\nTactic Notation \"substs\" :=\n repeat (match goal with H: ?x = ?y |- _ => \n first [ subst x | subst y ] end).\n\n(** Implementation of [substs below]. *)\n\nLtac substs_below limit := \n match goal with H: ?T |- _ =>\n match T with\n | limit => idtac\n | ?x = ?y => \n first [ subst x; substs_below limit\n | subst y; substs_below limit\n | generalizes H; substs_below limit; intro ] \n end end.\n\n(** [substs below body E] applies [subst] on all equalities that appear\n in the context below the first hypothesis whose body is [E].\n If there is no such hypothesis in the context, it is equivalent\n to [subst]. For instance, if [H] is an hypothesis, then \n [substs below H] will substitute equalities below hypothesis [H]. *)\n\nTactic Notation \"substs\" \"below\" \"body\" constr(M) :=\n substs_below M.\n\n(** [substs below H] applies [subst] on all equalities that appear\n in the context below the hypothesis named [H]. Note that \n the current implementation is technically incorrect since it\n will confuse different hypotheses with the same body. *)\n\nTactic Notation \"substs\" \"below\" hyp(H) :=\n match type of H with ?M => substs below body M end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Proving equalities *)\n\n(** [fequal] is a variation on [f_equal] which has a better behaviour\n on equalities between n-ary tuples. *)\n\nLtac fequal_base :=\n let go := f_equal; [ fequal_base | ] in\n match goal with\n | |- (_,_,_) = (_,_,_) => go\n | |- (_,_,_,_) = (_,_,_,_) => go\n | |- (_,_,_,_,_) = (_,_,_,_,_) => go\n | |- (_,_,_,_,_,_) = (_,_,_,_,_,_) => go\n | |- _ => f_equal\n end.\n\nTactic Notation \"fequal\" :=\n fequal_base.\n\n(** [fequals] is the same as [fequal] except that it tries and solve\n all trivial subgoals, using [reflexivity] and [congruence].\n (It applies to goals of the form [f x1 .. xN = f y1 .. yN]\n and may produce subgoals of the form [xi = yi]). *)\n\nLtac fequal_post :=\n first [ reflexivity | congruence | idtac ].\n\nTactic Notation \"fequals\" :=\n fequal; fequal_post.\n\n(** [fequals_rec] calls [fequals] recursively. \n It is equivalent to [repeat (progress fequals)]. *)\n\nTactic Notation \"fequals_rec\" :=\n repeat (progress fequals). \n\n\n\n(* ********************************************************************** *)\n(** * Inversion *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Tools for naming hypotheses generated by inversion *)\n\n(** [ltac_Mark] and [ltac_mark] are dummy definitions used as sentinel\n by tactics. The [ltac_mark] has type [ltac_Mark]. *)\n\nInductive ltac_Mark : Type :=\n | ltac_mark : ltac_Mark.\n\n(** [gen_until_mark] repeats [generalize] on hypotheses from the \n context, starting from the bottom and stopping as soon as reaching\n an hypothesis of type [Mark]. If fails if [Mark] does not\n appear in the context. *)\n\nLtac gen_until_mark :=\n match goal with H: ?T |- _ =>\n match T with \n | ltac_Mark => clear H\n | _ => generalizes H; gen_until_mark\n end end.\n\n(** [intro_until_mark] repeats [intro] until reaching an hypothesis of\n type [Mark]. It throws away the hypothesis [Mark]. \n It fails if [Mark] does not appear as an hypothesis in the \n goal. *)\n\nLtac intro_until_mark :=\n match goal with \n | |- (ltac_Mark -> _) => intros _\n | _ => intro; intro_until_mark\n end.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Basic inversion *)\n\n(** [invert keep H] is same to [inversion H] except that it puts all the\n facts obtained in the goal. The keyword [keep] means that the\n hypothesis [H] should not be removed. *)\n\nTactic Notation \"invert\" \"keep\" hyp(H) :=\n pose ltac_mark; inversion H; gen_until_mark.\n\n(** [invert keep H as X1 .. XN] is the same as [inversion H as ...] except\n that only hypotheses which are not variable need to be named\n explicitely, in a similar fashion as [introv] is used to name\n only hypotheses. *)\n\nTactic Notation \"invert\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) :=\n invert keep H; introv I1. \nTactic Notation \"invert\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n invert keep H; introv I1 I2. \nTactic Notation \"invert\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n invert keep H; introv I1 I2 I3. \n\n(** [invert H] is same to [inversion H] except that it puts all the\n facts obtained in the goal and clears hypothesis [H].\n In other words, it is equivalent to [invert keep H; clear H]. *)\n\nTactic Notation \"invert\" hyp(H) :=\n invert keep H; clear H.\n\n(** [invert H as X1 .. XN] is the same as [invert keep H as X1 .. XN]\n but it also clears hypothesis [H]. *)\n\nTactic Notation \"invert_tactic\" hyp(H) tactic(tac) :=\n let H' := fresh in rename H into H'; tac H'; clear H'.\nTactic Notation \"invert\" hyp(H) \"as\" simple_intropattern(I1) :=\n invert_tactic H (fun H => invert keep H as I1).\nTactic Notation \"invert\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n invert_tactic H (fun H => invert keep H as I1 I2).\nTactic Notation \"invert\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n invert_tactic H (fun H => invert keep H as I1 I2 I3).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inversion with substitution *)\n\n(** Our inversion tactics is able to get rid of dependent equalities\n generated by [inversion], using proof irrelevance. *)\n\nRequire Import Eqdep.\n\nLtac inverts_tactic H i1 i2 i3 i4 i5 :=\n let rec go i1 i2 i3 i4 i5 :=\n match goal with \n | |- (ltac_Mark -> _) => intros _\n | |- (?x = ?y -> _) => let H := fresh in intro H; \n first [ subst x | subst y ]; \n go i1 i2 i3 i4 i5\n | |- (existT ?P ?p ?x = existT ?P ?p ?y -> _) =>\n let H := fresh in intro H; \n generalize (@EqdepTheory.inj_pair2 _ P p x y H);\n clear H; go i1 i2 i3 i4 i5\n | |- (?P -> ?Q) => i1; go i2 i3 i4 i5 ltac:(intro)\n | |- (forall _, _) => intro; go i1 i2 i3 i4 i5\n end in\n generalize ltac_mark; invert keep H; go i1 i2 i3 i4 i5.\n\n(** [inverts keep H] is same to [invert keep H] except that it \n applies [subst] to all the equalities generated by the inversion. *)\n\nTactic Notation \"inverts\" \"keep\" hyp(H) :=\n inverts_tactic H ltac:(intro) ltac:(intro) ltac:(intro) ltac:(intro) ltac:(intro).\n\n(** [inverts keep H as X1 .. XN] is the same as\n [invert keep H as X1 .. XN] except that it applies [subst] to all the \n equalities generated by the inversion *)\n\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) :=\n inverts_tactic H ltac:(intros I1) \n ltac:(intro) ltac:(intro) ltac:(intro) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2)\n ltac:(intro) ltac:(intro) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2) ltac:(intros I3)\n ltac:(intro) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2) ltac:(intros I3)\n ltac:(intros I4) ltac:(intro).\nTactic Notation \"inverts\" \"keep\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4)\n simple_intropattern(I5) :=\n inverts_tactic H ltac:(intros I1) ltac:(intros I2) ltac:(intros I3)\n ltac:(intros I4) ltac:(intros I5).\n\n(** [inverts H] is same to [inverts keep H] except that it \n clears hypothesis [H]. *)\n\nTactic Notation \"inverts\" hyp(H) :=\n inverts keep H; clear H.\n\n(** [inverts H as X1 .. XN] is the same as [inverts keep H as X1 .. XN]\n but it also clears the hypothesis [H]. *)\n\nTactic Notation \"inverts_tactic\" hyp(H) tactic(tac) :=\n let H' := fresh in rename H into H'; tac H'; clear H'.\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) :=\n invert_tactic H (fun H => inverts keep H as I1).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) :=\n invert_tactic H (fun H => inverts keep H as I1 I2).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) :=\n invert_tactic H (fun H => inverts keep H as I1 I2 I3).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4) :=\n invert_tactic H (fun H => inverts keep H as I1 I2 I3 I4).\nTactic Notation \"inverts\" hyp(H) \"as\" simple_intropattern(I1) \n simple_intropattern(I2) simple_intropattern(I3) simple_intropattern(I4) \n simple_intropattern(I5) :=\n invert_tactic H (fun H => inverts keep H as I1 I2 I3 I4 I5).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Injection with substitution *)\n\n(** Underlying implementation of [injects] *)\n\nLtac injects_tactic H :=\n let rec go _ :=\n match goal with \n | |- (ltac_Mark -> _) => intros _\n | |- (?x = ?y -> _) => let H := fresh in intro H; \n first [ subst x | subst y | idtac ]; \n go tt\n end in\n generalize ltac_mark; injection H; go tt.\n\n(** [injects keep H] takes an hypothesis [H] of the form\n [C a1 .. aN = C b1 .. bN] and substitute all equalities\n [ai = bi] that have been generated. *)\n\nTactic Notation \"injects\" \"keep\" hyp(H) :=\n injects_tactic H.\n\n(** [injects H] is similar to [injects keep H] but clears \n the hypothesis [H]. *)\n\nTactic Notation \"injects\" hyp(H) :=\n injects_tactic H; clear H.\n\n(** [inject H as X1 .. XN] is the same as [injection]\n followed by [intros X1 .. XN] *)\n \nTactic Notation \"inject\" hyp(H) :=\n injection H. \nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) :=\n injection H; intros X1.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) :=\n injection H; intros X1 X2.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) ident(X3) :=\n injection H; intros X1 X2 X3.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) ident(X3) \n ident(X4) :=\n injection H; intros X1 X2 X3 X4.\nTactic Notation \"inject\" hyp(H) \"as\" ident(X1) ident(X2) ident(X3) \n ident(X4) ident(X5) :=\n injection H; intros X1 X2 X3 X4 X5.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inversion and injection with substitution --rough implementation *)\n\n(** The tactics [inversions] and [injections] provided in this section\n are similar to [inverts] and [injects] except that they perform\n substitution on all equalities from the context and not only\n the ones freshly generated. The counterpart is that they have\n simpler implementations. *)\n\n(** [inversions keep H] is the same as [inversions H] but it does\n not clear hypothesis [H]. *)\n\nTactic Notation \"inversions\" \"keep\" hyp(H) :=\n inversion H; subst.\n\n(** [inversions H] is a shortcut for [inversion H] followed by [subst]\n and [clear H].\n It is a rough implementation of [inverts keep H] which behave\n badly when the proof context already contains equalities. \n It is provided in case the better implementation turns out to be\n too slow. *)\n\nTactic Notation \"inversions\" hyp(H) :=\n inversion H; subst; clear H.\n\n(** [injections keep H] is the same as [injection H] followed\n by [intros] and [subst]. It is a rough implementation of \n [injects keep H] which behave\n badly when the proof context already contains equalities,\n or when the goal starts with a forall or an implication. *)\n\nTactic Notation \"injections\" \"keep\" hyp(H) :=\n injection H; intros; subst.\n\n(** [injections H] is the same as [injection H] followed\n by [intros] and [clear H] and [subst]. It is a rough \n implementation of [injects keep H] which behave\n badly when the proof context already contains equalities,\n or when the goal starts with a forall or an implication. *)\n\nTactic Notation \"injections\" \"keep\" hyp(H) :=\n injection H; clear H; intros; subst.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Case analysis *)\n\n(** [case_if] looks for a pattern of the form [if ?B then ?E1 else ?E2]\n in the goal, and perform a case analysis on [B] by calling \n [destruct B]. It looks in the goal first, and otherwise in the\n first hypothesis that contains and [if] statement. \n [case_if in H] can be used to specify which hypothesis to consider. \n Syntaxes [case_if as Eq] and [case_if in H as Eq] allows to name\n the hypothesis coming from the case analysis. *)\nLtac case_if_on_tactic E Eq :=\n let X := fresh in \n sets_eq <- X Eq: E;\n destruct X.\n\nTactic Notation \"case_if_on\" constr(E) \"as\" simple_intropattern(Eq) :=\n case_if_on_tactic E Eq.\n\nTactic Notation \"case_if\" \"as\" simple_intropattern(Eq) :=\n match goal with \n | |- context [if ?B then _ else _] => case_if_on B as Eq\n | K: context [if ?B then _ else _] |- _ => case_if_on B as Eq\n end.\n\nTactic Notation \"case_if\" \"in\" hyp(H) \"as\" simple_intropattern(Eq) :=\n match type of H with context [if ?B then _ else _] => \n case_if_on B as Eq end.\n\nTactic Notation \"case_if\" :=\n let Eq := fresh in case_if as Eq.\n\nTactic Notation \"case_if\" \"in\" hyp(H) :=\n let Eq := fresh in case_if in H as Eq.\n\n\n(* ********************************************************************** *)\n(** * Induction *)\n\n(** [gen_eq X: E] is a tactic whose purpose is to introduce \n equalities so as to work around the limitation of the [induction]\n tactic which typically loses information. [gen_eq E as X] replaces \n all occurences of term [E] with a fresh variable [X] and the equality\n [X = E] as extra hypothesis to the current conclusion. In other words\n a conclusion [C] will be turned into [(X = E) -> C].\n [gen_eq: E] and [gen_eq: E as X] are also accepted. *)\n\nTactic Notation \"gen_eq\" ident(X) \":\" constr(E) :=\n let EQ := fresh in sets_eq X EQ: E; revert EQ.\nTactic Notation \"gen_eq\" \":\" constr(E) :=\n let X := fresh \"X\" in gen_eq X: E.\nTactic Notation \"gen_eq\" \":\" constr(E) \"as\" ident(X) :=\n gen_eq X: E.\nTactic Notation \"gen_eq\" ident(X1) \":\" constr(E1) \",\"\n ident(X2) \":\" constr(E2) :=\n gen_eq X2: E2; gen_eq X1: E1.\nTactic Notation \"gen_eq\" ident(X1) \":\" constr(E1) \",\"\n ident(X2) \":\" constr(E2) \",\" ident(X3) \":\" constr(E3) :=\n gen_eq X3: E3; gen_eq X2: E2; gen_eq X1: E1.\n\n\n(** [inductions H] is a tactic similar to [induction H] except\n that it is able to introduce equalities in order to avoid\n losing information. The syntax [inductions H gen X1 .. XN end]\n is to be used in order to generalize variables before the \n induction. Syntaxes [inductions H as I] and\n [inductions H as I gen X1 .. XN end] are also available.\n\n For technical reasons, the tactic [inductions] will not introduce\n equalities for constants (e.g. if [H] has type [P 0 x], [inductions]\n will not save the information that the first argument is [0]). \n However, the tactic [inductions'] aggressively introduces equalities\n for all arguments, and will apply. The reason why [inductions'] is not\n the default tactic is that it may introduce more equalities than necessary,\n which slightly pollutes the induction hypotheses.\n*)\n\nLtac gen_eq_for_inductions H E :=\n let X := fresh \"aux\" in\n let HX := fresh \"H\" X in\n set (X := E) in H |-;\n assert (HX : ltac_tag_subst (X = E));\n [ unfold ltac_tag_subst; reflexivity\n | clearbody X; generalizes HX ].\n\n(* [apply_to_all_args T Tac] expects the type [T] to be of the form [P E1 .. En]\n and applies the tactic [Tac] to all the arguments [Ei]. *)\n\nLtac apply_to_all_args T go :=\n match T with\n | ?P ?E1 ?E2 ?E3 ?E4 ?E5 ?E6 => go E1; go E2; go E3; go E4; go E5; go E6\n | ?P ?E1 ?E2 ?E3 ?E4 ?E5 => go E1; go E2; go E3; go E4; go E5\n | ?P ?E1 ?E2 ?E3 ?E4 => go E1; go E2; go E3; go E4\n | ?P ?E1 ?E2 ?E3 => go E1; go E2; go E3\n | ?P ?E1 ?E2 => go E1; go E2\n | ?P ?E1 => go E1\n end.\n\n(* [gens_eqs' H] introduces equalities to name arguments in [H]. *)\n\nTactic Notation \"gen_eqs'\" hyp(H) :=\n let T := type of H in\n let go E := try gen_eq_for_inductions H E in\n apply_to_all_args T go.\n\n(* [gens_eqs H] is same as [gens_eqs' H] but it tries to be slightly more\n clever. As a consequence, it generates fewer equalities, but sometimes\n it forgets some equalities. This happens when some arguments of [H] are\n constants. *)\n\nTactic Notation \"gen_eqs\" hyp(H) :=\n let T := type of H in\n let go E := \n match is_metavar E with\n | true => idtac\n | false => try gen_eq_for_inductions H E\n end in\n apply_to_all_args T go.\n\nLtac intros_head_ltac_tag_subst :=\n try match goal with |- (ltac_tag_subst (?x = ?y) -> ?Q) =>\n let H := fresh \"Aux\" in \n intro H; unfold ltac_tag_subst in H;\n try subst x; intros_head_ltac_tag_subst\n end.\n\nLtac inductions_post :=\n intros_head_ltac_tag_subst; \n unfold ltac_tag_subst in * |-.\n\nTactic Notation \"inductions\" hyp(H) :=\n gen_eqs H; induction H; inductions_post.\nTactic Notation \"inductions\" hyp(H) \"as\" simple_intropattern(I) :=\n gen_eqs H; induction H as I; inductions_post.\nTactic Notation \"inductions\" hyp(H) tactic(Gen) \"end\" :=\n gen_eqs H; Gen; induction H; inductions_post.\nTactic Notation \"inductions\" hyp(H) \"as\" simple_intropattern(I) \n tactic(Gen) \"end\" :=\n gen_eqs H; Gen; induction H as I; inductions_post.\n\nTactic Notation \"inductions'\" hyp(H) :=\n gen_eqs' H; induction H; inductions_post.\nTactic Notation \"inductions'\" hyp(H) \"as\" simple_intropattern(I) :=\n gen_eqs' H; induction H as I; inductions_post.\nTactic Notation \"inductions'\" hyp(H) tactic(Gen) \"end\" :=\n gen_eqs' H; Gen; induction H; inductions_post.\nTactic Notation \"inductions'\" hyp(H) \"as\" simple_intropattern(I) \n tactic(Gen) \"end\" :=\n gen_eqs' H; Gen; induction H as I; inductions_post.\n\n(** [induction_wf IH: E X] is used to apply the well-founded induction\n principle, for a given well-founded relation. It applies to a goal\n [PX] where [PX] is a proposition on [X]. First, it sets up the\n goal in the form [(fun a => P a) X], using [pattern X], and then\n it applies the well-founded induction principle instantiated on [E],\n where [E] is a term of type [well_founded R], and [R] is a binary\n relation.\n Syntaxes [induction_wf: E X] and [induction_wf E X]\n and [induction_wf E X as IH] are also available. *)\n\nTactic Notation \"induction_wf\" ident(IH) \":\" constr(E) ident(X) :=\n pattern X; apply (well_founded_ind E); clear X; intros X IH.\nTactic Notation \"induction_wf\" \":\" constr(E) ident(X) :=\n let IH := fresh \"IH\" in induction_wf IH: E X.\nTactic Notation \"induction_wf\" \":\" constr(E) ident(X) \"as\" ident(IH) :=\n induction_wf IH: E X.\nTactic Notation \"induction_wf\" \":\" constr(E) ident(X) :=\n induction_wf: E X.\n\n\n(* ********************************************************************** *)\n(** * Decidable equality *)\n\n(** [decides_equality] is the same as [decide equality] excepts that it \n is able to unfold definitions at head of the current goal. *)\n\nLtac decides_equality_tactic :=\n first [ decide equality | progress(unfolds); decides_equality_tactic ].\n\nTactic Notation \"decides_equality\" :=\n decides_equality_tactic.\n\n\n(* ********************************************************************** *)\n(** * N-ary Conjunctions and Disjunctions *)\n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Conjunctions Splitting in Goals *)\n\n(** Underlying implementation of [splits]. *)\n\nLtac splits_tactic N :=\n match N with\n | O => fail\n | S O => idtac\n | S ?N' => split; [| splits_tactic N']\n end.\n\nLtac unfold_goal_until_conjunction :=\n match goal with\n | |- _ /\\ _ => idtac\n | _ => progress(unfolds); unfold_goal_until_conjunction\n end.\n\nLtac get_term_conjunction_arity T :=\n match T with\n | _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(8)\n | _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(7)\n | _ /\\ _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(6)\n | _ /\\ _ /\\ _ /\\ _ /\\ _ => constr:(5)\n | _ /\\ _ /\\ _ /\\ _ => constr:(4)\n | _ /\\ _ /\\ _ => constr:(3)\n | _ /\\ _ => constr:(2)\n | _ -> ?T' => get_term_conjunction_arity T'\n | _ => let P := get_head T in\n let T' := eval unfold P in T in\n match T' with \n | T => fail 1\n | _ => get_term_conjunction_arity T'\n end\n end.\n\nLtac get_goal_conjunction_arity :=\n match goal with |- ?T => get_term_conjunction_arity T end.\n\n(** [splits] applies to a goal of the form [(T1 /\\ .. /\\ TN)] and\n destruct it into [N] subgoals [T1] .. [TN]. If the goal is not a \n conjunction, then it unfolds the head definition. *)\n\nTactic Notation \"splits\" :=\n unfold_goal_until_conjunction;\n let N := get_goal_conjunction_arity in\n splits_tactic N.\n\n(** [splits N] is similar to [splits], except that it will unfold as many\n definitions as necessary to obtain an [N]-ary conjunction. *)\n\nTactic Notation \"splits\" constr(N) := \n splits_tactic N.\n\n(** [splits_all] will recursively split any conjunction, unfolding\n definitions when necessary. *)\n\nTactic Notation \"splits_all\" := \n repeat split.\n\n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Conjunctions Deconstruction *)\n\n(** Underlying implementation of [destructs]. *)\n\nLtac destructs_conjunction_tactic N T :=\n match N with\n | 2 => destruct T as [? ?]\n | 3 => destruct T as [? [? ?]]\n | 4 => destruct T as [? [? [? ?]]]\n | 5 => destruct T as [? [? [? [? ?]]]]\n | 6 => destruct T as [? [? [? [? [? ?]]]]]\n | 7 => destruct T as [? [? [? [? [? [? ?]]]]]]\n end. \n\n(** [destructs T] allows destructing a term [T] which is a N-ary \n conjunction. It is equivalent to [destruct T as (H1 .. HN)], \n except that it does not require to manually specify N different \n names. *)\n\nTactic Notation \"destructs\" constr(T) :=\n let TT := type of T in\n let N := get_term_conjunction_arity TT in \n destructs_conjunction_tactic N T.\n\n(** [destructs N T] is equivalent to [destruct T as (H1 .. HN)],\n except that it does not require to manually specify N different \n names. Remark that it is not restricted to N-ary conjunctions. *)\n\nTactic Notation \"destructs\" constr(N) constr(T) :=\n destructs_conjunction_tactic N T.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Proving goals which are N-ary disjunctions *)\n\n(** Underlying implementation of [branch]. *)\n\nLtac branch_tactic K N := \n match constr:(K,N) with\n | (_,0) => fail 1\n | (0,_) => fail 1\n | (1,1) => idtac\n | (1,_) => left\n | (S ?K', S ?N') => right; branch_tactic K' N'\n end.\n\nLtac unfold_goal_until_disjunction :=\n match goal with\n | |- _ \\/ _ => idtac\n | _ => progress(unfolds); unfold_goal_until_disjunction\n end.\n\nLtac get_term_disjunction_arity T :=\n match T with\n | _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(8)\n | _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(7)\n | _ \\/ _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(6)\n | _ \\/ _ \\/ _ \\/ _ \\/ _ => constr:(5)\n | _ \\/ _ \\/ _ \\/ _ => constr:(4)\n | _ \\/ _ \\/ _ => constr:(3)\n | _ \\/ _ => constr:(2)\n | _ -> ?T' => get_term_disjunction_arity T'\n | _ => let P := get_head T in\n let T' := eval unfold P in T in\n match T' with \n | T => fail 1\n | _ => get_term_disjunction_arity T'\n end\n end.\n\nLtac get_goal_disjunction_arity :=\n match goal with |- ?T => get_term_disjunction_arity T end.\n\n(** [branch N] applies to a goal of the form \n [P1 \\/ ... \\/ PK \\/ ... \\/ PN] and leaves the goal [PK].\n It only able to unfold the head definition (if there is one),\n but for more complex unfolding one should use the tactic\n [branch K of N]. *)\n\nTactic Notation \"branch\" constr(K) :=\n unfold_goal_until_disjunction; \n let N := get_goal_disjunction_arity in\n branch_tactic K N.\n\n(** [branch K of N] is similar to [branch K] except that the\n arity of the disjunction [N] is given manually, and so this\n version of the tactic is able to unfold definitions.\n In other words, applies to a goal of the form \n [P1 \\/ ... \\/ PK \\/ ... \\/ PN] and leaves the goal [PK]. *)\n\nTactic Notation \"branch\" constr(K) \"of\" constr(N) :=\n branch_tactic K N.\n\n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Disjunction Deconstruction *)\n\n(** Underlying implementation of [branches]. *)\n\nLtac destructs_disjunction_tactic N T :=\n match N with\n | 2 => destruct T as [? | ?]\n | 3 => destruct T as [? | ? | ?]\n | 4 => destruct T as [? | ? | ? | ?]\n | 5 => destruct T as [? | ? | ? | ? | ?]\n | 6 => destruct T as [? | ? | ? | ? | ? | ?]\n | 7 => destruct T as [? | ? | ? | ? | ? | ? | ?]\n end.\n\n(** [branches T] allows destructing a term [T] which is a N-ary \n disjunction. It is equivalent to [destruct T as [ H1 | .. | HN ] ], \n and produces [N] subgoals corresponding to the [N] possible cases. *)\n\nTactic Notation \"branches\" constr(T) :=\n let TT := type of T in\n let N := get_term_disjunction_arity TT in\n destructs_disjunction_tactic N T.\n\n(** [branches N T] is the same as [branches T] except that the arity is\n forced to [N]. This version is useful to unfold definitions \n on the fly. *)\n\nTactic Notation \"branches\" constr(N) constr(T) :=\n destructs_disjunction_tactic N T.\n \n\n(* ---------------------------------------------------------------------- *)\n(** N-ary Existentials *)\n\n(* Underlying implementation of [exists]. *)\n\nLtac get_term_existential_arity T :=\n match T with\n | exists x1 x2 x3 x4 x5 x6 x7 x8, _ => constr:(8)\n | exists x1 x2 x3 x4 x5 x6 x7, _ => constr:(7)\n | exists x1 x2 x3 x4 x5 x6, _ => constr:(6)\n | exists x1 x2 x3 x4 x5, _ => constr:(5)\n | exists x1 x2 x3 x4, _ => constr:(4)\n | exists x1 x2 x3, _ => constr:(3)\n | exists x1 x2, _ => constr:(2)\n | exists x1, _ => constr:(1)\n | _ -> ?T' => get_term_existential_arity T'\n | _ => let P := get_head T in\n let T' := eval unfold P in T in\n match T' with \n | T => fail 1\n | _ => get_term_existential_arity T'\n end\n end.\n\nLtac get_goal_existential_arity :=\n match goal with |- ?T => get_term_existential_arity T end.\n\n(** [exists T1 ... TN] is a shorthand for [exists T1; ...; exists TN].\n It is intended to prove goals of the form [exist X1 .. XN, P].\n If an argument provided is [__] (double underscore), then an\n evar is introduced. Calling [exists_ N] is short for \n [exists __ ... __] with [N] double-underscores. Last,\n [exists_] is equivalent to calling [exists_ N] for\n the appropriate value of [N]. *)\n\nTactic Notation \"exists_original\" constr(T1) :=\n exists T1.\nTactic Notation \"exists\" constr(T1) :=\n match T1 with\n | ltac_wild => esplit\n | _ => exists T1\n end.\nTactic Notation \"exists\" constr(T1) constr(T2) :=\n exists T1; exists T2.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) :=\n exists T1; exists T2; exists T3.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) constr(T4) :=\n exists T1; exists T2; exists T3; exists T4.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) :=\n exists T1; exists T2; exists T3; exists T4; exists T5.\nTactic Notation \"exists\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) constr(T6) :=\n exists T1; exists T2; exists T3; exists T4; exists T5; exists T6.\nTactic Notation \"exists_\" constr(N) :=\n let rec aux N := \n match N with\n | 0 => idtac\n | S ?N' => esplit; aux N'\n end in\n aux N.\nTactic Notation \"exists_\" := \n let N := get_goal_existential_arity in\n exists_ N.\n\n\n(* ********************************************************************** *)\n(** * Tactics to invoke automation *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definitions of automation tactics *)\n\n(** The two following tactics defined the default behaviour of \n \"light automation\" and \"strong automation\". These tactics\n may be redefined at any time using the syntax [Ltac .. ::= ..]. *)\n\n(** [auto_tilde] is the tactic which will be called each time a symbol\n [~] is used after a tactic. *)\n\nLtac auto_tilde := auto.\n\n(** [auto_star] is the tactic which will be called each time a symbol\n [*] is used after a tactic. *)\n\nLtac auto_star := try solve [ auto | intuition eauto ].\n\n(** [auto~] is a notation for tactic [auto_tilde]. It may be followed\n by lemmas (or proofs terms) which auto will be able to use\n for solving the goal. *)\n\nTactic Notation \"auto\" \"~\" :=\n auto_tilde.\nTactic Notation \"auto\" \"~\" constr(E1) :=\n lets: E1; auto_tilde.\nTactic Notation \"auto\" \"~\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_tilde.\nTactic Notation \"auto\" \"~\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_tilde.\n\n(** [auto*] is a notation for tactic [auto_star]. It may be followed\n by lemmas (or proofs terms) which auto will be able to use\n for solving the goal. *)\n\nTactic Notation \"auto\" \"*\" :=\n auto_star.\nTactic Notation \"auto\" \"*\" constr(E1) :=\n lets: E1; auto_star.\nTactic Notation \"auto\" \"*\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_star.\nTactic Notation \"auto\" \"*\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_star.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definitions for parsing compatibility *)\n\nTactic Notation \"f_equal\" :=\n f_equal.\nTactic Notation \"constructor\" := \n constructor.\nTactic Notation \"simple\" :=\n simpl.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Parsing for light automation *)\n\n(** Any tactic followed by the symbol [~] will have [auto_tilde] called\n on all of its subgoals. Three exceptions:\n - [cuts] and [asserts] only call [auto] on their first subgoal,\n - [apply~] relies on [sapply] rather than [apply],\n - [tryfalse~] is defined as [tryfalse by auto_tilde].\n\n Some builtin tactics are not defined using tactic notations \n and thus cannot be extended, e.g. [simpl] and [unfold].\n For these, notation such as [simpl~] will not be available. *)\n\nTactic Notation \"apply\" \"~\" constr(H) :=\n sapply H; auto_tilde.\nTactic Notation \"applys\" \"~\" constr(H) :=\n sapply H; auto_tilde.\nTactic Notation \"apply_clear\" \"~\" constr(H) :=\n apply_clear H; auto_tilde.\nTactic Notation \"applys_clear\" \"~\" constr(H) :=\n applys_clear H; auto_tilde.\n\nTactic Notation \"destruct\" \"~\" constr(H) :=\n destruct H; auto_tilde.\nTactic Notation \"destruct\" \"~\" constr(H) \"as\" simple_intropattern(I) :=\n destruct H as I; auto_tilde.\nTactic Notation \"f_equal\" \"~\" :=\n f_equal; auto_tilde.\nTactic Notation \"induction\" \"~\" constr(H) :=\n induction H; auto_tilde.\nTactic Notation \"inversion\" \"~\" constr(H) :=\n inversion H; auto_tilde.\nTactic Notation \"split\" \"~\" :=\n split; auto_tilde.\nTactic Notation \"subst\" \"~\" :=\n subst; auto_tilde.\nTactic Notation \"right\" \"~\" := \n right; auto_tilde.\nTactic Notation \"left\" \"~\" := \n left; auto_tilde.\nTactic Notation \"constructor\" \"~\" := \n constructor; auto_tilde.\nTactic Notation \"constructors\" \"~\" := \n constructors; auto_tilde.\n\nTactic Notation \"false\" \"~\" :=\n false; auto_tilde.\nTactic Notation \"false\" \"~\" constr(T) :=\n false T by auto_tilde/.\nTactic Notation \"tryfalse\" \"~\" :=\n tryfalse by auto_tilde/.\nTactic Notation \"tryfalse_inv\" \"~\" :=\n first [ tryfalse~ | false_inv ].\n\nTactic Notation \"asserts\" \"~\" simple_intropattern(H) \":\" constr(E) :=\n asserts H: E; [ auto_tilde | idtac ].\nTactic Notation \"cuts\" \"~\" simple_intropattern(H) \":\" constr(E) :=\n cuts H: E; [ auto_tilde | idtac ].\nTactic Notation \"cuts\" \"~\" \":\" constr(E) :=\n cuts: E; [ auto_tilde | idtac ].\n\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) :=\n lets I: E; auto_tilde.\nTactic Notation \"lets\" \"~\" \":\" constr(E1) :=\n lets: E1; auto_tilde.\nTactic Notation \"lets\" \"~\" \":\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_tilde.\nTactic Notation \"lets\" \"~\" \":\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_tilde.\n\nTactic Notation \"applys\" \"~\" constr(E) constr(A) :=\n applys E A; auto_tilde.\nTactic Notation \"specializes\" \"~\" hyp(H) constr(A) :=\n specializes H A; auto_tilde.\n\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) constr(A) :=\n lets I: E A; auto_tilde.\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) :=\n lets I: E A1 A2; auto_tilde.\nTactic Notation \"lets\" \"~\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) constr(A3) :=\n lets I: E A1 A2 A3; auto_tilde.\n\nTactic Notation \"forwards\" \"~\" simple_intropattern(I) \":\" constr(E) :=\n forwards I: E; auto_tilde. \nTactic Notation \"forwards\" \"~\" \":\" constr(E) := \n forwards: E; auto_tilde. \n\nTactic Notation \"fapply\" \"~\" constr(E) := \n fapply E; auto_tilde.\nTactic Notation \"sapply\" \"~\" constr(E) :=\n sapply E; auto_tilde.\n\nTactic Notation \"intros_all\" \"~\" :=\n intros_all; auto_tilde.\n\nTactic Notation \"unfolds\" \"~\" reference(F1) :=\n unfolds F1; auto_tilde.\nTactic Notation \"unfolds\" \"~\" reference(F1) reference(F2) :=\n unfolds F1, F2; auto_tilde.\nTactic Notation \"unfolds\" \"~\" reference(F1) reference(F2) reference(F3) :=\n unfolds F1, F2, F3; auto_tilde.\nTactic Notation \"unfolds\" \"~\" reference(F1) reference(F2) reference(F3) \n reference(F4) :=\n unfolds F1, F2, F3, F4; auto_tilde.\n\nTactic Notation \"simple\" \"~\" :=\n simpl; auto_tilde.\nTactic Notation \"simple\" \"~\" \"in\" hyp(H) :=\n simpl in H; auto_tilde.\nTactic Notation \"simpls\" \"~\" :=\n simpls; auto_tilde.\nTactic Notation \"substs\" \"~\" :=\n substs; auto_tilde.\n\nTactic Notation \"rewrite\" \"~\" constr(E) :=\n rewrite E; auto_tilde.\nTactic Notation \"rewrite\" \"~\" \"<-\" constr(E) :=\n rewrite <- E; auto_tilde.\nTactic Notation \"rewrite\" \"~\" constr(E) \"in\" hyp(H) :=\n rewrite E in H; auto_tilde.\nTactic Notation \"rewrite\" \"~\" \"<-\" constr(E) \"in\" hyp(H) :=\n rewrite <- E in H; auto_tilde.\n\nTactic Notation \"rewrite_all\" \"~\" constr(E) :=\n rewrite_all E; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" \"<-\" constr(E) :=\n rewrite_all <- E; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" constr(E) \"in\" ident(H) :=\n rewrite_all E in H; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" \"<-\" constr(E) \"in\" ident(H) :=\n rewrite_all <- E in H; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" constr(E) \"in\" \"*\" :=\n rewrite_all E in *; auto_tilde.\nTactic Notation \"rewrite_all\" \"~\" \"<-\" constr(E) \"in\" \"*\" :=\n rewrite_all <- E in *; auto_tilde.\n\nTactic Notation \"asserts_rewrite\" \"~\" constr(E) :=\n asserts_rewrite E; auto_tilde.\nTactic Notation \"asserts_rewrite\" \"~\" \"<-\" constr(E) :=\n asserts_rewrite <- E; auto_tilde.\nTactic Notation \"asserts_rewrite\" \"~\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite E in H; auto_tilde.\nTactic Notation \"asserts_rewrite\" \"~\" \"<-\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite <- E in H; auto_tilde.\n\nTactic Notation \"cuts_rewrite\" \"~\" constr(E) :=\n cuts_rewrite E; auto_tilde.\nTactic Notation \"cuts_rewrite\" \"~\" \"<-\" constr(E) :=\n cuts_rewrite <- E; auto_tilde.\nTactic Notation \"cuts_rewrite\" \"~\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite E in H; auto_tilde.\nTactic Notation \"cuts_rewrite\" \"~\" \"<-\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite <- E in H; auto_tilde.\n\nTactic Notation \"fequal\" \"~\" :=\n fequal; auto_tilde.\nTactic Notation \"fequals\" \"~\" :=\n fequals; auto_tilde.\n\nTactic Notation \"invert\" \"~\" hyp(H) :=\n invert H; auto_tilde.\nTactic Notation \"inverts\" \"~\" hyp(H) :=\n inverts H; auto_tilde.\nTactic Notation \"injects\" \"~\" hyp(H) :=\n injects H; auto_tilde.\nTactic Notation \"inversions\" \"~\" hyp(H) :=\n inversions H; auto_tilde.\n\nTactic Notation \"case_if\" \"~\" :=\n case_if; auto_tilde.\nTactic Notation \"case_if\" \"~\" \"in\" hyp(H) :=\n case_if in H; auto_tilde. \n\nTactic Notation \"decides_equality\" \"~\" :=\n decides_equality; auto_tilde.\n\nTactic Notation \"splits\" \"~\" :=\n splits; auto_tilde.\nTactic Notation \"splits\" \"~\" constr(N) := \n splits N; auto_tilde.\n\nTactic Notation \"destructs\" \"~\" constr(T) :=\n destructs T; auto_tilde.\nTactic Notation \"destructs\" \"~\" constr(N) constr(T) :=\n destructs N T; auto_tilde.\n\nTactic Notation \"branch\" \"~\" constr(N) :=\n branch N; auto_tilde.\nTactic Notation \"branch\" \"~\" constr(K) \"of\" constr(N) :=\n branch K of N; auto_tilde.\n\nTactic Notation \"branches\" \"~\" constr(T) :=\n branches T; auto_tilde.\nTactic Notation \"branches\" \"~\" constr(N) constr(T) :=\n branches N T; auto_tilde.\n\nTactic Notation \"exists_\" \"~\" :=\n exists_; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) :=\n exists T1; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) :=\n exists T1 T2; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) :=\n exists T1 T2 T3; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) constr(T4) :=\n exists T1 T2 T3 T4; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) :=\n exists T1 T2 T3 T4 T5; auto_tilde.\nTactic Notation \"exists\" \"~\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) constr(T6) :=\n exists T1 T2 T3 T4 T5 T6; auto_tilde.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Parsing for strong automation *)\n\n(** Any tactic followed by the symbol [*] will have [auto*] called\n on all of its subgoals. The exceptions to these rules are the\n same as for light automation. \n\n Exception: use [subs*] instead of [subst*] if you \n import the library [Coq.Classes.Equivalence]. *)\n\nTactic Notation \"apply\" \"*\" constr(H) :=\n sapply H; auto_star.\nTactic Notation \"applys\" \"*\" constr(H) :=\n sapply H; auto_star.\nTactic Notation \"apply_clear\" \"*\" constr(H) :=\n applys_clear H; auto_star.\nTactic Notation \"applys_clear\" \"*\" constr(H) :=\n applys_clear H; auto_star.\n\nTactic Notation \"destruct\" \"*\" constr(H) :=\n destruct H; auto_star.\nTactic Notation \"destruct\" \"*\" constr(H) \"as\" simple_intropattern(I) :=\n destruct H as I; auto_star.\nTactic Notation \"f_equal\" \"*\" :=\n f_equal; auto_star.\nTactic Notation \"induction\" \"*\" constr(H) :=\n induction H; auto_star.\nTactic Notation \"inversion\" \"*\" constr(H) :=\n inversion H; auto_star.\nTactic Notation \"split\" \"*\" :=\n split; auto_star.\nTactic Notation \"subs\" \"*\" :=\n subst; auto_star.\nTactic Notation \"subst\" \"*\" :=\n subst; auto_star.\nTactic Notation \"right\" \"*\" := \n right; auto_star.\nTactic Notation \"left\" \"*\" := \n left; auto_star.\nTactic Notation \"constructor\" \"*\" := \n constructor; auto_star.\nTactic Notation \"constructors\" \"*\" := \n constructors; auto_star.\n\nTactic Notation \"false\" \"*\" :=\n false; auto_star.\nTactic Notation \"false\" \"*\" constr(T) :=\n false T by auto_star/.\nTactic Notation \"tryfalse\" \"*\" :=\n tryfalse by auto_star/.\nTactic Notation \"tryfalse_inv\" \"*\" :=\n first [ tryfalse* | false_inv ].\n\nTactic Notation \"asserts\" \"*\" simple_intropattern(H) \":\" constr(E) :=\n asserts H: E; [ auto_star | idtac ].\nTactic Notation \"cuts\" \"*\" simple_intropattern(H) \":\" constr(E) :=\n cuts H: E; [ auto_star | idtac ].\nTactic Notation \"cuts\" \"*\" \":\" constr(E) :=\n cuts: E; [ auto_star | idtac ].\n\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) :=\n lets I: E; auto_star.\nTactic Notation \"lets\" \"*\" \":\" constr(E1) :=\n lets: E1; auto_star.\nTactic Notation \"lets\" \"*\" \":\" constr(E1) constr(E2) :=\n lets: E1 E2; auto_star.\nTactic Notation \"lets\" \"*\" \":\" constr(E1) constr(E2) constr(E3) :=\n lets: E1 E2 E3; auto_star.\n\nTactic Notation \"applys\" \"*\" constr(E) constr(A) :=\n applys E A; auto_star.\nTactic Notation \"specializes\" \"*\" hyp(H) constr(A) :=\n specializes H A; auto_star.\n\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) constr(A) :=\n lets I: E A; auto_star.\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) :=\n lets I: E A1 A2; auto_star.\nTactic Notation \"lets\" \"*\" simple_intropattern(I) \":\" constr(E) constr(A1) constr(A2) constr(A3) :=\n lets I: E A1 A2 A3; auto_star.\n\nTactic Notation \"forwards\" \"*\" simple_intropattern(I) \":\" constr(E) :=\n forwards I: E; auto_star. \nTactic Notation \"forwards\" \"*\" \":\" constr(E) := \n forwards: E; auto_star. \n\nTactic Notation \"fapply\" \"*\" constr(E) := \n fapply E; auto_star.\nTactic Notation \"sapply\" \"*\" constr(E) :=\n sapply E; auto_star.\n\nTactic Notation \"intros_all\" \"*\" :=\n intros_all; auto_star.\n\nTactic Notation \"unfolds\" \"*\" reference(F1) :=\n unfolds F1; auto_star.\nTactic Notation \"unfolds\" \"*\" reference(F1) reference(F2) :=\n unfolds F1, F2; auto_star.\nTactic Notation \"unfolds\" \"*\" reference(F1) reference(F2) reference(F3) :=\n unfolds F1, F2, F3; auto_star.\nTactic Notation \"unfolds\" \"*\" reference(F1) reference(F2) reference(F3) \n reference(F4) :=\n unfolds F1, F2, F3, F4; auto_star.\n\nTactic Notation \"simple\" \"*\" :=\n simpl; auto_star.\nTactic Notation \"simple\" \"*\" \"in\" hyp(H) :=\n simpl in H; auto_star.\nTactic Notation \"simpls\" \"*\" :=\n simpls; auto_star.\nTactic Notation \"substs\" \"*\" :=\n substs; auto_star.\n\nTactic Notation \"rewrite\" \"*\" constr(E) :=\n rewrite E; auto_star.\nTactic Notation \"rewrite\" \"*\" \"<-\" constr(E) :=\n rewrite <- E; auto_star.\nTactic Notation \"rewrite\" \"*\" constr(E) \"in\" hyp(H) :=\n rewrite E in H; auto_star.\nTactic Notation \"rewrite\" \"*\" \"<-\" constr(E) \"in\" hyp(H) :=\n rewrite <- E in H; auto_star.\n\nTactic Notation \"rewrite_all\" \"*\" constr(E) :=\n rewrite_all E; auto_star.\nTactic Notation \"rewrite_all\" \"*\" \"<-\" constr(E) :=\n rewrite_all <- E; auto_star.\nTactic Notation \"rewrite_all\" \"*\" constr(E) \"in\" ident(H) :=\n rewrite_all E in H; auto_star.\nTactic Notation \"rewrite_all\" \"*\" \"<-\" constr(E) \"in\" ident(H) :=\n rewrite_all <- E in H; auto_star.\nTactic Notation \"rewrite_all\" \"*\" constr(E) \"in\" \"*\" :=\n rewrite_all E in *; auto_star.\nTactic Notation \"rewrite_all\" \"*\" \"<-\" constr(E) \"in\" \"*\" :=\n rewrite_all <- E in *; auto_star.\n\nTactic Notation \"asserts_rewrite\" \"*\" constr(E) :=\n asserts_rewrite E; auto_star.\nTactic Notation \"asserts_rewrite\" \"*\" \"<-\" constr(E) :=\n asserts_rewrite <- E; auto_star.\nTactic Notation \"asserts_rewrite\" \"*\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite E; auto_star.\nTactic Notation \"asserts_rewrite\" \"*\" \"<-\" constr(E) \"in\" hyp(H) :=\n asserts_rewrite <- E; auto_star.\n\nTactic Notation \"cuts_rewrite\" \"*\" constr(E) :=\n cuts_rewrite E; auto_star.\nTactic Notation \"cuts_rewrite\" \"*\" \"<-\" constr(E) :=\n cuts_rewrite <- E; auto_star.\nTactic Notation \"cuts_rewrite\" \"*\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite E in H; auto_star.\nTactic Notation \"cuts_rewrite\" \"*\" \"<-\" constr(E) \"in\" hyp(H) :=\n cuts_rewrite <- E in H; auto_star.\n\nTactic Notation \"fequal\" \"*\" :=\n fequal; auto_star.\nTactic Notation \"fequals\" \"*\" :=\n fequals; auto_star.\n\nTactic Notation \"invert\" \"*\" hyp(H) :=\n invert H; auto_star.\nTactic Notation \"inverts\" \"*\" hyp(H) :=\n inverts H; auto_star.\nTactic Notation \"injects\" \"*\" hyp(H) :=\n injects H; auto_star.\nTactic Notation \"inversions\" \"*\" hyp(H) :=\n inversions H; auto_star.\n\nTactic Notation \"case_if\" \"*\" :=\n case_if; auto_star.\nTactic Notation \"case_if\" \"*\" \"in\" hyp(H) :=\n case_if in H; auto_star. \n \nTactic Notation \"decides_equality\" \"*\" :=\n decides_equality; auto_star.\n\nTactic Notation \"splits\" \"*\" :=\n splits; auto_star.\nTactic Notation \"splits\" \"*\" constr(N) := \n splits N; auto_star.\n\nTactic Notation \"destructs\" \"*\" constr(T) :=\n destructs T; auto_star.\nTactic Notation \"destructs\" \"*\" constr(N) constr(T) :=\n destructs N T; auto_star.\n\nTactic Notation \"branch\" \"*\" constr(N) :=\n branch N; auto_star.\nTactic Notation \"branch\" \"*\" constr(K) \"of\" constr(N) :=\n branch K of N; auto_star.\n\nTactic Notation \"branches\" \"*\" constr(T) :=\n branches T; auto_star.\nTactic Notation \"branches\" \"*\" constr(N) constr(T) :=\n branches N T; auto_star.\n\nTactic Notation \"exists_\" \"*\" :=\n exists_; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) :=\n exists T1; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) :=\n exists T1 T2; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) :=\n exists T1 T2 T3; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) constr(T4) :=\n exists T1 T2 T3 T4; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) :=\n exists T1 T2 T3 T4 T5; auto_star.\nTactic Notation \"exists\" \"*\" constr(T1) constr(T2) constr(T3) constr(T4) \n constr(T5) constr(T6) :=\n exists T1 T2 T3 T4 T5 T6; auto_star.\n\n\n\n(* ********************************************************************** *)\n(** * Tactics to sort out the proof context *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Sorting hypotheses *)\n\n(** [sort] sorts out hypotheses from the context by moving all the\n propositions (hypotheses of type Prop) to the bottom of the context. *)\n\nLtac sort_tactic :=\n match goal with H: ?T |- _ =>\n match type of T with Prop =>\n generalizes H; (try sort_tactic); intro\n end end.\n\nTactic Notation \"sort\" :=\n sort_tactic.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Clearing hypotheses *)\n\n(** [clears X1 ... XN] is a variation on [clear] which clears\n the variables [X1]..[XN] as well as all the hypotheses which\n depend on them. Contrary to [clear], it never fails. *)\n\nTactic Notation \"clears\" ident(X1) :=\n let rec doit _ :=\n match goal with \n | H:context[X1] |- _ => clear H; try (doit tt)\n | _ => clear X1\n end in doit tt.\nTactic Notation \"clears\" ident(X1) ident(X2) :=\n clears X1; clears X2.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) :=\n clears X1; clears X2; clear X3.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) ident(X4) :=\n clears X1; clears X2; clear X3; clear X4.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) ident(X4) \n ident(X5) :=\n clears X1; clears X2; clear X3; clear X4; clear X5.\nTactic Notation \"clears\" ident(X1) ident(X2) ident(X3) ident(X4)\n ident(X5) ident(X6) :=\n clears X1; clears X2; clear X3; clear X4; clear X5; clear X6.\n\n(** [clears] (without any argument) clears all the unused variables\n from the context. In other words, it removes any variable\n which is not a proposition (i.e. not of type Prop) and which \n does not appear in another hypothesis nor in the goal. *)\n\nLtac clears_tactic :=\n match goal with H: ?T |- _ =>\n match type of T with \n | Prop => generalizes H; (try clears_tactic); intro\n | ?TT => clear H; (try clears_tactic)\n | ?TT => generalizes H; (try clears_tactic); intro\n end end.\n\nTactic Notation \"clears\" :=\n clears_tactic.\n\n(** [clear_last] clears the last hypothesis in the context.\n [clear_last N] clears the last [N] hypothesis in the context. *)\n\nTactic Notation \"clear_last\" := \n match goal with H: ?T |- _ => clear H end.\n\nLtac clear_last_base n :=\n match n with\n | 0 => idtac\n | S ?p => clear_last; clear_last_base p\n end.\n\nTactic Notation \"clear_last\" constr(n) := \n clear_last_base n.\n\n\n(* ********************************************************************** *)\n(** * Tactics for development purposes *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Skipping subgoals *)\n\n(** The [skip] tactic can be used at any time to admit the current\n goal. Using [skip] is much more efficient than using the [Focus] \n top-level command to reach a particular subgoal. \n\n There are two possible implementations of [skip]. The first one \n relies on the use of an existential variable. The second one \n relies on an axiom of type [False]. Remark that the builtin tactic\n [admit] is not applicable if the current goal contains uninstantiated\n variables.\n \n The advantage of the first technique is that a proof using [skip]\n must end with [Admitted], since [Qed] will be rejected with the message\n \"[uninstantiated existential variables]\". It is thereafter clear \n that the development is incomplete.\n \n The advantage of the second technique is exactly the converse: one \n may conclude the proof using [Qed], and thus one saves the pain from\n renaming [Qed] into [Admitted] and vice-versa all the time.\n Note however, that it is still necessary to instantiate all the existential\n variables introduced by other tactics in order for [Qed] to be accepted.\n\n The two implementation are provided, so that you can select the one that\n suits you best. By default [skip'] uses the first implementation, and \n [skip] uses the second implementation.\n*)\n\nLtac skip_with_existential :=\n match goal with |- ?G => \n let H := fresh in evar(H:G); eexact H end.\n\nVariable skip_axiom : False. \nLtac skip_with_axiom :=\n assert False; [ apply skip_axiom | contradiction ]. \n (* todo: apply False_rect skip_axim *)\n\nTactic Notation \"skip\" := \n skip_with_axiom. \nTactic Notation \"skip'\" := \n skip_with_existential. \n\n(** [skip H: T] adds an assumption named [H] of type [T] to the \n current context, blindly assuming that it is true.\n [skip: T] and [skip H_asserts: T] and [skip_asserts: T] \n are other possible syntax. \n Note that H may be an intro pattern. \n The syntax [skip H1 .. HN: T] can be used when [T] is a \n conjunction of [N] items. *)\n\nTactic Notation \"skip\" simple_intropattern(I) \":\" constr(T) :=\n asserts I: T; [ skip | ]. \nTactic Notation \"skip\" \":\" constr(T) :=\n let H := fresh in skip H: T. \n\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) \":\" constr(T) :=\n skip [I1 I2]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3) \":\" constr(T) :=\n skip [I1 [I2 I3]]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) \":\" constr(T) :=\n skip [I1 [I2 [I3 I4]]]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5) \":\" constr(T) :=\n skip [I1 [I2 [I3 [I4 I5]]]]: T.\nTactic Notation \"skip\" simple_intropattern(I1)\n simple_intropattern(I2) simple_intropattern(I3)\n simple_intropattern(I4) simple_intropattern(I5)\n simple_intropattern(I6) \":\" constr(T) :=\n skip [I1 [I2 [I3 [I4 [I5 I6]]]]]: T.\n\nTactic Notation \"skip_asserts\" simple_intropattern(I) \":\" constr(T) :=\n skip I: T.\nTactic Notation \"skip_asserts\" \":\" constr(T) :=\n skip: T. \n\n(** [skip_cuts T] simply replaces the current goal with [T]. *)\n\nTactic Notation \"skip_cuts\" constr(T) :=\n cuts: T; [ skip | ]. \n\n(** [skip_goal H] applies to any goal. It simply assumes\n the current goal to be true. The assumption is named \"H\".\n It is useful to set up proof by induction or coinduction.\n Syntax [skip_goal] is also accepted.*)\n\nTactic Notation \"skip_goal\" ident(H) :=\n match goal with |- ?G => skip H: G end.\n\nTactic Notation \"skip_goal\" :=\n let IH := fresh \"IH\" in skip_goal IH.\n\n(** [skip_rewrite T] can be applied when [T] is an equality.\n It blindly assumes this equality to be true, and rewrite it in\n the goal. *)\n\nTactic Notation \"skip_rewrite\" constr(T) :=\n let M := fresh in skip_asserts M: T; rewrite M; clear M.\n\n(** [skip_rewrite T in H] is similar as [rewrite_skip], except that\n it rewrites in hypothesis [H]. *)\n\nTactic Notation \"skip_rewrite\" constr(T) \"in\" hyp(H) :=\n let M := fresh in skip_asserts M: T; rewrite M in H; clear M.\n\n(** [skip_rewrites_all T] is similar as [rewrite_skip], except that\n it rewrites everywhere (goal and all hypotheses). *)\n\nTactic Notation \"skip_rewrite_all\" constr(T) :=\n let M := fresh in skip_asserts M: T; rewrite_all M; clear M.\n\n(** [skip_induction E] applies to any goal. It simply assumes\n the current goal to be true (the assumption is named \"IH\" by\n default), and call [destruct E] instead of [induction E]. \n It is useful to try and set up a proof by induction\n first, and fix the applications of the induction hypotheses\n during a second pass on the proof. *)\n\nTactic Notation \"skip_induction\" constr(E) :=\n let IH := fresh \"IH\" in skip_goal IH; destruct E.\n\n(* TODO: why needed? *)\nTactic Notation \"apply\" \"*\" constr(H) :=\n sapply H; auto_star.\n", "meta": {"author": "cmcl", "repo": "msci", "sha": "06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9", "save_path": "github-repos/coq/cmcl-msci", "path": "github-repos/coq/cmcl-msci/msci-06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9/Coq Developments/jar12/lib/LibTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.13477590873473297, "lm_q1q2_score": 0.06213395537377722}} {"text": "(*|\n##########################################################\nWhy would the tactic ``exact`` be complete for Coq proofs?\n##########################################################\n\n:Link: https://stackoverflow.com/q/46386249\n|*)\n\n(*|\nQuestion\n********\n\nIn the question `Is there a minimal complete set of tactics in Coq?\n`__,\nthe answers mentioned that ``exact`` would be enough to prove all\ngoals. Could someone explain and give an example? For example, how\nwould the goal ``A \\/ B -> B \\/ A`` with ``A``, ``B`` being ``Prop``\nbe proven by merely a bunch of ``exact``? If you have other better\nexamples, please don't hesitate to answer as well. The point is to\ngive some explanation on this issue and give a non-trivial example.\n|*)\n\n(*|\nAnswer (ejgallego)\n******************\n\nRecall that proofs in Coq are just terms in the (lambda) Calculus of\nInductive Constructions. Thus, your lemma is proven as:\n|*)\n\nLemma test A B : A \\/ B -> B \\/ A.\nProof.\n exact (fun x => match x with\n | or_introl p => or_intror p\n | or_intror p => or_introl p\n end).\nQed.\n\n(*| which is almost the same as: |*)\n\nDefinition test' A B : A \\/ B -> B \\/ A :=\n fun x => match x with\n | or_introl p => or_intror p\n | or_intror p => or_introl p\n end.\n\n(*|\n[they differ in \"opacity\", don't worry about that, but Coq 8.8 will\nlikely support the ``Lemma foo := term`` syntax, closer to ``exact\nterm``.]\n\nA more convenient tactic to build proofs is ``refine``, which allows\nyou to specify partial terms:\n|*)\n\nLemma test'' A B : A \\/ B -> B \\/ A.\nProof.\n refine (fun x => _).\n refine (match x with | or_introl _ => _ | or_intror _ => _ end).\n - refine (or_intror a).\n - refine (or_introl b).\nQed.\n\n(*|\nIn fact, ``refine`` is the basic tactic of the Coq proof engine;\n``exact T`` basically executes ``refine T`` and checks that no goals\nremain open.\n|*)\n\n(*|\nAnswer (Yves)\n*************\n\nBecause of its theoretical foundations, the logic of Coq does not rely\non tactics as a primitive way to construct proofs. In fact, you could\nuse Coq and construct what would be considered as legitimate proofs\nwithout ever using any tactic by using the idiom.\n|*)\n\nLemma test3 A B : A \\/ B -> B \\/ A.\nProof.\n exact (fun x => match x with\n | or_introl p => or_intror p\n | or_intror p => or_introl p\n end).\nQed.\n\n(*|\nSo the question of \"complete set of tactics\" is not completely\nmeaningful.\n\nOn the other hand, tactics have been introduced to make the work\neasier. So it is useful to know a *reasonably complete set of tactics*\nthat makes it possible to perform proofs without having a thorough\nknowledge of Coq's theoretical foundations. My favorite set of tactics\nis:\n\n- ``intros``, ``apply`` (to deal with universal quantification and\n implication);\n- ``destruct`` (to deal with logical connectives ``and``, also written\n ``/\\`` and ``or``, also written ``\\/``, and existential\n quantification, when in hypotheses);\n- ``split`` to deal with ``and`` when in a goal's conclusion;\n- ``left``, ``right`` to deal with ``or`` when in a goal's conclusion;\n- ``exists`` to deal with an existential quantification when in the\n conclusion;\n- ``assert`` to establish intermediate facts (not needed for\n completeness, but it really helps you write more readable proofs);\n- ``exact`` and ``assumption`` when what you want to prove is really\n obvious from the context.\n\nWhen reasoning about natural numbers, you will undoubtedly define\nfunctions by pattern-matching and recursively and reason about their\nbehavior, so it is important to also know the tactics ``change``,\n``simpl``, ``case``, ``case_eq``, ``injection``, and ``discriminate``.\nLast, when you start making proofs that are advanced enough you need\ntools for automated proofs like ``ring`` and ``lia``.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/why-would-the-tactic-exact-be-complete-for-coq-proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1259227615549033, "lm_q1q2_score": 0.06197768925452213}} {"text": "(*|\n############################################\nUsing typeclass instances within typeclasses\n############################################\n\n:Link: https://stackoverflow.com/q/44638611\n|*)\n\n(*|\nQuestion\n********\n\nI am trying to define two instances of a type class, one of which will\nuse the other's instance. However, unless I bind the function's name\noutside of the second definition Coq is unable to determine it should\nuse the type class instance from ``bexp`` (take a look at the comment\nfor dirty hack). Is there a way to avoid this sort of hack in Coq?\n|*)\n\nClass Compilable (A : Type) := { compile : A -> bool }.\n\nDefinition bexp := False. (* .none *)\nInductive cexp : Type :=\n| CAnd : cexp -> cexp -> cexp\n| COr : cexp -> cexp -> cexp\n| CProp : bexp -> cexp.\n\nInstance : Compilable bexp :=\n { compile :=\n fix compile b :=\n match b with\n (* elided *)\n end\n }.\n\nDefinition compile2 := compile.\n\nRequire Import Coq.Bool.Bool. (* .none *)\nInstance: Compilable cexp :=\n { compile :=\n fix compile c :=\n match c with\n | CAnd x y => compile x && compile y\n | COr x y => compile x || compile y\n | CProp e => compile2 e (* <-- dirty hack *)\n end\n }.\n\n(*|\nAnswer\n******\n\nThis can be fixed if we replace ``compile`` with some other name\n(``rec``) like so:\n|*)\n\nInstance : Compilable cexp :=\n { compile :=\n fix rec c :=\n match c with\n | CAnd x y => rec x && rec y\n | COr x y => rec x || rec y\n | CProp e => compile e\n end\n }.\n\n(*|\nIn this comment the OP pointed out that Haskell easily deals with this\nsituation. To understand the reason why Coq does not do it let us take\na look at the type of ``compile``:\n|*)\n\nAbout compile. (* .unfold *)\n\n(*|\nWe can see that Coq is more explicit about how typeclasses work. When\nyou call ``compile e`` Coq sort of inserts placeholders standing for\nthe implicit arguments like so ``@compile _ _ e`` (see `these slides\n`__,\npages 21-25 for more detail). But with ``fix compile c`` you shadowed\nthe previous binding, hence the type error.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/using-typeclass-instances-within-typeclasses.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.06144250623015629}} {"text": "(*|\n#########################################\nFail to use let-destruct for tuple in Coq\n#########################################\n\n:Link: https://stackoverflow.com/q/30197166\n|*)\n\n(*|\nQuestion\n********\n\nI'm a new user for Coq. I have defined some functions:\n|*)\n\nDefinition p (a : nat) := (a + 1, a + 2, a + 3).\n\nFail Definition q :=\n let (s, r, t) := p 1 in\n s + r + t.\n\nDefinition q' :=\n match p 1 with\n | (s, r, t) => s + r + t\n end.\n\n(*|\nI'm trying to destruct the result of ``p`` into a tuple\nrepresentation. However coqc complains on ``q``:\n|*)\n\nFail Definition q :=\n let (s, r, t) := p 1 in\n s + r + t. (* .unfold .messages *)\n\n(*|\nwhile ``q'`` can pass the compilation. If I change ``p`` to return a\npair ``(a + 1, a + 2)``, the corresponding ``q`` and ``q'`` both work\nfine.\n\n**Why let-destruct only allows pair? Or have I made any error in\nsyntax?** I've checked with Coq manual but found no clue.\n|*)\n\n(*|\nAnswer\n******\n\nWhat is a bit confusing in Coq is that there are *two* different forms\nof destructing let. The one you are looking for needs a quote before\nthe pattern:\n|*)\n\nReset Initial. (* .none *)\nDefinition p (a : nat) := (a + 1, a + 2, a + 3).\n\nDefinition q :=\n let '(s, r, t) := p 1 in\n s + r + t.\n\n(*|\nPrefixing the pattern with a quote allows you to use nested patterns\nand use user-defined notations in them. The form without the quote\nonly works with one-level patterns, and doesn't allow you to use\nnotations, or refer to constructor names in your patterns.\n\n----\n\n**Q:** So the 3-member tuple should be regarded as destructing again\non the first member of pair, then I have to use 'quote'?\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/fail-to-use-let-destruct-for-tuple-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.13117323225300484, "lm_q1q2_score": 0.060982641796548394}} {"text": "(**\n<<\n Lecture 2: Fundamentals of Coq\n -------------------------------------------------------------\n Anders Mörtberg (Carnegie Mellon University)\n>>\nThe Coq proof assistant is a programming language for writing\nproofs: https://coq.inria.fr/\n\nIt has been around since 1984 and was initially implemented by Thierry\nCoquand and his PhD supervisor Gérard Huet. The first version, called\nCoC, implemented the Calculus of Constructions as presented in:\n\n\"The Calculus of Constructions\".\nThierry Coquand, Gérard Huet,\nInformation and Computation (1988). 76(2–3): 95–120.\n\nIt was later extended to the Calculus of Inductive Constructions and\nthe name changed to Coq. These type theories are similar to Martin-Löf\ntype theory, but there are some differences that I won't have time to\nget into. As Coq is supposed to be a programming language for\ndeveloping proofs all programs have to be terminating, so it can be\nseen as a \"total\" programming language.\n\nThe Coq system has a very long and detailed reference manual:\n\nhttps://coq.inria.fr/distrib/current/refman/\n\nHowever, UniMath is only using a subset of Coq. So there is a lot of\ninformation that is not relevant for UniMath development in there. The\nfragment of Coq that UniMath uses consists of:\n\n- Pi-types (with judgmental eta)\n- Sigma-types (with judgmental eta/surjective pairing)\n- Some inductive types: natural numbers, booleans, unit, empty\n- Coproduct types\n- A universe UU\n\nThe reason we only have one universe is that there is no support for\nuniverse resizing axioms in Coq yet. Because of this we assume the\ninconsistent rule UU : UU, but we are working on improving this so\nthat we can make use of Coq's universe consistency\nchecker. Furthermore, the reason UniMath only relies on this subset is\nthat everything in UniMath has to be motivated by the model in\nsimplicial sets.\n\nIn this lecture I will show some things than can be done in UniMath if\nit is viewed as a programming language. In the later lectures we will\nalso see how to actually prove properties about definitions and\nprograms. The UniMath library can be found at:\n\nhttps://github.com/UniMath/UniMath\n\nThis whole file is a Coq file and it hence has the file ending \".v\" (v\nfor vernacular) and can be processed using:\n\n- emacs with proof-general: https://proofgeneral.github.io/\n\n- Coq IDE\n\nI use emacs as it is also an extremely powerful text editor, but if\nyou never saw emacs before it might be quite overwhelming. If so I\nthink Coq IDE (interactive development environment) might be easier to\nget started with and it has some features that emacs doesn't have so\nsome Coq experts use it as well. But in this talk I will use emacs.\n\nIn order to make emacs interact with Coq one should install Proof\nGeneral. This is an extension to emacs that enables it to interact\nwith a range of proof assistants, including Coq. For UniMath\ndevelopment one should also install agda-mode in order to be able to\nproperly insert unicode characters.\n\nThe basic keybinding that I use when working in Proof General are:\n<<\nC-c C-n -- Process one line\nC-c C-u -- Unprocess a line\nC-c C-ENTER -- Process the whole buffer until where the cursor is\nC-c C-b -- Process the whole file\nC-c C-r -- Unprocess (retract) the whole file\nC-x C-c -- Kill Coq process\n>>\nFor more commands see:\n\nhttps://proofgeneral.github.io/doc/master/userman/Basic-Script-Management/#Script-processing-commands\nhttps://proofgeneral.github.io/doc/master/userman/Coq-Proof-General/#Coq_002dspecific-commands\n\nHere C = CTRL and M = ALT on a standard emacs setup, so \"C-c C-n\"\nmeans \"press c while holding CTRL and then press n while still holding\nCTRL\" (note that the keybindings are case sensitive). ENTER is the\n\"return\" key on my keyboard.\n\nVarious basic emacs commands:\n<<\nC-x C-f -- Find file\nC-x C-s -- Save file\nC-x C-x -- Exit emacs\nC-x b -- Kill buffer\nC-_ -- Undo\nC-x 1 -- Maximize buffer\nC-x 2 -- Split buffer horizontally\nC-x 3 -- Split buffer vertically\nM-% -- Search-and-replace\nM-; -- Comment region\n>>\nFor more commands see: https://www.gnu.org/software/emacs/ (or just\nGoogle \"emacs tutorial\")\n\n*)\n\n(** To import a file write:\n<<\nRequire Import Dir.Filename.\n>>\n*)\n\n(**\n\nThis will import the file Filename in the directory Dir. This assumes\nthat directory Dir is visible to Coq, that is, in the list of\ndirectories in which Coq looks for files to import. If you are working\nin the UniMath directory this Coq will be able to find all of the\nfiles in the UniMath library, but if you are in another directory you\nneed to the update your LoadPath by running (where \"/path/to/UniMath/\"\nis replaced to the path where UniMath is located on your computer):\n<<\nAdd LoadPath \"/path/to/UniMath\".\n>>\n\nCoq has a quite fancy module system which allows you to import and\nexport definitions in various complicated ways. We extremely rarely\nuse this in UniMath so you can safely ignore it for now. The only\nthing you need to know is that there is an alternative to Require\nImport:\n<<\nRequire Export Dir.Filename.\n>>\nthat is used in some files. This will make the file your working on\nimport all of the definitions in Dir.Filename and then export them\nagain so that any file that imports this file also gets the\ndefinitions in Dir.Filename. I personally only use Require Import.\n\n*)\n\nRequire Import UniMath.Foundations.Preamble.\n\n(** * Definitions, lambda terms *)\n\n(** The polymorphic identity function *)\nDefinition idfun : forall (A : UU), A -> A := fun (A : UU) (a : A) => a.\n\n(** forall = Pi *)\n(** fun = lambda *)\n\nCheck idfun.\nPrint idfun.\n\nDefinition idfun' (A : UU) (a : A) : A := a.\n\nCheck idfun'.\nPrint idfun'.\n\n(** The constant function that returns its first argument *)\nDefinition const (A B : UU) (a : A) (b : B) : A := a.\n\n(** The booleans come from the Coq standard library *)\nAbout bool.\nPrint bool.\n\n(** These are generated by true and false *)\nCheck true.\nCheck false.\n\n(** They also come with an induction principle *)\nAbout bool_rect.\n\n(** Using this we can define a \"recursion\" principle *)\nDefinition ifbool (A : UU) (x y : A) : bool -> A :=\n bool_rect (fun _ : bool => A) x y.\n\n(** We can define boolean negation: *)\nDefinition negbool : bool -> bool :=\n ifbool bool false true.\n\n(** and compute with it *)\nEval compute in negbool true.\n\n(** Coq supports many evaluation strategies, like cbn and cbv, for\ndetails see:\n\nhttps://coq.inria.fr/refman/tactics.html#Conversion-tactics\n\n*)\n\n(** boolean and *)\nDefinition andbool (b : bool) : bool -> bool :=\n ifbool (bool -> bool) (idfun bool) (const bool bool false) b.\n\nEval compute in andbool true true.\nEval compute in andbool true false.\nEval compute in andbool false true.\nEval compute in andbool false false.\n\n(** Exercise: define boolean or:\n\nDefinition orbool : bool -> bool -> bool :=\n\n*)\n\n(** The natural numbers do no longer come from the Coq standard library (as of 2018) *)\nAbout nat.\nPrint nat.\n\n(** They are defined as Peano numbers, but we can use numerals *)\nCheck idfun nat 3.\n\n(** This type also comes with an induction principle *)\nCheck nat_rect.\n\n(** We can define the recursor: *)\nDefinition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=\n nat_rect (fun _ : nat => A) a f.\n\n(**\n\nThis can be understood as a function defined by the following clauses:\n<<\nnat_rec m f 0 = m\nnat_rec m f (S n) = f n (nat_rec m f n)\n>>\n*)\n\n(** We can look at the normal form of the recursor by *)\nEval compute in nat_rec.\n\n(** This contains a both a \"fix\" and \"match _ with _\". These primitives\nof Coq are not allowed in UniMath. Instead we write everything using\nrecursors. The reason is that everything we write in UniMath has to be\njustified by the simplicial set model and the situation for general\ninductive types with match is unclear. *)\n\n(** If you are used to regular programming languages it might seem very\nstrange to only program with the recursors, but it's actually not too\nbad and we can do many programs quite directly *)\n\n(** truncated predecessor *)\nDefinition pred : nat -> nat := nat_rec nat 0 (fun x _ => x).\n\nEval compute in pred 3.\n\n(** We can test if a number is even by: *)\nDefinition even : nat -> bool := nat_rec bool true (fun _ b => negbool b).\n\nEval compute in even 3.\nEval compute in even 4.\n\n(** Exercise: define a function odd that tests if a number is odd\n\nDefinition odd : nat -> bool :=\n\n*)\n\n(** Addition *)\nDefinition add (m : nat) : nat -> nat := nat_rec nat m (fun _ y => S y).\n\nEval compute in add 2 3.\n\n(** We can define a nice notation for addition by: *)\nNotation \"x + y\" := (add x y).\n\nEval compute in 4 + 9.\n\n(** To find information about a notation we can write: *)\nLocate \"+\".\n\n(** Coq allows us to write very sophisticated notations, for details\nsee: https://coq.inria.fr/refman/syntax-extensions.html *)\n\n(** In UniMath we use a lot of unicode. To input a unicode character\nwrite \\ and then the name of the symbol. For example \\alpha gives\nα. To get information about a unicode character, including how to\nwrite it, put the cursor on top of the symbol and type: M-x\ndescribe-char\n\nIn fact one can write:\n<<\n λ x, e instead of fun x => e\n ∏ (x : A), T instead of forall (x : A), T\n A → B instead of A -> B\n>>\n*)\n\n(** Iterate a function many times *)\nDefinition iter (A : UU) (a : A) (f : A → A) : nat → A :=\n nat_rec A a (λ _ y, f y).\n\n(** A more fancy notation where the ̂ symbol is the unicode one (written \\^ ) *)\nNotation \"f ̂ n\" := (λ x, iter _ x f n) (at level 10).\n\nEval compute in pred̂2 5.\n\n(** Exercise: define a notation \"myif b then x else y\" for \"ifbool _ x y b\"\nand rewrite negbool and andbool using this notation.\n\nNote that we cannot introduce the notation \"if b then x else y\" as\nthis is already used.\n\n*)\n\nDefinition sub (m n : nat) : nat := pred̂n m.\n\nEval compute in sub 15 4.\nEval compute in sub 11 15.\n\n(** Exercise: define addition using iter and S *)\n\nDefinition is_zero : nat → bool := nat_rec bool true (λ _ _, false).\n\nEval compute in is_zero 3.\nEval compute in is_zero 0.\n\nDefinition eqnat (m n : nat) : bool :=\n andbool (is_zero (sub m n)) (is_zero (sub n m)).\n\nNotation \"m == n\" := (eqnat m n) (at level 30).\n\nEval compute in 5 == 5.\nEval compute in 5 == 3.\nEval compute in 9 == 5.\n\n(** Exercises: define <, >, ≤, ≥ *)\n\n(** Note that I could omit the A from the definition of f ̂ n and just\nreplace it by _. The reason is that Coq very often can infer what\narguments are so that we can omit them. *)\n\n(** For example if I omit nat in *)\nCheck idfun _ 3.\n(** Coq will figure it out for us *)\n\n(** In fact we can tell Coq to always put _ for an argument by using\ncurly braces in the definition: *)\n\nDefinition idfun'' {A : UU} (a : A) : A := a.\n\nCheck idfun'' 3.\nCheck idfun'' true.\n\n(** Such an argument is called an \"implicit argument\" and these are\nvery useful in order for us to get definitions that don't take too\nmany unnecessary arguments. However it is sometimes necessary to be\nable to give all the arguments explicitly, this is achieved by putting\nan @ in front of the function *)\n\nCheck @idfun'' nat 3.\n\n\n(** * More inductive types *)\n\n(** The inductive types we have seen so far come from the standard\nlibrary, but Coq allows us to define any inductive types we want. In\nUniMath we don't allow this and the additional inductive types we have\nare defined in Foundations. *)\n\n(** One of these is the coproduct (disjoint union) of types *)\nAbout coprod.\nPrint coprod.\nCheck inl.\nCheck inr.\nLocate \"ii1\".\nLocate \"ii2\".\n\nCheck (λ A B C : UU, @coprod_rect A B (λ _, C)).\n\nDefinition coprod_rec {A B C : UU} (f : A → C) (g : B → C) : A ⨿ B → C :=\n @coprod_rect A B (λ _, C) f g.\n\n(** Define integers as a coproduct of nat with itself *)\n(** +1 = inl 1 *)\n(** 0 = inl 0 *)\n(** -1 = inr 0 *)\n(** Note that we get the negative numbers \"off-by-one\". We could also\nhave inl 0 and inr 0 representing zero, but this becomes quite strange\nas we actually want to work with a quotient type where \"inl 0 = inr\n0\". *)\n\nDefinition Z : UU := nat ⨿ nat.\n\nNotation \"⊹ x\" := (inl x) (at level 20).\nNotation \"─ x\" := (inr x) (at level 40).\n\nDefinition Z1 : Z := ⊹ 1.\nDefinition Z0 : Z := ⊹ 0.\nDefinition Zn3 : Z := ─ 2.\n\n(** We can define a function by case on whether the number is ⊹ n or ─ n *)\nDefinition Zcase (A : UU) (fpos : nat → A) (fneg : nat → A) : Z → A :=\n coprod_rec fpos fneg.\n\nDefinition negate : Z → Z :=\n Zcase Z (λ x, ifbool Z Z0 (─ pred x) (is_zero x)) (λ x, ⊹ S x).\n\nEval compute in negate Z0.\nEval compute in negate Z1.\nEval compute in negate Zn3.\n\n(** Exercise (harder): define addition for Z. *)\n\n(** We also have two more inductive types: *)\n\n(** The unit type with one inhabitant tt *)\nAbout unit.\nPrint unit.\n\n(** The empty type with no inhabitants *)\nAbout empty.\nPrint empty.\n\n\n(** * Sigma types *)\n\n(** Sigma types are called total2 and this is the only example of a\nRecord in the whole UniMath library. The reason we use a record is so\nthat we can get surjective pairing. *)\n\nAbout total2.\nPrint total2.\n\n(** We have a notation ∑ (x : A), B for Sigma types *)\n\n(** To form a pair use *)\nCheck tpair.\nLocate \",,\".\n\n(** and to project out of a pair use *)\nCheck pr1.\nCheck pr2.\n\n(** In PartA.v we define the direct product as a Sigma type *)\nDefinition dirprod (X Y : UU) := ∑ x : X, Y.\n\nNotation \"A × B\" := (dirprod A B) (at level 75, right associativity) : type_scope.\n\nDefinition dirprod_pr1 {X Y : UU} : X × Y -> X := pr1.\nDefinition dirprod_pr2 {X Y : UU} : X × Y -> Y := pr2.\n\nDefinition dirprodf {X Y X' Y' : UU} (f : X -> Y) (f' : X' -> Y')\n (xx' : X × X') : Y × Y' := (f (pr1 xx'),,f' (pr2 xx')).\n\nDefinition swap {X Y : UU} (xy : X × Y) : Y × X :=\n dirprodf dirprod_pr2 dirprod_pr1 (xy,,xy).\n\n(** We can define the type of even numbers as a Sigma-type: *)\nDefinition even_nat : UU :=\n ∑ (n : nat), ifbool _ unit empty (even n).\n\nDefinition test20 : even_nat := (20,,tt).\n\n(** This Definition does not work *)\nFail Definition test3 : even_nat := (3,,tt).\n\n(** Section's can be very useful to only write parameters that are used\nmany times once and for all. They are also useful for organizing your\nfiles into logical sections. *)\nSection curry.\n\nVariables A B C : UU.\n\n(** To make these arguments implicit use:\n<<\nContext {A B C : UU}.\n>>\n*)\n\nDefinition curry : (A × B → C) → (A → B → C) :=\n λ (f : A × B → C) (a : A) (b : B), f (a,,b).\n\nDefinition uncurry : (A → B → C) → (A × B → C) :=\n λ (f : A → B → C) (ab : A × B), f (pr1 ab) (pr2 ab).\n\nEnd curry.\n\nCheck curry.\nPrint curry.\nCheck uncurry.\nPrint uncurry.\n\n\n(** These were all the basics for interacting with Coq in this\nlecture. The UniMath library is a very large library and so far we\nhave only seen parts of Preamble.v. When writing programs and proofs\nin UniMath it is very important to be able to search the library so\nthat you don't do something someone else has already done. *)\n\n(** To find everything about nat type: *)\nSearch nat.\n\n(** To search for all lemmas involving the pattern *)\n(* Search _ (_ -> _ <= _). *)\n\n(** To find information about a notation *)\nLocate \"+\".\n\n(** More information about searching can be found in the reference\nmanual. *)\n\n(**\n\nOne can also generate HTML documentation for UniMath that is a bit\neasier to browse than reading text files. This is done by typing:\n<<\n> make html\n>>\nYou can then open this documentation in your browser:\n<<\n> firefox html/toc.html\n>>\nIn order to have your comments display properly in the HTML use the\nfollowing format:\n\n(** This comment will be displayed *)\n(** * This will be displayed as a section header *)\n(** ** This will be a subsection *)\n\nFor more details see:\n\nhttps://coq.inria.fr/distrib/current/refman/tools.html#coqdoc\n\n*)\n\n(**\n\nThe UniMath library is organized into a collection of packages that\ncan be found in the UniMath folder. The library is then compiled using\na Makefile which specifies in which order things has to be compiled\nand how they should be compiled.\n\nIn order to have your file get compiled when you type \"make\" add it to\nthe .package/files file of the package where it belongs. See for\nexample: UniMath/UniMath/Foundations/.package/files\n\nIf you're working on a new package then you need to add it to the\nMakefile by writing:\n\nPACKAGES += MyPackage\n\n*)\n\n (*⋆⋆⋆⋆⋆⋆ THE END ⋆⋆⋆⋆⋆⋆*)\n", "meta": {"author": "UniMath", "repo": "Schools", "sha": "ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b", "save_path": "github-repos/coq/UniMath-Schools", "path": "github-repos/coq/UniMath-Schools/Schools-ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b/2017-12-Birmingham/Part2_Fundamentals_Coq/fundamentals_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.16026603433317138, "lm_q1q2_score": 0.060506945787772055}} {"text": "(** * UseTactics: Tactic Library for Coq: A Gentle Introduction *)\n\n(* Chapter written and maintained by Arthur Chargueraud *)\n\n(** Coq comes with a set of builtin tactics, such as [reflexivity],\n [intros], [inversion] and so on. While it is possible to conduct\n proofs using only those tactics, you can significantly increase\n your productivity by working with a set of more powerful tactics.\n This chapter describes a number of such useful tactics, which, for\n various reasons, are not yet available by default in Coq. These\n tactics are defined in the [LibTactics.v] file. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\n\nFrom Coq Require Import Arith.Arith.\n\nFrom PLF Require Maps.\nFrom PLF Require Stlc.\nFrom PLF Require Types.\nFrom PLF Require Smallstep.\nFrom PLF Require LibTactics.\nFrom PLF Require Equiv.\nFrom PLF Require References.\nFrom PLF Require Hoare.\nFrom PLF Require Sub.\n\nImport LibTactics.\n\n(** Remark: SSReflect is another package providing powerful tactics.\n The library \"LibTactics\" differs from \"SSReflect\" in two respects:\n - \"SSReflect\" was primarily developed for proving mathematical\n theorems, whereas \"LibTactics\" was primarily developed for proving\n theorems on programming languages. In particular, \"LibTactics\"\n provides a number of useful tactics that have no counterpart in the\n \"SSReflect\" package.\n - \"SSReflect\" entirely rethinks the presentation of tactics,\n whereas \"LibTactics\" mostly stick to the traditional\n presentation of Coq tactics, simply providing a number of\n additional tactics. For this reason, \"LibTactics\" is\n probably easier to get started with than \"SSReflect\". *)\n\n(** This chapter is a tutorial focusing on the most useful features\n from the \"LibTactics\" library. It does not aim at presenting all\n the features of \"LibTactics\". The detailed specification of tactics\n can be found in the source file [LibTactics.v]. Further documentation\n as well as demos can be found at https://www.chargueraud.org/softs/tlc/. *)\n\n(** In this tutorial, tactics are presented using examples taken from\n the core chapters of the \"Software Foundations\" course. To illustrate\n the various ways in which a given tactic can be used, we use a\n tactic that duplicates a given goal. More precisely, [dup] produces\n two copies of the current goal, and [dup n] produces [n] copies of it. *)\n\n(* ################################################################# *)\n(** * Tactics for Naming and Performing Inversion *)\n\n(** This section presents the following tactics:\n - [introv], for naming hypotheses more efficiently,\n - [inverts], for improving the [inversion] tactic. *)\n\n(* ================================================================= *)\n(** ** The Tactic [introv] *)\n\nModule IntrovExamples.\n\nImport Maps.\nImport Imp.\nImport Equiv.\nImport Stlc.\n\n(** The tactic [introv] allows to automatically introduce the\n variables of a theorem and explicitly name the hypotheses\n involved. In the example shown next, the variables [c],\n [st], [st1] and [st2] involved in the statement of determinism\n need not be named explicitly, because their name where already\n given in the statement of the lemma. On the contrary, it is\n useful to provide names for the two hypotheses, which we\n name [E1] and [E2], respectively. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n introv E1 E2. (* was [intros c st st1 st2 E1 E2] *)\nAbort.\n\n(** When there is no hypothesis to be named, one can call\n [introv] without any argument. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n introv. (* was [intros X P Q] *)\nAbort.\n\n(** The tactic [introv] also applies to statements in which\n [forall] and [->] are interleaved. *)\n\nTheorem ceval_deterministic': forall c st st1,\n (st =[ c ]=> st1) ->\n forall st2,\n (st =[ c ]=> st2) ->\n st1 = st2.\nProof.\n introv E1 E2. (* was [intros c st st1 E1 st2 E2] *)\nAbort.\n\n(** Like the arguments of [intros], the arguments of [introv]\n can be structured patterns. *)\n\nTheorem exists_impl: forall X (P : X -> Prop) (Q : Prop) (R : Prop),\n (forall x, P x -> Q) ->\n ((exists x, P x) -> Q).\nProof.\n introv [x H2]. eauto.\n (* same as [intros X P Q R H1 [x H2].], which is itself short\n for [intros X P Q R H1 H2. destruct H2 as [x H2].] *)\nQed.\n\n(** Remark: the tactic [introv] works even when definitions\n need to be unfolded in order to reveal hypotheses. *)\n\nEnd IntrovExamples.\n\n(* ================================================================= *)\n(** ** The Tactic [inverts] *)\n\nModule InvertsExamples.\nImport Maps.\nImport Imp.\nImport Equiv.\n\n(** The [inversion] tactic of Coq is not very satisfying for\n three reasons. First, it produces a bunch of equalities\n which one typically wants to substitute away, using [subst].\n Second, it introduces meaningless names for hypotheses.\n Third, a call to [inversion H] does not remove [H] from the\n context, even though in most cases an hypothesis is no longer\n needed after being inverted. The tactic [inverts] address all\n of these three issues. It is intented to be used in place of\n the tactic [inversion]. *)\n\n(** The following example illustrates how the tactic [inverts H]\n behaves mostly like [inversion H] except that it performs\n some substitutions in order to eliminate the trivial equalities\n that are being produced by [inversion]. *)\n\nTheorem skip_left: forall c,\n cequiv <{skip; c}> c.\nProof.\n introv. split; intros H.\n dup. (* duplicate the goal for comparison *)\n (* was... *)\n - inversion H. subst. inversion H2. subst. assumption.\n (* now... *)\n - inverts H. inverts H2. assumption.\nAbort.\n\n(** A slightly more interesting example appears next. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n introv E1 E2. generalize dependent st2.\n induction E1; intros st2 E2.\n admit. admit. (* skip some basic cases *)\n dup. (* duplicate the goal for comparison *)\n (* was: *)\n - inversion E2. subst. admit.\n (* now: *)\n - inverts E2. admit.\nAbort.\n\n(** The tactic [inverts H as.] is like [inverts H] except that the\n variables and hypotheses being produced are placed in the goal\n rather than in the context. This strategy allows naming those\n new variables and hypotheses explicitly, using either [intros]\n or [introv]. *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n introv E1 E2. generalize dependent st2.\n induction E1; intros st2 E2;\n inverts E2 as.\n - (* E_Skip *) reflexivity.\n - (* E_Ass *)\n (* Observe that the variable [n] is not automatically\n substituted because, contrary to [inversion E2; subst],\n the tactic [inverts E2] does not substitute the equalities\n that exist before running the inversion. *)\n (* new: *) subst n.\n reflexivity.\n - (* E_Seq *)\n (* Here, the newly created variables can be introduced\n using intros, so they can be assigned meaningful names,\n for example [st3] instead of [st'0]. *)\n (* new: *) intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n { (* Proof of assertion *) apply IHE1_1; assumption. }\n subst st3.\n apply IHE1_2. assumption.\n (* E_IfTrue *)\n - (* b1 reduces to true *)\n (* In an easy case like this one, there is no need to\n provide meaningful names, so we can just use [intros] *)\n (* new: *) intros.\n apply IHE1. assumption.\n - (* b1 reduces to false (contradiction) *)\n (* new: *) intros.\n rewrite H in H5. inversion H5.\n (* The other cases are similiar *)\nAbort.\n\n(** In the particular case where a call to [inversion] produces\n a single subgoal, one can use the syntax [inverts H as H1 H2 H3]\n for calling [inverts] and naming the new hypotheses [H1], [H2]\n and [H3]. In other words, the tactic [inverts H as H1 H2 H3] is\n equivalent to [inverts H as; introv H1 H2 H3]. An example follows. *)\n\nTheorem skip_left': forall c,\n cequiv <{ skip ; c}> c.\nProof.\n introv. split; intros H.\n inverts H as U V. (* new hypotheses are named [U] and [V] *)\n inverts U. assumption.\nAbort.\n\nEnd InvertsExamples.\n\n(** A more involved example appears next. In particular, this example\n shows that the name of the hypothesis being inverted can be reused. *)\n\nModule InvertsExamples1.\nImport Types.\nImport Stlc.\nImport STLC.\nImport Maps.\n\nExample typing_nonexample_1 :\n ~ exists T,\n empty |-\n \\x:Bool,\n \\y:Bool,\n (x y) \\in\n T.\nProof.\n dup 3.\n\n (* The old proof: *)\n - intros Hc. destruct Hc as [T Hc].\n inversion Hc; subst; clear Hc.\n inversion H4; subst; clear H4.\n inversion H5; subst; clear H5 H4.\n inversion H2; subst; clear H2.\n discriminate H1.\n\n (* The new proof: *)\n - intros C. destruct C.\n inverts H as H1.\n inverts H1 as H2.\n inverts H2 as H3 H4.\n inverts H3 as H5.\n inverts H5.\n\n (* The new proof, alternative: *)\n - intros C. destruct C.\n inverts H as H.\n inverts H as H.\n inverts H as H1 H2.\n inverts H1 as H1.\n inverts H1.\nQed.\n\nEnd InvertsExamples1.\n\n(** Note: in the rare cases where one needs to perform an inversion\n on an hypothesis [H] without clearing [H] from the context,\n one can use the tactic [inverts keep H], where the keyword [keep]\n indicates that the hypothesis should be kept in the context. *)\n\n(* ################################################################# *)\n(** * Tactics for N-ary Connectives *)\n\n(** Because Coq encodes conjunctions and disjunctions using binary\n constructors [/\\] and [\\/], working with a conjunction or a\n disjunction of [N] facts can sometimes be quite cumbursome.\n For this reason, \"LibTactics\" provides tactics offering direct\n support for n-ary conjunctions and disjunctions. It also provides\n direct support for n-ary existententials. *)\n\n(** This section presents the following tactics:\n - [splits] for decomposing n-ary conjunctions,\n - [branch] for decomposing n-ary disjunctions *)\n\nModule NaryExamples.\n Import References.\n Import Smallstep.\n Import STLCRef.\n\n(* ================================================================= *)\n(** ** The Tactic [splits] *)\n\n(** The tactic [splits] applies to a goal made of a conjunction\n of [n] propositions and it produces [n] subgoals. For example,\n it decomposes the goal [G1 /\\ G2 /\\ G3] into the three subgoals\n [G1], [G2] and [G3]. *)\n\nLemma demo_splits : forall n m,\n n > 0 /\\ n < m /\\ m < n+10 /\\ m <> 3.\nProof.\n intros. splits.\nAbort.\n\n(* ================================================================= *)\n(** ** The Tactic [branch] *)\n\n(** The tactic [branch k] can be used to prove a n-ary disjunction.\n For example, if the goal takes the form [G1 \\/ G2 \\/ G3],\n the tactic [branch 2] leaves only [G2] as subgoal. The following\n example illustrates the behavior of the [branch] tactic. *)\n\nLemma demo_branch : forall n m,\n n < m \\/ n = m \\/ m < n.\nProof.\n intros.\n destruct (lt_eq_lt_dec n m) as [ [H1|H2]|H3].\n - branch 1. apply H1.\n - branch 2. apply H2.\n - branch 3. apply H3.\nQed.\n\nEnd NaryExamples.\n\n(* ################################################################# *)\n(** * Tactics for Working with Equality *)\n\n(** One of the major weakness of Coq compared with other interactive\n proof assistants is its relatively poor support for reasoning\n with equalities. The tactics described next aims at simplifying\n pieces of proof scripts manipulating equalities. *)\n\n(** This section presents the following tactics:\n - [asserts_rewrite] for introducing an equality to rewrite with,\n - [cuts_rewrite], which is similar except that its subgoals are swapped,\n - [substs] for improving the [subst] tactic,\n - [fequals] for improving the [f_equal] tactic,\n - [applys_eq] for proving [P x y] using an hypothesis [P x z],\n automatically producing an equality [y = z] as subgoal. *)\n\nModule EqualityExamples.\n\n(* ================================================================= *)\n(** ** The Tactics [asserts_rewrite] and [cuts_rewrite] *)\n\n(** The tactic [asserts_rewrite (E1 = E2)] replaces [E1] with [E2] in\n the goal, and produces the goal [E1 = E2]. *)\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n dup.\n (* The old proof: *)\n intros n m.\n assert (H: 0 + n = n). reflexivity. rewrite -> H.\n reflexivity.\n\n (* The new proof: *)\n intros n m.\n asserts_rewrite (0 + n = n).\n reflexivity. (* subgoal [0+n = n] *)\n reflexivity. (* subgoal [n*m = m*n] *)\nQed.\n\n(** Remark: the syntax [asserts_rewrite (E1 = E2) in H] allows\n rewriting in the hypothesis [H] rather than in the goal. *)\n\n(** The tactic [cuts_rewrite (E1 = E2)] is like\n [asserts_rewrite (E1 = E2)], except that the equality [E1 = E2]\n appears as first subgoal. *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n cuts_rewrite (0 + n = n).\n reflexivity. (* subgoal [n*m = m*n] *)\n reflexivity. (* subgoal [0+n = n] *)\nQed.\n\n(** More generally, the tactics [asserts_rewrite] and [cuts_rewrite]\n can be provided a lemma as argument. For example, one can write\n [asserts_rewrite (forall a b, a*(S b) = a*b+a)].\n This formulation is useful when [a] and [b] are big terms,\n since there is no need to repeat their statements. *)\n\nTheorem mult_0_plus'' : forall u v w x y z: nat,\n (u + v) * (S (w * x + y)) = z.\nProof.\n intros. asserts_rewrite (forall a b, a*(S b) = a*b+a).\n (* first subgoal: [forall a b, a*(S b) = a*b+a] *)\n (* second subgoal: [(u + v) * (w * x + y) + (u + v) = z] *)\nAbort.\n\n(* ================================================================= *)\n(** ** The Tactic [substs] *)\n\n(** The tactic [substs] is similar to [subst] except that it\n does not fail when the goal contains \"circular equalities\",\n such as [x = f x]. *)\n\nLemma demo_substs : forall x y (f:nat->nat),\n x = f x ->\n y = x ->\n y = f x.\nProof.\n intros. substs. (* the tactic [subst] would fail here *)\n assumption.\nQed.\n\n(* ================================================================= *)\n(** ** The Tactic [fequals] *)\n\n(** The tactic [fequals] is similar to [f_equal] except that it\n directly discharges all the trivial subgoals produced. Moreover,\n the tactic [fequals] features an enhanced treatment of equalities\n between tuples. *)\n\nLemma demo_fequals : forall (a b c d e : nat) (f : nat->nat->nat->nat->nat),\n a = 1 ->\n b = e ->\n e = 2 ->\n f a b c d = f 1 2 c 4.\nProof.\n intros. fequals.\n (* subgoals [a = 1], [b = 2] and [c = c] are proved, [d = 4] remains *)\nAbort.\n\n(* ================================================================= *)\n(** ** The Tactic [applys_eq] *)\n\n(** The tactic [applys_eq] is a variant of [eapply] that introduces\n equalities for subterms that do not unify. For example, assume\n the goal is the proposition [P x y] and assume we have the\n assumption [H] asserting that [P x z] holds. We know that we can\n prove [y] to be equal to [z]. So, we could call the tactic\n [assert_rewrite (y = z)] and change the goal to [P x z], but\n this would require copy-pasting the values of [y] and [z].\n With the tactic [applys_eq], we can call [applys_eq H 1], which\n proves the goal and leaves only the subgoal [y = z]. The value [1]\n given as argument to [applys_eq] indicates that we want an equality\n to be introduced for the first argument of [P x y] counting from\n the right. The three following examples illustrate the behavior\n of a call to [applys_eq H 1], a call to [applys_eq H 2], and a\n call to [applys_eq H 1 2]. *)\n\nAxiom big_expression_using : nat->nat. (* Used in the example *)\n\nLemma demo_applys_eq_1 : forall (P:nat->nat->Prop) x y z,\n P x (big_expression_using z) ->\n P x (big_expression_using y).\nProof.\n introv H. dup.\n\n (* The old proof: *)\n assert (Eq: big_expression_using y = big_expression_using z).\n admit. (* Assume we can prove this equality somehow. *)\n rewrite Eq. apply H.\n\n (* The new proof: *)\n applys_eq H 1.\n admit. (* Assume we can prove this equality somehow. *)\nAbort.\n\n(** If the mismatch was on the first argument of [P] instead of\n the second, we would have written [applys_eq H 2]. Recall\n that the occurences are counted from the right. *)\n\nLemma demo_applys_eq_2 : forall (P:nat->nat->Prop) x y z,\n P (big_expression_using z) x ->\n P (big_expression_using y) x.\nProof.\n introv H. applys_eq H 2.\nAbort.\n\n(** When we have a mismatch on two arguments, we want to produce\n two equalities. To achieve this, we may call [applys_eq H 1 2].\n More generally, the tactic [applys_eq] expects a lemma and a\n sequence of natural numbers as arguments. *)\n\nLemma demo_applys_eq_3 : forall (P:nat->nat->Prop) x1 x2 y1 y2,\n P (big_expression_using x2) (big_expression_using y2) ->\n P (big_expression_using x1) (big_expression_using y1).\nProof.\n introv H. applys_eq H 1 2.\n (* produces two subgoals:\n [big_expression_using x1 = big_expression_using x2]\n [big_expression_using y1 = big_expression_using y2] *)\nAbort.\n\nEnd EqualityExamples.\n\n(* ################################################################# *)\n(** * Some Convenient Shorthands *)\n\n(** This section of the tutorial introduces a few tactics\n that help make proof scripts shorter and more readable:\n - [unfolds] (without argument) for unfolding the head definition,\n - [false] for replacing the goal with [False],\n - [gen] as a shorthand for [dependent generalize],\n - [admits] for naming an addmited fact,\n - [admit_rewrite] for rewriting using an admitted equality,\n - [admit_goal] to set up a proof by induction by skipping the\n justification that some order decreases,\n - [sort] for re-ordering the proof context by moving moving all\n propositions at the bottom. *)\n\n(* ================================================================= *)\n(** ** The Tactic [unfolds] *)\n\nModule UnfoldsExample.\n Import Hoare.\n\n(** The tactic [unfolds] (without any argument) unfolds the\n head constant of the goal. This tactic saves the need to\n name the constant explicitly. *)\n\nLemma bexp_eval_true : forall b st,\n beval st b = true ->\n (bassn b) st.\nProof.\n intros b st Hbe. dup.\n\n (* The old proof: *)\n unfold bassn. assumption.\n\n (* The new proof: *)\n unfolds. assumption.\nQed.\n\n(** Remark: contrary to the tactic [hnf], which may unfold several\n constants, [unfolds] performs only a single step of unfolding. *)\n\n(** Remark: the tactic [unfolds in H] can be used to unfold the\n head definition of the hypothesis [H]. *)\n\nEnd UnfoldsExample.\n\n(* ================================================================= *)\n(** ** The Tactics [false] and [tryfalse] *)\n\n(** The tactic [false] can be used to replace any goal with [False].\n In short, it is a shorthand for [exfalso].\n Moreover, [false] proves the goal if it contains an absurd\n assumption, such as [False] or [0 = S n], or if it contains\n contradictory assumptions, such as [x = true] and [x = false]. *)\n\nLemma demo_false : forall n,\n S n = 1 ->\n n = 0.\nProof.\n intros. destruct n. reflexivity. false.\nQed.\n\n(** The tactic [false] can be given an argument: [false H] replace\n the goals with [False] and then applies [H]. *)\n\nLemma demo_false_arg :\n (forall n, n < 0 -> False) ->\n 3 < 0 ->\n 4 < 0.\nProof.\n intros H L. false H. apply L.\nQed.\n\n(** The tactic [tryfalse] is a shorthand for [try solve [false]]:\n it tries to find a contradiction in the goal. The tactic\n [tryfalse] is generally called after a case analysis. *)\n\nLemma demo_tryfalse : forall n,\n S n = 1 ->\n n = 0.\nProof.\n intros. destruct n; tryfalse. reflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** The Tactic [gen] *)\n\n(** The tactic [gen] is a shortand for [generalize dependent]\n that accepts several arguments at once. An invocation of\n this tactic takes the form [gen x y z]. *)\n\nModule GenExample.\n Import Stlc.\n Import STLC.\n Import Maps.\n\nLemma substitution_preserves_typing : forall Gamma x U t v T,\n x |-> U ; Gamma |- t \\in T ->\n empty |- v \\in U ->\n Gamma |- [x:=v]t \\in T.\nProof.\n dup.\n\n (* The old proof: *)\n - intros Gamma x U t v T Ht Hv.\n generalize dependent Gamma. generalize dependent T.\n induction t; intros T Gamma H;\n inversion H; clear H; subst; simpl; eauto.\n admit. admit.\n\n (* The new proof: *)\n - introv Ht Hv. gen Gamma T.\n induction t; intros S Gamma H;\n inversion H; clear H; subst; simpl; eauto.\n admit. admit.\nAbort.\n\nEnd GenExample.\n\n(* ================================================================= *)\n(** ** The Tactics [admits], [admit_rewrite] and [admit_goal] *)\n\n(** Temporarily admitting a given subgoal is very useful when\n constructing proofs. Several tactics are provided as\n useful wrappers around the builtin [admit] tactic. *)\n\nModule SkipExample.\n\n(** The tactic [admits H: P] adds the hypothesis [H: P] to the context,\n without checking whether the proposition [P] is true.\n It is useful for exploiting a fact and postponing its proof.\n Note: [admits H: P] is simply a shorthand for [assert (H:P). admit.] *)\n\nTheorem demo_admits : True.\nProof.\n admits H: (forall n m : nat, (0 + n) * m = n * m).\nAbort.\n\n(** The tactic [admit_rewrite (E1 = E2)] replaces [E1] with [E2] in\n the goal, without checking that [E1] is actually equal to [E2]. *)\n\nTheorem mult_plus_0 : forall n m : nat,\n (n + 0) * m = n * m.\nProof.\n dup 3.\n\n (* The old proof: *)\n intros n m.\n assert (H: n + 0 = n). admit. rewrite -> H. clear H.\n reflexivity.\n\n (* The new proof: *)\n intros n m.\n admit_rewrite (n + 0 = n).\n reflexivity.\n\n (* Remark: [admit_rewrite] can be given a lemma statement as argument,\n like [asserts_rewrite]. For example: *)\n intros n m.\n admit_rewrite (forall a, a + 0 = a).\n reflexivity.\nAdmitted.\n\n(** The tactic [admit_goal] adds the current goal as hypothesis.\n This cheat is useful to set up the structure of a proof by\n induction without having to worry about the induction hypothesis\n being applied only to smaller arguments. Using [skip_goal], one\n can construct a proof in two steps: first, check that the main\n arguments go through without waisting time on fixing the details\n of the induction hypotheses; then, focus on fixing the invokations\n of the induction hypothesis. *)\n\nImport Imp.\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n (* The tactic [admit_goal] creates an hypothesis called [IH]\n asserting that the statment of [ceval_deterministic] is true. *)\n admit_goal.\n (* Of course, if we call [assumption] here, then the goal is solved\n right away, but the point is to do the proof and use [IH]\n only at the places where we need an induction hypothesis. *)\n introv E1 E2. gen st2.\n induction E1; introv E2; inverts E2 as.\n - (* E_Skip *) reflexivity.\n - (* E_Ass *)\n subst n.\n reflexivity.\n - (* E_Seq *)\n intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n { (* Proof of assertion *)\n (* was: [apply IHE1_1; assumption.] *)\n (* new: *) eapply IH. eapply E1_1. eapply Red1. }\n subst st3.\n (* was: apply IHE1_2. assumption.] *)\n (* new: *) eapply IH. eapply E1_2. eapply Red2.\n (* The other cases are similiar. *)\nAbort.\n\nEnd SkipExample.\n\n(* ================================================================= *)\n(** ** The Tactic [sort] *)\n\nModule SortExamples.\n Import Imp.\n\n(** The tactic [sort] reorganizes the proof context by placing\n all the variables at the top and all the hypotheses at the\n bottom, thereby making the proof context more readable. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2.\n induction E1; intros st2 E2; inverts E2.\n admit. admit. (* Skipping some trivial cases *)\n sort. (* Observe how the context is reorganized *)\nAbort.\n\nEnd SortExamples.\n\n(* ################################################################# *)\n(** * Tactics for Advanced Lemma Instantiation *)\n\n(** This last section describes a mechanism for instantiating a lemma\n by providing some of its arguments and leaving other implicit.\n Variables whose instantiation is not provided are turned into\n existentential variables, and facts whose instantiation is not\n provided are turned into subgoals.\n\n Remark: this instantion mechanism goes far beyond the abilities of\n the \"Implicit Arguments\" mechanism. The point of the instantiation\n mechanism described in this section is that you will no longer need\n to spend time figuring out how many underscore symbols you need to\n write. *)\n\n(** In this section, we'll use a useful feature of Coq for decomposing\n conjunctions and existentials. In short, a tactic like [intros] or\n [destruct] can be provided with a pattern [(H1 & H2 & H3 & H4 & H5)],\n which is a shorthand for [[H1 [H2 [H3 [H4 H5]]]]]]. For example,\n [destruct (H _ _ _ Htypt) as [T [Hctx Hsub]].] can be rewritten in\n the form [destruct (H _ _ _ Htypt) as (T & Hctx & Hsub).] *)\n\n(* ================================================================= *)\n(** ** Working of [lets] *)\n\n(** When we have a lemma (or an assumption) that we want to exploit,\n we often need to explicitly provide arguments to this lemma,\n writing something like:\n [destruct (typing_inversion_var _ _ _ Htypt) as (T & Hctx & Hsub).]\n The need to write several times the \"underscore\" symbol is tedious.\n Not only we need to figure out how many of them to write down, but\n it also makes the proof scripts look prettly ugly. With the tactic\n [lets], one can simply write:\n [lets (T & Hctx & Hsub): typing_inversion_var Htypt.]\n\n In short, this tactic [lets] allows to specialize a lemma on a bunch\n of variables and hypotheses. The syntax is [lets I: E0 E1 .. EN],\n for building an hypothesis named [I] by applying the fact [E0] to the\n arguments [E1] to [EN]. Not all the arguments need to be provided,\n however the arguments that are provided need to be provided in the\n correct order. The tactic relies on a first-match algorithm based on\n types in order to figure out how the to instantiate the lemma with\n the arguments provided. *)\n\nModule ExamplesLets.\n Import Sub.\n\n(* To illustrate the working of [lets], assume that we want to\n exploit the following lemma. *)\n\nImport Maps.\nImport Sub.\nImport String.\n\nAxiom typing_inversion_var : forall Gamma (x:string) T,\n Gamma |- x \\in T ->\n exists S,\n Gamma x = Some S /\\ S <: T.\n\n(** First, assume we have an assumption [H] with the type of the form\n [has_type G (var x) T]. We can obtain the conclusion of the\n lemma [typing_inversion_var] by invoking the tactics\n [lets K: typing_inversion_var H], as shown next. *)\n\nLemma demo_lets_1 : forall (G:context) (x:string) (T:ty),\n G |- x \\in T ->\n True.\nProof.\n intros G x T H. dup.\n\n (* step-by-step: *)\n lets K: typing_inversion_var H.\n destruct K as (S & Eq & Sub).\n admit.\n\n (* all-at-once: *)\n lets (S & Eq & Sub): typing_inversion_var H.\n admit.\nAbort.\n\n(** Assume now that we know the values of [G], [x] and [T] and we\n want to obtain [S], and have [has_type G (var x) T] be produced\n as a subgoal. To indicate that we want all the remaining arguments\n of [typing_inversion_var] to be produced as subgoals, we use a\n triple-underscore symbol [___]. (We'll later introduce a shorthand\n tactic called [forwards] to avoid writing triple underscores.) *)\n\nLemma demo_lets_2 : forall (G:context) (x:string) (T:ty), True.\nProof.\n intros G x T.\n lets (S & Eq & Sub): typing_inversion_var G x T ___.\nAbort.\n\n(** Usually, there is only one context [G] and one type [T] that are\n going to be suitable for proving [has_type G (tm_var x) T], so\n we don't really need to bother giving [G] and [T] explicitly.\n It suffices to call [lets (S & Eq & Sub): typing_inversion_var x].\n The variables [G] and [T] are then instantiated using existential\n variables. *)\n\nLemma demo_lets_3 : forall (x:string), True.\nProof.\n intros x.\n lets (S & Eq & Sub): typing_inversion_var x ___.\nAbort.\n\n(** We may go even further by not giving any argument to instantiate\n [typing_inversion_var]. In this case, three unification variables\n are introduced. *)\n\nLemma demo_lets_4 : True.\nProof.\n lets (S & Eq & Sub): typing_inversion_var ___.\nAbort.\n\n(** Note: if we provide [lets] with only the name of the lemma as\n argument, it simply adds this lemma in the proof context, without\n trying to instantiate any of its arguments. *)\n\nLemma demo_lets_5 : True.\nProof.\n lets H: typing_inversion_var.\nAbort.\n\n(** A last useful feature of [lets] is the double-underscore symbol,\n which allows skipping an argument when several arguments have\n the same type. In the following example, our assumption quantifies\n over two variables [n] and [m], both of type [nat]. We would like\n [m] to be instantiated as the value [3], but without specifying a\n value for [n]. This can be achieved by writting [lets K: H __ 3]. *)\n\nLemma demo_lets_underscore :\n (forall n m, n <= m -> n < m+1) ->\n True.\nProof.\n intros H.\n\n (* If we do not use a double underscore, the first argument,\n which is [n], gets instantiated as 3. *)\n lets K: H 3. (* gives [K] of type [forall m, 3 <= m -> 3 < m+1] *)\n clear K.\n\n (* The double underscore preceeding [3] indicates that we want\n to skip a value that has the type [nat] (because [3] has\n the type [nat]). So, the variable [m] gets instiated as [3]. *)\n lets K: H __ 3. (* gives [K] of type [?X <= 3 -> ?X < 3+1] *)\n clear K.\nAbort.\n\n(** Note: one can write [lets: E0 E1 E2] in place of [lets H: E0 E1 E2].\n In this case, the name [H] is chosen arbitrarily.\n\n Note: the tactics [lets] accepts up to five arguments. Another\n syntax is available for providing more than five arguments.\n It consists in using a list introduced with the special symbol [>>],\n for example [lets H: (>> E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 10)]. *)\n\nEnd ExamplesLets.\n\n(* ================================================================= *)\n(** ** Working of [applys], [forwards] and [specializes] *)\n\n(** The tactics [applys], [forwards] and [specializes] are\n shorthand that may be used in place of [lets] to perform\n specific tasks.\n\n - [forwards] is a shorthand for instantiating all the arguments\n of a lemma. More precisely, [forwards H: E0 E1 E2 E3] is the\n same as [lets H: E0 E1 E2 E3 ___], where the triple-underscore\n has the same meaning as explained earlier on.\n\n - [applys] allows building a lemma using the advanced instantion\n mode of [lets], and then apply that lemma right away. So,\n [applys E0 E1 E2 E3] is the same as [lets H: E0 E1 E2 E3]\n followed with [eapply H] and then [clear H].\n\n - [specializes] is a shorthand for instantiating in-place\n an assumption from the context with particular arguments.\n More precisely, [specializes H E0 E1] is the same as\n [lets H': H E0 E1] followed with [clear H] and [rename H' into H].\n\n Examples of use of [applys] appear further on. Several examples of\n use of [forwards] can be found in the tutorial chapter [UseAuto]. *)\n(* ################################################################# *)\n(** * Summary *)\n\n(** In this chapter we have presented a number of tactics that help make\n proof script more concise and more robust on change.\n\n - [introv] and [inverts] improve naming and inversions.\n\n - [false] and [tryfalse] help discarding absurd goals.\n\n - [unfolds] automatically calls [unfold] on the head definition.\n\n - [gen] helps setting up goals for induction.\n\n - [cases] and [cases_if] help with case analysis.\n\n - [splits] and [branch], to deal with n-ary constructs.\n\n - [asserts_rewrite], [cuts_rewrite], [substs] and [fequals] help\n working with equalities.\n\n - [lets], [forwards], [specializes] and [applys] provide means\n of very conveniently instantiating lemmas.\n\n - [applys_eq] can save the need to perform manual rewriting steps\n before being able to apply lemma.\n\n - [admits], [admit_rewrite] and [admit_goal] give the flexibility to\n choose which subgoals to try and discharge first.\n\n Making use of these tactics can boost one's productivity in Coq proofs.\n\n If you are interested in using [LibTactics.v] in your own developments,\n make sure you get the lastest version from:\n https://www.chargueraud.org/softs/tlc/.\n\n*)\n\n(* 2020-09-09 21:08 *)\n", "meta": {"author": "shouya", "repo": "thinking-dumps", "sha": "bfe50272459ddfca95de74a1857e2e649218584e", "save_path": "github-repos/coq/shouya-thinking-dumps", "path": "github-repos/coq/shouya-thinking-dumps/thinking-dumps-bfe50272459ddfca95de74a1857e2e649218584e/software-foundations-2/plf/UseTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.14804719615221756, "lm_q1q2_score": 0.06030456777594954}} {"text": "(** * Induction: Proof by Induction *)\n\n\n(** The next line imports all of our definitions from the\n previous chapter. *)\n\nRequire Export Basics.\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n into [Basics.vo]. (This is like making a .class file from a .java\n file, or a .o file from a .c file.)\n\n Here are two ways to compile your code:\n\n - CoqIDE:\n\n Open [Basics.v].\n In the \"Compile\" menu, click on \"Compile Buffer\".\n\n - Command line:\n\n Run [coqc Basics.v]\n\n *)\n\n(* ###################################################################### *)\n(** * Naming Cases *)\n\n(** The fact that there is no explicit command for moving from\n one branch of a case analysis to the next can make proof scripts\n rather hard to read. In larger proofs, with nested case analyses,\n it can even become hard to stay oriented when you're sitting with\n Coq and stepping through the proof. (Imagine trying to remember\n that the first five subgoals belong to the inner case analysis and\n the remaining seven cases are what remains of the outer one...)\n Disciplined use of indentation and comments can help, but a better\n way is to use the [Case] tactic. *)\n\n(** [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- you can just skip\n over the definition to the example that follows. It uses some\n facilities of Coq that we have not discussed -- the string\n library (just for the concrete syntax of quoted strings) and the\n [Ltac] command, which allows us to declare custom tactics. Kudos\n to Aaron Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n(** Here's an example of how [Case] is used. Step through the\n following proof and observe how the context changes. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\". (* <----- here *)\n reflexivity.\n Case \"b = false\". (* <---- and here *)\n rewrite <- H.\n reflexivity.\nQed.\n\n(** [Case] does something very straightforward: It simply adds a\n string that we choose (tagged with the identifier \"Case\") to the\n context for the current goal. When subgoals are generated, this\n string is carried over into their contexts. When the last of\n these subgoals is finally proved and the next top-level goal\n becomes active, this string will no longer appear in the context\n and we will be able to see that the case where we introduced it is\n complete. Also, as a sanity check, if we try to execute a new\n [Case] tactic while the string left by the previous one is still\n in the context, we get a nice clear error message.\n\n For nested case analyses (e.g., when we want to use a [destruct]\n to solve a goal that has itself been generated by a [destruct]),\n there is an [SCase] (\"subcase\") tactic. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2) *)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c H.\n destruct c.\n Case \"c = true\".\n reflexivity.\n Case \"c = false\".\n rewrite <- H.\n destruct b.\n SCase \"b = true\".\n reflexivity.\n SCase \"b = false\".\n reflexivity.\nQed.\n(** [] *)\n\n(** There are no hard and fast rules for how proofs should be\n formatted in Coq -- in particular, where lines should be broken\n and how sections of the proof should be indented to indicate their\n nested structure. However, if the places where multiple subgoals\n are generated are marked with explicit [Case] tactics placed at\n the beginning of lines, then the proof will be readable almost no\n matter what choices are made about other aspects of layout.\n\n This is a good place to mention one other piece of (possibly\n obvious) advice about line lengths. Beginning Coq users sometimes\n tend to the extremes, either writing each tactic on its own line\n or entire proofs on one line. Good style lies somewhere in the\n middle. In particular, one reasonable convention is to limit\n yourself to 80-character lines. Lines longer than this are hard\n to read and can be inconvenient to display and print. Many\n editors have features that help enforce this. *)\n\n(* ###################################################################### *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left using a simple argument. The fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... cannot be proved in the same simple way. Just applying\n [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** *** *)\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. We could use [destruct n'] to\n get one step further, but since [n] can be arbitrarily large, if we\n try to keep on like this we'll never be done. *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* so far so good... *)\n Case \"n = S n'\".\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** *** *)\n\n(** To prove such facts -- indeed, to prove most interesting\n facts about numbers, lists, and other inductively defined sets --\n we need a more powerful reasoning principle: _induction_.\n\n Recall (from high school) the principle of induction over natural\n numbers: If [P(n)] is some proposition involving a natural number\n [n] and we want to show that P holds for _all_ numbers [n], we can\n reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same but the order is backwards: we\n begin with the goal of proving [P(n)] for all [n] and break it\n down (by applying the [induction] tactic) into two separate\n subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n n')]. Here's how this works for the theorem we are trying to\n prove at the moment: *)\n\n(** *** *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. In the first branch, [n] is replaced by [0] and\n the goal becomes [0 + 0 = 0], which follows by simplification. In\n the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n n'] is added to the context (with the name [IHn'], i.e., the\n Induction Hypothesis for [n']). The goal in this case becomes [(S\n n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in\n turn follows from the induction hypothesis. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (basic_induction) *)\n\n(** Prove the following lemmas using induction. You might need\n previously proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m.\n (* Completed in Basics.v for Binary *)\n rewrite <- plus_S_assoc. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. rewrite <- plus_comm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite IHn'. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus) *)\n\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite <- plus_n_Sm. rewrite IHn'. reflexivity.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics\n [destruct] and [induction].\n\nInduction introduces an induction hypothesis in addition to performing case analysis.\n\n*)\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Proofs Within Proofs *)\n\n\n(** In Coq, as in informal mathematics, large proofs are very\n often broken into a sequence of theorems, with later proofs\n referring to earlier theorems. Occasionally, however, a proof\n will need some miscellaneous fact that is too trivial (and of too\n little general interest) to bother giving it its own top-level\n name. In such cases, it is convenient to be able to simply state\n and prove the needed \"sub-theorem\" right at the point where it is\n used. The [assert] tactic allows us to do this. For example, our\n earlier proof of the [mult_0_plus] theorem referred to a previous\n theorem named [plus_O_n]. We can also use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n).\n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (Note that we could also name the assertion with\n [as] just as we did above with [destruct] and [induction], i.e.,\n [assert (0 + n = n) as H]. Also note that we mark the proof of\n this assertion with a [Case], both for readability and so that,\n when using Coq interactively, we can see when we're finished\n proving the assertion by observing when the [\"Proof of assertion\"]\n string disappears from the context.) The second goal is the same\n as the one at the point where we invoke [assert], except that, in\n the context, we have the assumption [H] that [0 + n = n]. That\n is, [assert] generates one subgoal where we must prove the\n asserted fact and a second subgoal where we can use the asserted\n fact to make progress on whatever we were trying to prove in the\n first place. *)\n\n(** Actually, [assert] will turn out to be handy in many sorts of\n situations. For example, suppose we want to prove that [(n + m)\n + (p + q) = (m + n) + (p + q)]. The only difference between the\n two sides of the [=] is that the arguments [m] and [n] to the\n first inner [+] are swapped, so it seems we should be able to\n use the commutativity of addition ([plus_comm]) to rewrite one\n into the other. However, the [rewrite] tactic is a little stupid\n about _where_ it applies the rewrite. There are three uses of\n [+] here, and it turns out that doing [rewrite -> plus_comm]\n will affect only the _outer_ one. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)...\n it seems like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To get [plus_comm] to apply at the point where we want it, we can\n introduce a local lemma stating that [n + m = m + n] (for\n the particular [m] and [n] that we are talking about here), prove\n this lemma using [plus_comm], and then use this lemma to do the\n desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Exercise: 4 stars (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction. *)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite plus_assoc. rewrite plus_assoc.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\". rewrite plus_comm. reflexivity.\n rewrite H. reflexivity.\nQed.\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one.) You may find that [plus_swap] comes in\n handy. *)\n\nTheorem mult_S_r : forall m n : nat,\n m * S n = m * n + m.\nProof.\n intros m n.\n induction m as [|m'].\n Case \"m = 0\". reflexivity.\n Case \"m = S m'\".\n simpl. rewrite IHm'.\n rewrite plus_n_Sm. rewrite plus_n_Sm.\n rewrite plus_assoc. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros n m.\n induction n as [|n'].\n Case \"n = 0\". rewrite mult_0_l. rewrite mult_0_r. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite mult_S_r. rewrite IHn'. rewrite plus_comm. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)\n\n(** Prove the following simple fact: *)\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\".\n simpl. rewrite IHn'. rewrite negb_involutive. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before hacking!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\nProof.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n destruct b.\n Case \"b = true\". reflexivity.\n Case \"b = false\". reflexivity.\nQed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n intros n m p H.\n induction p as [|p'].\n Case \"p = 0\". simpl. rewrite H. reflexivity.\n Case \"p = p'\". simpl. rewrite IHp'. reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros n. simpl. rewrite plus_0_r. reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros b c.\n destruct b.\n Case \"b = true\". simpl. destruct c.\n SCase \"c = true\". reflexivity.\n SCase \"c = false\". reflexivity.\n Case \"b = false\". reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n induction p as [|p'].\n Case \"p = 0\". rewrite mult_0_r. rewrite mult_comm. simpl. rewrite mult_0_r. reflexivity.\n Case \"p = S p'\".\n rewrite mult_S_r.\n rewrite mult_S_r.\n rewrite mult_S_r.\n rewrite <- plus_assoc.\n assert (H: n + (m * p' + m) = (m * p') + (n + m)).\n SCase \"Proof of assertion\".\n rewrite plus_comm. rewrite <- plus_assoc.\n assert (H': m + n = n + m).\n SSCase \"Proof of subassertion\". rewrite plus_comm. reflexivity.\n rewrite H'. reflexivity.\n rewrite H.\n assert (H1: n * p' + (m * p' + (n + m)) = (n * p' + m * p') + (n + m)).\n SCase \"Proof of subassertion\".\n rewrite plus_assoc. reflexivity.\n rewrite H1.\n rewrite IHp'.\n reflexivity.\n(* Sigh, too long *)\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros.\n induction n as [|n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite IHn'. rewrite mult_plus_distr_r. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\n(** Prove the following theorem. Putting [true] on the left-hand side\nof the equality may seem odd, but this is how the theorem is stated in\nthe standard library, so we follow suit. Since rewriting\nworks equally well in either direction, we will have no\nproblem using the theorem no matter which way we state it. *)\n\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\nProof.\n\n induction n as [|n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n\".\n simpl. rewrite IHn'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to. More precisely,\n [replace (t) with (u)] replaces (all copies of) expression [t] in\n the goal by expression [u], and generates [t = u] as an additional\n subgoal. This is often useful when a plain [rewrite] acts on the wrong\n part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)].\n*)\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros.\n rewrite plus_assoc. rewrite plus_assoc.\n replace (n + m) with (m + n).\n reflexivity.\n Case \"replace\". rewrite plus_comm. reflexivity.\nQed.\n\n(** [] *)\n\n\n(** **** Exercise: 3 stars (binary_commute) *)\n(** Recall the [increment] and [binary-to-unary] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that these functions commute -- that is, incrementing a binary\n number and then converting it to unary yields the same result as\n first converting it to unary and then incrementing.\n\n (Before you start working on this exercise, please copy the\n definitions from your solution to the [binary] exercise here so\n that this file can be graded on its own. If you find yourself\n wanting to change your original definitions to make the property\n easier to prove, feel free to do so.) *)\n\n(* Redefining *)\nFixpoint bin_to_nat (n : bin) : nat :=\n match n with\n | B => O\n | T n => (bin_to_nat n) + (bin_to_nat n)\n | M n => (bin_to_nat n) + (bin_to_nat n) + 1\n end.\n\nTheorem inc_bin_to_nat_commute:\n forall (b : bin),\n bin_to_nat (inc b) = S (bin_to_nat b).\nProof.\n induction b as [|b'|b'].\n Case \"b = B\". reflexivity.\n Case \"b = M b'\".\n simpl. rewrite IHb'. simpl. replace (S (bin_to_nat b')) with (bin_to_nat b' + 1).\n rewrite plus_assoc. reflexivity.\n SCase \"rewrite\". rewrite plus_comm. reflexivity.\n Case \"b = T b'\".\n simpl. rewrite <- plus_comm. reflexivity.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n the previous exercise to complete this one.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, it is not true!\n Explain what the problem is.\n\n (c) Define a function [normalize] from binary numbers to binary\n numbers such that for any binary number b, converting to a\n natural and then back to binary yields [(normalize b)]. Prove\n it.\n\n Again, feel free to change your earlier definitions if this helps\n here.\n*)\nFixpoint nat_to_bin (n : nat) : bin :=\n match n with\n | O => B\n | S n' => inc (nat_to_bin n')\n end.\n\nTheorem nat_to_bin_bin_to_nat_commute:\n forall (n : nat),\n bin_to_nat (nat_to_bin n) = n.\nProof.\n induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite inc_bin_to_nat_commute. rewrite IHn'. reflexivity.\nQed.\n\n(* (b) There are multiple valid representations of the same nat number in the binary system *)\n(* (c) *)\nFixpoint normalize_bin (b : bin) : bin :=\n match b with\n | B => B\n | T b' => match (normalize_bin b') with\n | B => B\n | b'' => T b''\n end\n | M b' => M (normalize_bin b')\n end.\n\nTheorem M_nat_to_bin_commute : forall (n : nat),\n M (nat_to_bin n) = nat_to_bin (n + n + 1).\nProof.\n induction n; intros.\n simpl. reflexivity.\n simpl.\n assert (n + S n + 1 = S (n + n + 1)).\n rewrite plus_S_assoc. rewrite plus_0_r. rewrite plus_S_assoc.\n assert (n + n + 1 = S (n + n)).\n rewrite plus_comm. reflexivity.\n rewrite H. reflexivity.\n rewrite H. simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem bin_to_nat_nat_to_bin_normalized_commute:\n forall (b : bin),\n nat_to_bin (bin_to_nat b) = normalize_bin b.\nProof.\n induction b as [|b'|b'].\n Case \"b = B\". reflexivity.\n Case \"b = M b'\". simpl. rewrite <- IHb'. rewrite M_nat_to_bin_commute. reflexivity.\n Case \"b = T b'\". simpl. rewrite <- IHb'.\nAbort.\n\n\n(** [] *)\n\n(* ###################################################################### *)\n(** * Advanced Material *)\n\n(** ** Formal vs. Informal Proof *)\n\n(** \"Informal proofs are algorithms; formal proofs are code.\" *)\n\n(** The question of what, exactly, constitutes a \"proof\" of a\n mathematical claim has challenged philosophers for millennia. A\n rough and ready definition, though, could be this: a proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true.\n That is, a proof is an act of communication.\n\n Now, acts of communication may involve different sorts of readers.\n On one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is a simple mechanical check that\n [P] can be derived from a certain set of formal logical rules, and\n the proof is a recipe that guides the program in performing this\n check. Such recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n thus necessarily _informal_. Here, the criteria for success are\n less clearly specified. A \"good\" proof is one that makes the\n reader believe [P]. But the same proof may be read by many\n different readers, some of whom may be convinced by a particular\n way of phrasing the argument, while others may not be. One reader\n may be particularly pedantic, inexperienced, or just plain\n thick-headed; the only way to convince them will be to make the\n argument in painstaking detail. But another reader, more familiar\n in the area, may find all this detail so overwhelming that they\n lose the overall thread. All they want is to be told the main\n ideas, because it is easier to fill in the details for themselves.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader. In practice, however,\n mathematicians have developed a rich set of conventions and idioms\n for writing about complex mathematical objects that, within a\n certain community, make communication fairly reliable. The\n conventions of this stylized form of communication give a fairly\n clear standard for judging proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can ignore\n the informal ones! Formal proofs are useful in many ways, but\n they are _not_ very efficient ways of communicating ideas between\n human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this as a proof. For a human,\n however, it is difficult to make much sense of it. If you're used\n to Coq you can probably step through the tactics one after the\n other in your mind and imagine the state of the context and goal\n stack at each point, but if the proof were even a little bit more\n complicated this would be next to impossible. Instead, a\n mathematician might write it something like this: *)\n(** - _Theorem_: For any [n], [m] and [p],\n n + (m + p) = (n + m) + p.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n 0 + (m + p) = (0 + m) + p.\n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n n' + (m + p) = (n' + m) + p.\n We must show\n (S n') + (m + p) = ((S n') + m) + p.\n By the definition of [+], this follows from\n S (n' + (m + p)) = S ((n' + m) + p),\n which is immediate from the induction hypothesis. [] *)\n\n(** The overall form of the proof is basically similar. This is\n no accident: Coq has been designed so that its [induction] tactic\n generates the same sub-goals, in the same order, as the bullet\n points that a mathematician would write. But there are\n significant differences of detail: the formal proof is much more\n explicit in some ways (e.g., the use of [reflexivity]) but much\n less explicit in others (in particular, the \"proof state\" at any\n given point in the Coq proof is completely implicit, whereas the\n informal proof reminds the reader several times where things\n stand). *)\n\n(** Here is a formal proof that shows the structure more\n clearly: *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, advanced (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative.\n\n Proof: (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n\n Theorem: [true = beq_nat n n] for any [n].\n\n Proof: (* FILL IN HERE *)\n[]\n *)\n\n(* $Date: 2014-02-19 21:36:35 -0500 (Wed, 19 Feb 2014) $ *)\n", "meta": {"author": "IgnoredAmbience", "repo": "software-foundations", "sha": "e1e75f8bdfd83979b13f5ce7574659c7925a6cf6", "save_path": "github-repos/coq/IgnoredAmbience-software-foundations", "path": "github-repos/coq/IgnoredAmbience-software-foundations/software-foundations-e1e75f8bdfd83979b13f5ce7574659c7925a6cf6/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.18242552380635635, "lm_q1q2_score": 0.059775059016526196}} {"text": "(*|\n###############################\nCoq coercions and goal matching\n###############################\n\n:Link: https://stackoverflow.com/q/45482430\n|*)\n\n(*|\nQuestion\n********\n\nAssume I have the following setup:\n|*)\n\nInductive exp: Set :=\n| CE: nat -> exp.\n\nInductive adt: exp -> Prop :=\n| CA: forall e, adt e.\n\nCoercion nat_to_exp := CE.\n\nLtac my_tactic := match goal with\n | [ |- adt (CE ?N) ] => apply (CA (CE N))\n end.\n\n(*| And I try to prove a simple theorem using the custom tactic: |*)\n\nTheorem silly: adt 0.\nProof.\n Fail my_tactic. (* .unfold .fails .no-goals *)\nAbort.\n\n(*|\nThis fails, because the goal is not of the form ``adt (CE ?N)`` but of\nthe form ``adt (nat_to_exp ?N)`` (This is shown explicitly when using\n``Set Printing Coercions``).\n\nTrying to prove a slightly different theorem works:\n|*)\n\nTheorem silly: adt (CE 0).\nProof.\n my_tactic.\nQed.\n\n(*|\nPossible workarounds I know of:\n\n- Not using coercions.\n- Unfolding coercions in the tactic (with ``unfold nat_to_exp``). This\n alleviates the problem slightly, but fails as soon as a new coercion\n is introduced the tactic doesn't know about.\n\nIdeally, I would like the pattern matching to succeed if the pattern\nmatches after unfolding all definitions (The definitions should not\nstay unfolded, of course).\n\nIs this possible? If not, are there reasons why it is not possible?\n|*)\n\n(*|\nAnswer\n******\n\nYou can directly declare the constructor ``CE`` as a coercion rather\nthan wrapping it as ``nat_to_exp`` like so:\n|*)\n\nCoercion CE : nat >-> exp.\n\n(*|\nThe proof then goes through without any issue. If you insist on naming\nyour coercion (e.g. because it's a compound expression rather than a\nsingle constructor), you can change your tactics so that it handles\nnon unfolded coercions explicitly:\n|*)\n\nReset my_tactic. (* .none *)\nLtac my_tactic := match goal with\n | [ |- adt (CE ?N) ] => apply (CA (CE N))\n | [ |- adt (nat_to_exp ?N) ] => apply (CA (CE N))\n end.\n\n(*|\n----\n\n**A:** There is also syntactic sugar for the case when constructors\nare coercions:\n|*)\n\nReset exp. (* .none *)\nInductive exp: Set := | CE :> nat -> exp.\n\n(*|\nautomatically declares ``CE`` as a coercion (notice that I used ``:>``\ninstead of ``:`` for ``CE``).\n\n**A:** You can also use e.g. ``cbv delta.`` before pattern-matching on\nthe goal to unfold transparent definitions. Then your original\n``my_tactic`` would work.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/coq-coercions-and-goal-matching.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.16238004274695514, "lm_q1q2_score": 0.05952685930197585}} {"text": "Require Import String.\nRequire Import bin_rels.\nRequire Import eq_rel.\nRequire Import universe.\nRequire Import LibTactics.\nRequire Import tactics.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Program.Tactics.\nRequire Import Omega.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Init.Notations.\nRequire Import UsefulTypes.\nRequire Import Coq.Classes.DecidableClass.\nRequire Import Coq.Classes.Morphisms.\nRequire Import list.\n\nRequire Import Recdef.\nRequire Import Eqdep_dec.\nRequire Import varInterface.\nRequire Import terms.\nOpen Scope list_scope.\n\n(** printing # $\\times$ #×# *)\n(** printing <=> $\\Leftrightarrow$ #⇔# *)\n(** printing $ $\\times$ #×# *)\n(** printing & $\\times$ #×# *)\n\n\n(** Here are some handy definitions that will\n reduce the verbosity of some of our later definitions\n*)\n\nGeneralizable Variable Opid.\n\nSection terms2Generic.\n\nContext {NVar VarClass} {deqnvar : Deq NVar} {varcl freshv} {varclass: @VarType NVar VarClass deqnvar varcl freshv} \n`{hdeq: Deq Opid} {gts : GenericTermSig Opid}.\nNotation NTerm := (@NTerm NVar Opid).\nNotation BTerm := (@BTerm NVar Opid).\n\nDefinition nobnd (f:NTerm) : BTerm := bterm [] f.\n\n\n(** %\\noindent \\\\*% We define similar abstractions for other [Opid]s.\n This document does not show them. As mentioned before, one can click\n at the hyperlinked filename that is closest above to open a\n webpage that shows complete contents of this file.\n*)\n\n\nLemma fold_nobnd :\n forall t, bterm [] t = nobnd t.\nProof using.\n unfold nobnd; auto.\nQed.\n\n\n(*\nDefinition mk_esquash (R : NTerm) :=\n oterm (Can NEsquash) [nobnd R].\n*)\n\n\n\n(* Picks a variable that is not in the set of free variables of a given term *)\nDefinition newvar (t : NTerm) := fresh_var (free_vars t).\n\n(* Delete. use flat_map instead *)\nFixpoint free_vars_list (terms : list NTerm) :=\n match terms with\n | [] => []\n | t :: ts => free_vars t ++ free_vars_list ts\n end.\n\n\n\n\n(* ------ SIMPLE OPERATORS ON TERMS ------ *)\n\n(*\nFixpoint depth (t : NTerm) : nat :=\n match t with\n | vterm _ => 1\n | oterm op bterms => lsum map depth_bterm bterms\n end\n with depth_bterm (lv : list NVar) (nt : NTerm) :=\n match bt with\n | bterm lv nt => depth nt\n end.\n*)\n\nEnd terms2Generic.\n\n\nFixpoint size {NVar:Type} {Opid:Type} (t : @NTerm NVar Opid) : nat :=\n match t with\n | vterm _ => 1\n | oterm op bterms => S (addl (map (@size_bterm NVar _) bterms))\n end\n with size_bterm {NVar:Type} {Opid:Type} (bt: @BTerm NVar Opid) :nat :=\n match bt with\n | bterm lv nt => @size NVar Opid nt\n end.\n\nFixpoint wft {NVar:Type} {Opid:Type} {gts : GenericTermSig Opid} (t : @NTerm NVar Opid) : bool :=\n match t with\n | vterm _ => true\n | oterm o bts =>\n andb (beq_list deq_nat (map (@num_bvars NVar _) bts) (OpBindings o))\n (ball (map wftb bts))\n end\nwith wftb {NVar:Type} {Opid:Type} {gts : GenericTermSig Opid} (bt : @BTerm NVar Opid) : bool :=\n match bt with\n | bterm vars t => wft t\n end.\n\nScheme Equality for list.\n\n \n Fixpoint NTerm_beq {NVar:Type} {Opid:Type} `{Deq NVar} `{Deq Opid} \n (t1 t2: @NTerm NVar Opid) : bool :=\n match (t1, t2) with\n | (terms.vterm v1, terms.vterm v2) => decide (v1=v2)\n | (terms.oterm o1 lbt1, terms.oterm o2 lbt2)\n => andb (decide (o1=o2)) (list_beq _ (@BTerm_beq NVar Opid _ _) lbt1 lbt2)\n |(_,_)=> false\n end\nwith BTerm_beq {NVar:Type} {Opid:Type} `{Deq NVar} `{Deq Opid} (t1 t2: \n@BTerm NVar Opid) : bool :=\n match (t1, t2) with\n | (terms.bterm lv1 t1, terms.bterm lv2 t2) => \n andb (decide (lv1=lv2)) (@NTerm_beq NVar Opid _ _ t1 t2)\n end.\n\n(*\nLemma NTerm_beq_correct {NVar:Type} {Opid:Type} `{Deq NVar} `{Deq Opid} \n(a b: @terms.NTerm NVar Opid): NTerm_beq a b = true <=> a = b.\nAdmitted.\n*)\n\nSection terms3Generic.\n\nContext {NVar VarClass} {deqnvar : Deq NVar} \n {varcl freshv} {varclass: @VarType NVar VarClass deqnvar varcl freshv} \n `{hdeq: Deq Opid} {gts : GenericTermSig Opid}.\nNotation NTerm := (@NTerm NVar Opid).\nNotation BTerm := (@BTerm NVar Opid).\n\n(* ------ INDUCTION ON TERMS ------ *)\n\n\nLemma size_subterm2 :\n forall (o:Opid) (lb : list BTerm) (b : BTerm) ,\n LIn b lb\n -> size_bterm b < size (oterm o lb).\nProof using.\n simpl. induction lb; intros ? Hin; inverts Hin as; simpl; try omega.\n intros Hin. apply IHlb in Hin; omega.\nQed.\n\nLemma size_subterm3 :\n forall (o:Opid) (lb : list BTerm) (nt : NTerm) (lv : list NVar) ,\n LIn (bterm lv nt) lb\n -> size nt < size (oterm o lb).\nProof using.\n introv X.\n apply size_subterm2 with (o:=o) in X. auto.\nQed.\n\nLemma NTerm_better_ind3 :\n forall P : NTerm -> Type,\n (forall n : NVar, P (vterm n))\n -> (forall (o : Opid) (lbt : list BTerm),\n (forall (nt: NTerm),\n size nt < size (oterm o lbt)\n -> P nt\n )\n -> P (oterm o lbt)\n )\n -> forall t : NTerm, P t.\nProof using.\n intros P Hvar Hbt.\n assert (forall n t, size t = n -> P t) as Hass.\n Focus 2. intros. apply Hass with (n := size t) ; eauto; fail.\n \n induction n as [n Hind] using comp_ind_type.\n intros t Hsz.\n destruct t.\n apply Hvar.\n apply Hbt. introv Hs.\n apply Hind with (m := size nt) ; auto.\n subst.\n assert(size nt < size (oterm o l)); auto.\nQed.\n\n\nLemma NTerm_better_ind2 :\n forall P : NTerm -> Type,\n (forall n : NVar, P (vterm n))\n -> (forall (o : Opid) (lbt : list BTerm),\n (forall (nt nt': NTerm) (lv: list NVar),\n (LIn (bterm lv nt) lbt)\n -> size nt' <= size nt\n -> P nt'\n )\n -> P (oterm o lbt)\n )\n -> forall t : NTerm, P t.\nProof using.\n intros P Hvar Hbt.\n apply NTerm_better_ind3; eauto.\n intros ? ? H.\n apply Hbt.\n intros ? ? ? Hin Hs. apply H.\n eapply le_lt_trans;[apply Hs|].\n eapply size_subterm3; eauto.\nQed.\n\nLemma NTerm_BTerm_ind :\n forall (PN : NTerm -> Type) (PB : BTerm -> Type),\n (forall n : NVar, PN (vterm n))\n -> (forall (o : Opid) (lbt : list BTerm),\n (forall b,\n (LIn b lbt) -> PB b\n )\n -> PN (oterm o lbt)\n )\n -> (forall (lv: list NVar) (nt : NTerm),\n PN nt -> PB (bterm lv nt)\n )\n -> ((forall t : NTerm, PN t) * (forall t : BTerm, PB t)).\nProof using.\n introv Hv Hind Hb.\n assert (forall A B, A -> (A -> B) -> (A*B)) as H by tauto.\n apply H; clear H.\n- apply NTerm_better_ind2; auto. \n introv Hx. apply Hind. introv Hin. destruct b. eauto.\n- intro Hnt. intro b. destruct b. eauto. \nQed.\n\nLemma NTerm_better_ind :\n forall P : NTerm -> Type,\n (forall n : NVar, P (vterm n))\n -> (forall (o : Opid) (lbt : list BTerm),\n (forall (nt : NTerm) (lv: list NVar),\n (LIn (bterm lv nt) lbt) -> P nt\n )\n -> P (oterm o lbt)\n )\n -> forall t : NTerm, P t.\nProof using.\n introv Hv Hind. apply NTerm_better_ind2; auto. \n introv Hx. apply Hind. introv Hin. eapply Hx in Hin; eauto. \nQed.\n\n\nTactic Notation \"nterm_ind\" ident(h) ident(c) :=\n induction h using NTerm_better_ind;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\nTactic Notation \"nterm_ind\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n induction h as I using NTerm_better_ind;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\nTactic Notation \"nterm_ind1\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n induction h as I using NTerm_better_ind;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\nTactic Notation \"nterm_ind1s\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n induction h as I using NTerm_better_ind2;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\n\nLemma num_bvars_on_bterm :\n forall (l:list NVar) (n : NTerm),\n num_bvars (@bterm NVar Opid l n) = length l.\nProof using.\n unfold num_bvars; simpl; sp.\nQed.\n\n\n\nDefinition wf_term (t : NTerm) := wft t = true.\n\nDefinition wf_bterm (bt : BTerm) := wftb bt = true.\n\nLemma wf_term_proof_irrelevance :\n forall t,\n forall x y : wf_term t,\n x = y.\nProof using.\n intros.\n apply UIP_dec.\n apply bool_dec.\nQed.\n\nDefinition wf_term_extract :=\n fun (t : NTerm) (x : wf_term t) =>\n match x return (x = match x with\n | eq_refl => eq_refl (wft t)\n end)\n with\n | eq_refl => eq_refl eq_refl\n end.\n\n(*\nDefinition wf_term_extract1 :=\n fun (t : NTerm) (x : wf_term t) =>\n match x in _ = b return match b with\n | true => x = eq_refl (wft t)\n end\n with\n | eq_refl => eq_refl eq_refl\n end.\n\nLemma wf_term_extract2 :\n forall t : NTerm,\n forall x : wf_term t,\n x = eq_refl (wft t).\n*)\n\n(*Lemma yyy : forall A (x : A) (pf : x = x), pf = eq_refl x.\nLemma xxx : forall t (x : wft t = true), x = eq_refl (wft t).*)\n\nLemma nt_wf_eq :\n forall t,\n nt_wf t <=> wf_term t.\nProof using.\n clear varclass varcl freshv deqnvar VarClass.\n unfold wf_term.\n nterm_ind t as [|o lbt ind] Case; simpl; intros.\n\n - Case \"vterm\".\n split; sp.\n\n - Case \"oterm\".\n split_iff SCase.\n\n + SCase \"->\"; intro w.\n inversion w; subst.\n allrw.\n rewrite beq_list_refl; simpl.\n trw ball_true; sp.\n alltrewrite in_map_iff; sp; subst.\n apply_in_hyp wf; destruct wf; allsimpl.\n discover; sp. firstorder.\n\n + SCase \"<-\"; sp.\n remember (beq_list deq_nat (map num_bvars lbt) (OpBindings o)).\n destruct b; allsimpl; sp.\n alltrewrite ball_true.\n constructor; sp.\n destruct l.\n apply_in_hyp e.\n constructor.\n apply e.\n apply_hyp.\n alltrewrite in_map_iff.\n exists (bterm l n); simpl; sp.\n\n remember (OpBindings o).\n clear Heql.\n revert l Heqb.\nLocal Opaque deq_nat.\n induction lbt; allsimpl.\n destruct l; allsimpl; sp.\n destruct l; allsimpl; sp.\n rewrite decide_decideP in Heqb.\n destruct (decideP (num_bvars a = n)); subst; sp.\n apply cons_eq.\n apply IHlbt; sp.\n apply ind with (lv := lv); sp.\nQed.\n\nLemma nt_wf_implies :\n forall t, nt_wf t -> wf_term t.\nProof using.\n sp; apply nt_wf_eq; sp.\nQed.\n\nLemma wf_term_eq :\n forall t, wf_term t <=> nt_wf t.\nProof using.\n intro; generalize (nt_wf_eq t); sp.\n symm; auto.\nQed.\n\nLemma bt_wf_eq :\n forall bt, bt_wf bt <=> wf_bterm bt.\nProof using.\n sp; split; intro w.\n inversion w; subst; unfold wf_bterm; simpl.\n fold (wf_term nt).\n apply wf_term_eq; auto.\n destruct bt; allunfold wf_bterm; allsimpl.\n fold (wf_term n) in w.\n constructor.\n apply nt_wf_eq; auto.\nQed.\n\n(*\nInductive nt_wfb (t:NTerm) : bool :=\n match t with\n | vterm _ => true\n | bterm _ rt => nt_wfb rt\n | oterm o lnt : (eq map (num_bvars) lnt OpBindings o).\n*)\n\nDefinition closedb (t : NTerm) := nullb (free_vars(t)).\nDefinition closed_bt (bt : BTerm) := free_vars_bterm bt = [].\n\n\nDefinition isprogram_bt (bt : BTerm) := closed_bt bt # bt_wf bt.\n\n(** Our definition [isprog] below is is logically equivalent to [isprogram],\n but unlike [isprogram], it is easy to prove that\n for any [t], all members(proofs) of [isprog t] are equal.\n An interested reader can look at the lemma\n %\\coqexternalref{UIP\\_dec}\n {http://coq.inria.fr/distrib/8.4pl2/stdlib/Coq.Logic.Eqdep\\_dec}\n {\\coqdocdefinition{UIP\\_dec}}% from that standard library.\n As mentioned before, clicking on the lemma name in \n the previous sentence should open\n the corresponding webpage of the Coq standard library.\n Instead, one can also look at the lemma [isprog_eq] below and\n safely ignore these technicalites.\n\n*)\nDefinition isprog (t : NTerm) := (nullb (free_vars t) && wft t) = true.\n\nDefinition isprog_bt (bt : BTerm) :=\n (nullb (free_vars_bterm bt) && wftb bt) = true.\n\nDefinition isprog_vars (vs : list NVar) (t : NTerm) :=\n (sub_vars (free_vars t) vs && wft t) = true.\n\nLemma closed_nt :\n forall op bts,\n closed (oterm op bts)\n <=>\n forall bt, LIn bt bts -> closed_bt bt.\nProof using.\n sp; unfold closed, closed_bt; simpl; trw flat_map_empty; split; sp.\nQed.\n\nLemma closed_nt0 : forall o (nt:NTerm), closed (oterm o [bterm [] nt]) -> closed nt.\nProof using.\n intros. unfold closed in H. simpl in H. apply app_eq_nil in H. repnd.\n clears_last. unfold closed. assumption.\nQed.\n\nLemma closed_null_free_vars :\n forall (t:NTerm),\n closed t <=> null (free_vars t).\nProof using.\n unfold closed; sp.\n trw null_iff_nil; sp.\nQed.\n\nLemma isprog_proof_irrelevance :\n forall t,\n forall x y : isprog t,\n x = y.\nProof using.\n intros.\n apply UIP_dec.\n apply bool_dec.\nQed.\n\nLemma isprog_vars_proof_irrelevance :\n forall t vs,\n forall x y : isprog_vars vs t,\n x = y.\nProof using.\n intros.\n apply UIP_dec.\n apply bool_dec.\nQed.\n\n\nRequire Import tactics.\nLemma isprogram_eq :\n forall t,\n isprogram t <=> isprog t.\nProof using.\n unfold isprog, isprogram.\n nterm_ind t Case; simpl; intros.\n\n - Case \"vterm\".\n split; sp. unfold closed in *; allsimpl; sp.\n\n - Case \"oterm\".\n split_iff SCase.\n\n + SCase \"->\".\n intros i; destruct i as [ cl wf ].\n inversion cl; subst.\n inversion wf; subst.\n repeat (rw andb_eq_true).\n rewrite fold_assert.\n allrw <- null_iff_nil.\n rw ball_map_true.\n rw assert_nullb; sp.\n\n rewrite fold_assert.\n rw assert_beq_list; auto.\n\n destruct x; allsimpl.\n fold (wf_term n).\n apply wf_term_eq.\n apply_in_hyp p; inversion p; subst; sp.\n\n + SCase \"<-\"; intros.\n repeat (allrewrite andb_true); repd.\n allrw fold_assert.\n allrw assert_nullb.\n allrw null_iff_nil.\n allrw assert_beq_list.\n allrw ball_map_true; sp.\n constructor; sp.\n apply_in_hyp p.\n destruct l; allsimpl.\n constructor.\n allfold (wf_term n).\n apply wf_term_eq; auto.\nQed.\n\nLemma isprogram_implies :\n forall t, isprogram t -> isprog t.\nProof using.\n sp; apply isprogram_eq; sp.\nQed.\n\nLemma isprog_implies :\n forall t : NTerm, isprog t -> isprogram t.\nProof using.\n sp; apply isprogram_eq; sp.\nQed.\n\nLemma isprog_eq :\n forall t, isprog t <=> isprogram t.\nProof using.\n intro; symm; apply isprogram_eq; auto.\nQed.\n\nLemma isprogram_bt_eq :\n forall bt,\n isprogram_bt bt <=> isprog_bt bt.\nProof using.\n intro; unfold isprogram_bt, isprog_bt, closed_bt; split; sp.\n allrw; simpl.\n fold (wf_bterm bt).\n apply bt_wf_eq; auto.\n alltrewrite andb_eq_true; sp.\n allrewrite fold_assert.\n alltrewrite assert_nullb.\n alltrewrite null_iff_nil; sp.\n destruct bt; constructor.\n alltrewrite andb_eq_true; sp; allsimpl.\n allfold (wf_term n).\n apply nt_wf_eq; auto.\nQed.\n\nLemma isprog_vars_eq :\n forall t vs,\n isprog_vars vs t <=> subsetv (free_vars t) vs # nt_wf t.\nProof.\n unfold isprog_vars; sp.\n rw andb_eq_true.\n rewrite fold_assert.\n rewrite assert_sub_vars.\n rw nt_wf_eq; sp.\nQed.\n\nLemma isprog_vars_if_isprog :\n forall vs t, isprog t -> isprog_vars vs t.\nProof using.\n introv ip.\n rw isprog_vars_eq.\n rw isprog_eq in ip.\n destruct ip; sp.\n unfold closed in *; allrw; sp.\nQed.\n\nLemma isprog_vars_app_l :\n forall t vs1 vs2,\n isprog_vars vs2 t\n -> isprog_vars (vs1 ++ vs2) t.\nProof using.\n sp; alltrewrite isprog_vars_eq; sp.\n unfold subset in *.\n apply subset_app_l; sp.\nQed.\n\nDefinition areprograms ts := forall t, LIn t ts -> isprogram t.\n\nLemma areprograms_nil : areprograms [].\nProof using.\n unfold areprograms; simpl; sp.\nQed.\n\nLemma areprograms_snoc :\n forall t ts,\n areprograms (snoc ts t) <=> areprograms ts # isprogram t.\nProof using.\n unfold areprograms; sp; split; sp; try (apply_hyp; rw in_snoc; sp).\n alltrewrite in_snoc; sp; subst; sp.\nQed.\n\nLemma areprograms_cons :\n forall t ts, areprograms (t :: ts) <=> isprogram t # areprograms ts.\nProof using.\n unfold areprograms; sp; simpl; split; sp; subst; sp.\nQed.\n\nLemma areprograms_app :\n forall ts1 ts2,\n areprograms (ts1 ++ ts2) <=> areprograms ts1 # areprograms ts2.\nProof using.\n unfold areprograms; sp; split; sp.\n apply_hyp; rw in_app_iff; sp.\n apply_hyp; rw in_app_iff; sp.\n alltrewrite in_app_iff; sp.\nQed.\n\nLemma isprogram_vterm :\n forall v, isprogram (vterm v) <=> False.\nProof using.\n unfold isprogram, closed; simpl; sp; split; sp.\nQed.\n\n(*\nLtac repnd :=\n repeat match goal with\n | [ H : _ # _ |- _ ] =>\n let name := fresh H in destruct H as [name H]\n | [ H : _ # _ |- _ ] =>\n let name := fresh H in destruct H as [name H]\n end.\n*)\n\nTheorem isprogram_ot_iff :\n forall o bts,\n isprogram (oterm o bts)\n <=>\n (map num_bvars bts = OpBindings o\n # forall bt, LIn bt bts -> isprogram_bt bt).\nProof using.\n intros. sp_iff Case.\n\n - Case \"->\".\n intros Hisp.\n unfold isprogram in Hisp. repnd.\n inverts Hisp0 as Hflat. inverts Hisp.\n split;auto. intros bt Hin.\n unfold isprogram_bt.\n rw flat_map_empty in Hflat.\n apply_in_hyp p; sp.\n\n - Case \"<-\".\n intros eq; destruct eq as [Hmap Hstclose].\n unfold isprogram, closed.\n\n split; try (constructor); auto;\n try (simpl; apply flat_map_empty);\n intros a ain;\n apply Hstclose in ain; inversion ain; sp.\nQed.\n\nTheorem nt_wf_ot_implies :\n forall lv o (nt1 : NTerm) bts,\n nt_wf (oterm o bts)\n -> LIn (bterm lv nt1) bts\n -> nt_wf nt1.\nProof using. intros ? ? ? ? Hwf Hin. inverts Hwf as Hwf Hmap.\n assert (bt_wf (bterm lv nt1)) as Hbf by (apply Hwf; auto).\n inverts Hbf. auto.\nQed.\n\n\nLemma newvar_prop :\n forall (t: NTerm), ! LIn (newvar t) (free_vars t).\nProof using.\n unfold newvar; sp.\n allapply fresh_var_not_in; sp.\nQed.\n\n\n(*\nLemma newvar_not_in_free_vars :\n forall (t: NTerm),\n ! LIn nvarx (free_vars t)\n -> newvar t = nvarx.\nProof using.\n sp.\n unfold newvar.\n apply fresh_var_nvarx; sp.\nQed.\n\nLemma newvar_prog :\n forall t,\n isprog t\n -> newvar t = nvarx.\nProof using.\n sp.\n unfold newvar.\n apply isprog_eq in H.\n inversion H.\n unfold closed in H0.\n rewrite H0; sp.\nQed.\n*)\n\n\n(*\n(** A value is a program with a canonical operator *)\nInductive isvalue : NTerm -> [univ] :=\n | isvl : forall (c : CanonicalOp) (bts : list BTerm ),\n isprogram (oterm (Can c) bts)\n -> isvalue (oterm (Can c) bts).\n\n\nInductive isovalue : NTerm -> Prop :=\n | isovl : forall (c : CanonicalOp) (bts : list BTerm),\n nt_wf (oterm (Can c) bts)\n -> isovalue (oterm (Can c) bts).\n\nLemma isvalue_closed :\n forall t, isvalue t -> closed t.\nProof using.\n introv isv; inversion isv.\n allunfold isprogram; sp.\n unfold isprogram in *.\n tauto.\nQed.\n\nLemma isvalue_program :\n forall t, isvalue t -> isprogram t.\nProof using.\n introv isv; inversion isv; sp.\nQed.\n*)\n\n(* ------ programs ------ *)\n\nDefinition WTerm := { t : NTerm | wf_term t }.\nDefinition WBTerm := { bt : BTerm | wf_bterm bt }.\n\n\n(*\n (* first of all, isprog is NOT a boolean. also, the reader will\n be left wondering what UIP_dec is*)\n\n where [isprog] is the Boolean version of [isprogram]\n (using a Boolean version of [isprogram] makes it easy to prove that\n closed terms are equal by proving that the underlying [NTerm]s are\n equals using [UIP_dec]). \n\n*)\n\n(**\n\n The [CTerm] type below is useful in compactly stating definitions\n that are only meaningful for closed terms. A [CTerm] is a pair\n of an [NTerm] [t] and a proof that [t] is closed.\n This [CTerm] type will be handy in compactly \n defining the Nuprl type system where types are defined as partial\n equivalence relations on closed terms.\n \n*)\n\nDefinition CTerm := { t : NTerm | isprog t }.\nDefinition get_cterm (t : CTerm) := let (a,_) := t in a.\n\n\nDefinition BCTerm := { bt : BTerm | isprog_bt bt }.\n\n\n(**\n\n We also define a type of terms that specifies what are the possible\n free variables of its inhabitants. A term is a [(CVTerm vs)] term\n if the set of its free variables is a subset of [vs]. This type is\n also useful to define the Nuprl type system. For example, to define\n a closed family of types such as a closed function type of the form\n $\\NUPRLfunction{x}{A}{\\NUPRLsuba{B}{z}{x}}$, $A$ has to be closed\n and the free variables of $B$ can only be $z$.\n\n*)\n\nDefinition CVTerm (vs : list NVar) := { t : NTerm | isprog_vars vs t }.\n\n\nDefinition CVTerm3 := forall a b c, CVTerm [a;b;c].\n\n\nDefinition mk_cvterm (vs : list NVar) (t : NTerm) (p : isprog_vars vs t) :=\n exist (isprog_vars vs) t p.\n\n\n\nDefinition get_wterm (t : WTerm) := let (a,_) := t in a.\nDefinition get_cvterm (vs : list NVar) (t : CVTerm vs) := let (a,_) := t in a.\nDefinition get_bcterm (bt : BCTerm) := let (a,_) := bt in a.\n\nDefinition selectbt (bts: list BTerm) (n:nat) : BTerm :=\n nth n bts (bterm [] (vterm nvarx)).\n\n(*\nDefinition isnoncan (t: NTerm):=\nmatch t with\n| vterm _ => False\n| oterm o _ => match o with\n | Can _ => False\n | NCan _ => True\n end\nend.\n*)\nLemma wf_cterm :\n forall t, wf_term (get_cterm t).\nProof.\n introv; ( repeat match goal with\n | [ H : CTerm |- _ ] => destruct H\n | [ H : CVTerm _ |- _ ] => destruct H\n end\n); simpl.\n allrw isprog_eq; unfold isprogram in *; repnd; allrw nt_wf_eq; sp.\nQed.\n\n\nEnd terms3Generic.\n\nLtac irr_step :=\n match goal with\n | [ H1 : isprog ?a, H2 : isprog ?a |- _ ] =>\n assert (H2 = H1) by apply isprog_proof_irrelevance; subst\n | [ H1 : isprog_vars ?vs ?a, H2 : isprog_vars ?vs ?a |- _ ] =>\n assert (H2 = H1) by apply isprog_vars_proof_irrelevance; subst\n end.\n\nLtac irr := repeat irr_step.\n\nLtac destruct_cterms :=\n repeat match goal with\n | [ H : CTerm |- _ ] => destruct H\n | [ H : CVTerm _ |- _ ] => destruct H\n end.\n\nLtac dest_cterm H :=\n let t := type of H in\n match goal with\n | [ x : CTerm |- _ ] =>\n match t with\n | context[x] => destruct x\n end\n | [ x : CVTerm _ |- _ ] =>\n match t with\n | context[x] => destruct x\n end\n end.\n\n(** A faster version of destruct_cterms. We avoid destructing all of them. *)\nLtac dest_cterms H := repeat (dest_cterm H).\n\nLtac clear_deps h :=\n repeat match goal with\n | [ H : context[h] |- _ ] => clear H\n end.\nTactic Notation \"nterm_ind\" ident(h) ident(c) :=\n induction h using NTerm_better_ind;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\nTactic Notation \"nterm_ind\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n induction h as I using NTerm_better_ind;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\nTactic Notation \"nterm_ind1\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n induction h as I using NTerm_better_ind;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\nTactic Notation \"nterm_ind1s\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n induction h as I using NTerm_better_ind2;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\n\n\nLtac fold_terms_step :=\n match goal with\n | [ |- context[bterm [] ?x] ] => fold (nobnd x)\n | [ |- context[vterm ?v] ] => fold (mk_var v)\n end.\n\nLtac fold_terms := repeat fold_terms_step.\n\n\n\n\nLtac boolvar_step :=\n match goal with\n | [ |- context[beq_var ?v ?v] ] => rw <- beq_var_refl\n | [ |- context[memvar ?v ?s] ] =>\n let name := fresh \"b\" in\n remember (memvar v s) as name;\n match goal with\n | [ H : name = memvar v s |- _ ] =>\n symmetry in H;\n destruct name;\n [ rewrite fold_assert in H;\n trw_h assert_memvar H;\n simpl in H\n | trw_h not_of_assert H;\n trw_h assert_memvar H;\n simpl in H\n ]\n end\n | [ |- context[beq_var ?v1 ?v2] ] =>\n let name := fresh \"b\" in\n remember (beq_var v1 v2) as name;\n match goal with\n | [ H : name = beq_var v1 v2 |- _ ] =>\n destruct name;\n [ apply beq_var_true in H; subst\n | apply beq_var_false in H\n ]\n end\n | [ H : context[beq_var ?v ?v] |- _ ] => rw <- beq_var_refl in H\n end.\n\nLtac boolvar := repeat boolvar_step.\nLtac unfold_all_mk :=\n allunfold mk_var\n ;allunfold nobnd.\n\n\nHint Immediate wf_cterm : wf.\n(* Hint Constructors isvalue. *)\nHint Constructors nt_wf bt_wf.\n\nLtac rwselectbt :=\nmatch goal with\n|[ H1: bterm ?lv ?nt = selectbt ?lbt ?n , H2 : context [selectbt ?lbt ?n] |- _ ] => rewrite <- H1 in H2\n|[ H1: selectbt ?lbt ?n = bterm ?lv ?nt , H2 : context [selectbt ?lbt ?n] |- _ ] => rewrite H1 in H2\n|[ H1: bterm ?lv ?nt = selectbt ?lbt ?n |- context [selectbt ?lbt ?n] ] => rewrite <- H1\n|[ H1: selectbt ?lbt ?n = bterm ?lv ?nt |- context [selectbt ?lbt ?n] ] => rewrite H1\nend.\n\nTactic Notation \"ntermd\" ident(h) \"as\" simple_intropattern(I) ident(c) :=\n destruct h as I;\n [ Case_aux c \"vterm\"\n | Case_aux c \"oterm\"\n ].\nLtac prove_or := \n try (left;cpx;fail);\n try (right;cpx;fail);\n try (left;left;cpx;fail);\n try (left;right;cpx;fail);\n try (right;left;cpx;fail);\n try (right;right;cpx;fail).\n\nLtac fold_selectbt :=\nmatch goal with\n[ |- context [nth ?n ?lbt (bterm [] (vterm nvarx))] ] =>\n fold (selectbt lbt n)\nend.\n\n(*\nLtac d_isnoncan H := \n match type of H with\n isnoncan ?t => let tlbt := fresh t \"lbt\" in let tnc := fresh t \"nc\" in\n let tt := fresh \"temp\" in \n destruct t as [tt|tt tlbt];[inverts H as H; fail|];\n destruct tt as [tt|tnc]; [inverts H as H; fail|]\n end.\n*)\n\nSection terms4Generic.\n\nContext {NVar VarClass} {deqnvar : Deq NVar} {varcl freshv} \n{varclass: @VarType NVar VarClass deqnvar varcl freshv} \n `{hdeq : Deq Opid} {gts : GenericTermSig Opid}.\nNotation NTerm := (@NTerm NVar Opid).\nNotation BTerm := (@BTerm NVar Opid).\n\nLemma cterm_eq :\n forall t u,\n get_cterm t = get_cterm u\n -> t = u.\nProof using.\n introv; destruct_cterms; simpl; sp; subst.\n rewrite dep_pair_eq\n with (eq0 := eq_refl)\n (pb := i); auto.\n apply UIP_dec.\n apply bool_dec.\nQed.\n\nLemma cvterm_eq :\n forall vs t u,\n get_cvterm vs t = get_cvterm vs u\n -> t = u.\nProof using.\n introv; destruct_cterms; simpl; sp; subst.\n rewrite dep_pair_eq\n with (eq0 := eq_refl)\n (pb := i); auto.\n apply UIP_dec.\n apply bool_dec.\nQed.\n\n\n\nLemma free_vars_cterm :\n forall t, free_vars (get_cterm t) = [].\nProof using.\n introv; destruct_cterms; simpl.\n allrw isprog_eq; unfold isprogram in *; repnd; allrw; sp.\nQed.\n\nDefinition mk_cterm (t : NTerm) (p : isprogram t) :=\n exist isprog t (isprogram_implies t p).\n\nDefinition mk_ct (t : NTerm) (p : isprog t) := exist isprog t p.\n\nDefinition mk_wterm (t : NTerm) (p : wf_term t) := exist (@wf_term NVar _ _) t p.\n\nDefinition mk_wterm' (t : NTerm) (p : nt_wf t) :=\n exist wf_term t (nt_wf_implies t p).\n\n(* Definition iscvalue (t : CTerm) : Type :=\n isvalue (get_cterm t).\n *)\n \nLemma mk_cv_pf :\n forall (vs : list NVar) (t:CTerm),\n @isprog_vars NVar _ Opid _ vs (@get_cterm NVar _ Opid _ t).\nProof.\n destruct t; simpl.\n rw @isprog_eq in i; destruct i.\n rw @isprog_vars_eq; simpl; sp.\n unfold closed in *.\n allrw; sp.\nQed.\n\n(** From a closed term, we can always make a term whose variables\n * are contained in vs: *)\nDefinition mk_cv (vs : list NVar) (t : @CTerm NVar _ Opid _) : @CVTerm NVar _ Opid _ vs :=\n exist (isprog_vars vs) (@get_cterm NVar _ Opid _ t) (mk_cv_pf vs t).\n\n\nLemma programs_bt_to_program :\n forall bts : list BCTerm,\n forall op,\n map (fun bt => num_bvars (get_bcterm bt)) bts = OpBindings op\n -> isprogram (oterm op (map get_bcterm bts)).\nProof using.\n sp; unfold isprogram; sp.\n rewrite closed_nt in *; sp.\n allrw in_map_iff; sp; subst.\n destruct a; destruct x; allsimpl.\n clear_deps i.\n rw <- @isprogram_bt_eq in i.\n inversion i; sp.\n constructor; sp.\n allrw in_map_iff; sp; subst.\n destruct a; destruct x; allsimpl.\n clear_deps i.\n rw <- @isprogram_bt_eq in i.\n inversion i; sp.\n rewrite <- H.\n rewrite map_map; unfold compose; sp.\nQed.\n\n(* ---------------------------------------------------- *)\n\n\nDefinition list_rel {A} {B} (R : A -> B -> Prop) (ll : list A) (lr : list B) :=\n (length ll = length lr)\n #\n forall p1 p2 , LIn (p1, p2) (combine ll lr)\n -> R p1 p2.\n\n(** gets the nth element of a list of bterms. if n is out of range, it returns the variable x\n*)\n\n(* Howe defines T(L) as B_0(L) (no bterm constructor)\n and T_0(L) as closed terms of T(L)\n so, a term T_0(L) cannot have the vterm constructor\n at the root\n This a superset of T_0(L)\n*)\nInductive not_vbterm: NTerm -> Type :=\n | nvbo : forall (op : Opid) (bts : list BTerm ),\n not_vbterm (oterm op bts).\n\n(** this should not be required anymore. a closed NTerm is automatically not_vbterm. Proof below*)\nDefinition not_vbtermb (t : NTerm) : bool :=\n match t with\n | oterm _ _ => true\n | _ => false\n end.\n\nTheorem closed_notvb : forall t: NTerm , (closed t) -> (not_vbterm t).\nProof using.\n intros ? Hclose. destruct t.\n unfold closed in Hclose. simpl in Hclose.\n inversion Hclose. constructor.\nQed.\n\nTheorem selectbt_in :\n forall n (bts : list BTerm),\n n < length bts -> LIn (selectbt bts n) bts.\nProof using.\n intros. unfold selectbt.\n apply nth_in; auto.\nQed.\n\nLemma selectbt_cons :\n forall bt (bts : list BTerm) n,\n selectbt (bt :: bts) n = if beq_nat n 0 then bt else selectbt bts (n - 1).\nProof using.\n unfold selectbt; simpl; sp.\n destruct n; simpl; sp.\n destruct n; simpl; sp.\nQed.\n\n(* Lemma isvalue_wf :\n forall c bts,\n isvalue (oterm (Can c) bts)\n -> map num_bvars bts = OpBindings (Can c).\nProof using. intros ? ? Hval.\n inverts Hval as Hpr. inverts Hpr as Hclose Hwf.\n inverts Hwf; auto.\nQed.\n *)\n\n(* Lemma isvalue_wf2: forall c bts,\n (isvalue (oterm (Can c) bts))\n -> length bts= length(OpBindings (Can c)).\nProof using. intros ? ? Hval. apply isvalue_wf in Hval.\n (* fequalhyp H length. why does this fail*)\n\n assert (length (map num_bvars bts) = length (OpBindings (Can c)))\n as Hlen by (rewrite Hval; reflexivity) .\n rewrite map_length in Hlen. auto.\nQed.\n *)\n\nNotation bterm := (@bterm NVar Opid).\nLemma isprogram_wf3: forall o bts,\n (isprogram (oterm o bts))\n -> forall n, (n (num_bvars (selectbt bts n))= nth n (OpBindings o) 0.\nProof using. intros ? ? Hprog. apply isprogram_ot_iff in Hprog. repnd.\n intros ? Hlt.\nassert(nth n (map num_bvars bts) 0= nth n (OpBindings o) 0)\n as Hnth by (rewrite Hprog0; reflexivity).\n unfold selectbt.\n instlemma (@map_nth BTerm nat num_bvars\n bts (bterm [] (vterm nvarx))) as Hmapn.\n assert((num_bvars (bterm [] (vterm nvarx))) =0).\n compute; auto . rewrite H in Hmapn. rewrite Hmapn in Hnth. auto.\nQed.\n\n(* Lemma isvalue_wf3: forall o bts,\n (isvalue (oterm o bts))\n -> forall n, (n (num_bvars (selectbt bts n))= nth n (OpBindings o) 0.\nProof using. intros ? ? Hval ? Hlt.\n inverts Hval as Hprog. apply isprogram_wf3 with (n:=n) in Hprog ; auto.\nQed. *)\n\nTheorem var_not_prog : forall v, (isprogram (vterm v)) -> void.\nProof using.\n unfold not. intros v Hpr.\n inversion Hpr as [Hclose ?].\n unfold closed in Hclose. simpl in Hclose. inversion Hclose.\nQed.\n\nLemma implies_isprogram_bt :\n forall bts,\n (forall l : BTerm, LIn l bts -> bt_wf l)\n -> flat_map free_vars_bterm bts = []\n -> forall bt : BTerm, LIn bt bts -> isprogram_bt bt.\nProof using.\n intros bts Hbf Hflat ? Hin.\n unfold isprogram_bt, closed_bt; split; auto.\n rw flat_map_empty in Hflat. apply Hflat; auto.\nQed.\n\nTheorem ntbf_wf :\n forall (nt : NTerm) , (bt_wf (bterm [] nt)) -> nt_wf nt.\nProof using.\n introv Hin. inverts Hin. auto.\nQed.\n\nLemma implies_isprogram_bt0 :\n forall t ,\n isprogram (t)\n -> isprogram_bt (bterm [] t).\nProof using.\n unfold isprogram_bt, closed_bt, isprogram, closed; simpl; sp.\nQed.\n\nTheorem is_program_ot_bts0 :\n forall o nt,\n isprogram nt\n -> OpBindings o = [0]\n -> isprogram (oterm o [bterm [] nt]).\nProof using.\n introv Hpr Hop. unfold isprogram, closed in *; simpl; repnd.\n split;auto. autorewrite with list. auto.\n\n constructor; sp; allsimpl; sp; subst; sp.\nQed.\n\nTheorem is_program_ot_nth_nobnd :\n forall o nt1 bts,\n isprogram (oterm o bts)\n -> LIn (bterm [] nt1) bts\n -> isprogram nt1.\nProof using. intros ? ? ? Hisp Hin. apply isprogram_ot_iff in Hisp. repnd.\n apply Hisp in Hin. inverts Hin as Hclose Hbf. inverts Hbf.\n unfold closed_bt in Hclose. simpl in Hclose.\n split; auto.\nQed.\n\nTheorem is_program_ot_fst_nobnd :\n forall o nt1 bts,\n isprogram (oterm o ((bterm [] nt1):: bts))\n -> isprogram nt1.\nProof using.\n intros ? ? ? Hisp.\n apply is_program_ot_nth_nobnd with (nt1:=nt1) in Hisp; sp.\nQed.\n\nTheorem is_program_ot_snd_nobnd :\n forall o bt1 nt2 bts, isprogram (oterm o ((bt1)::(bterm [] nt2):: bts))\n -> isprogram nt2.\nProof using. intros ? ? ? ? Hisp.\n apply is_program_ot_nth_nobnd with (nt1:=nt2) in Hisp; simpl; sp.\nQed.\n\n\nTheorem is_program_ot_subst1 :\n forall o nt1 bts nt1r,\n isprogram (oterm o ((bterm [] nt1):: bts))\n -> isprogram nt1r\n -> isprogram (oterm o ((bterm [] nt1r):: bts)).\nProof using. intros ? ? ? ? Hisp Hispst. unfold isprogram.\n unfold closed. simpl.\n inverts Hisp as Hclos Hisp. unfold closed in Hclos. simpl in Hclos.\n apply app_eq_nil in Hclos. repnd. \n inverts Hispst as Hclosst Hispst. unfold closed in Hclosst.\n rewrite Hclosst. rewrite Hclos. split;auto.\n invertsn Hisp. constructor;auto.\n intros ? Hin. inverts Hin. constructor; auto.\n apply Hisp. right; auto.\nQed.\n\nTheorem is_program_ot_subst2 :\n forall o bt1 nt2 bts nt2r,\n isprogram (oterm o (bt1::(bterm [] nt2):: bts))\n -> isprogram nt2r\n -> isprogram (oterm o (bt1::(bterm [] nt2r):: bts)).\nProof using. intros ? ? ? ? ? Hisp Hispst. unfold isprogram.\n unfold closed. simpl.\n inverts Hisp as Hclos Hisp. inverts Hispst as Hclosst Hwfst.\n unfold closed in *. simpl.\n unfold closed in Hclos. allsimpl.\n simpl_vlist. rewrite Hclosst. rewrite Hclos0.\n simpl. split;auto.\n inverts Hisp as Hisp Hm. constructor;simpl; auto.\n intros ? Hin. dorn Hin;subst;auto. apply Hisp; auto.\n left; auto.\n dorn Hin; subst; auto.\n apply Hisp. right;right;auto.\nQed.\n\n\nTheorem is_program_ot_nth_wf :\n forall lv o nt1 bts,\n isprogram (oterm o bts)\n -> LIn (bterm lv nt1) bts\n -> nt_wf nt1.\nProof using. intros ? ? ? ? Hisp Hin. apply isprogram_ot_iff in Hisp. repnd.\n assert (isprogram_bt (bterm lv nt1)) as Hass by (apply Hisp; auto).\n inverts Hass as Hass Hbt. inversion Hbt; auto.\nQed.\n\nLemma combine_vars_map_sp :\n forall vars,\n combine vars (map (@vterm NVar Opid) vars) = map (fun v => (v, vterm v)) vars.\nProof using.\n induction vars; simpl; sp.\n rewrite IHvars; sp.\nQed.\n\nLemma combine_vars_map :\n forall A,\n forall f : NVar -> A,\n forall vars,\n combine vars (map f vars) = map (fun v => (v, f v)) vars.\nProof using.\n induction vars; simpl; sp.\n rewrite IHvars; sp.\nQed.\n\n\nTheorem in_selectbt: forall bt (bts : list BTerm), LIn bt bts ->\n {n : nat $ n < length bts # selectbt bts n = bt}.\nProof using.\n intros ? ? Hin. induction bts. inverts Hin.\n invertsn Hin.\n - exists 0. split; simpl; auto. omega.\n - destruct IHbts; auto. exists (S x). repnd.\n split; simpl; try omega. auto.\nQed.\n\n(**useful for rewriting in complicated formulae*)\nTheorem ntot_wf_iff: forall o bts, nt_wf (oterm o bts)\n <=> map num_bvars bts = OpBindings o # forall n : nat,\n n < length bts -> bt_wf (selectbt bts n).\nProof using. introv. sp_iff Case; introv H.\n Case \"->\". inverts H as Hbf Hmap. split; auto.\n introv Hlt. apply Hbf. apply selectbt_in; auto.\n Case \"<-\". repnd. constructor; auto.\n introv Hin. apply in_selectbt in Hin.\n exrepnd. rw <- Hin0;auto.\nQed.\n\n(**useful for rewriting in complicated formulae*)\nTheorem bt_wf_iff: forall lv (nt : NTerm), bt_wf (bterm lv nt)\n <=> nt_wf nt.\nProof using. sp_iff Case; introv H.\n Case \"->\". inverts H as Hwf; auto.\n Case \"<-\". constructor; auto.\nQed.\n\n\nDefinition nvarxbt := bterm [] (vterm nvarx) .\n\n\nLemma isprogram_get_cterm :\n forall a, isprogram (get_cterm a).\nProof using.\n destruct a; sp; simpl.\n rw isprogram_eq; sp.\nQed.\n\n\nLemma oterm_eq :\n forall o1 o2 l1 l2,\n o1 = o2\n -> l1 = l2\n -> (@oterm NVar Opid) o1 l1 = oterm o2 l2.\nProof using.\n sp; allrw; sp.\nQed.\n\nNotation oterm := (@oterm NVar Opid).\nNotation vterm := (@vterm NVar Opid).\n\nInductive liftRBt (R : (NTerm) -> (NTerm) -> Prop)\n : (@BTerm) -> (@BTerm) -> Prop :=\n liftRbt : forall lv ntl ntr, R ntl ntr\n -> liftRBt R\n (bterm lv ntl)\n (bterm lv ntr).\n\nRequire Import SetoidList.\n(* Move to SquiggleEq and heterogenize *)\nLemma liftRBTeqlist (R : NTerm -> NTerm -> Prop) es lbt:\n eqlistA (liftRBt R) (map (bterm []) es) lbt\n -> exists esp, eqlistA R es esp /\\ lbt = map (bterm []) esp.\nProof using.\n revert es lbt.\n induction es; intros ? Heq; inverts Heq.\n + eexists. split. constructor. refl.\n + inverts H1. apply IHes in H3. exrepnd. eexists. split. econstructor; eauto.\n subst. auto.\nQed.\n\nLemma liftRbt_eqlista (R : NTerm -> NTerm -> Prop) vs vsp:\n eqlistA R vs vsp ->\n eqlistA (liftRBt R) (map (bterm []) vs) (map (bterm []) vsp).\nProof using.\n intros H. induction H; constructor; auto.\n constructor; auto.\nQed.\n\n Lemma liftRbtsiglist {dcon:Type} (R: NTerm -> NTerm -> Prop):\n forall (bs : list (dcon * BTerm)) (lbtp : list BTerm),\n eqlistA (liftRBt R) (map snd bs) lbtp ->\n map (fun x : dcon * BTerm => num_bvars (snd x)) bs = map num_bvars lbtp.\nProof using.\n intros ? ? Heq. remember (map snd bs) as msb. revert dependent bs.\n induction Heq; intros; destruct bs; invertsn Heqmsb; auto.\n simpl. f_equal; eauto. \n inverts H; auto. \nQed.\n\nLemma bterm_eq :\n forall l1 l2 n1 n2,\n l1 = l2\n -> n1 = n2\n -> bterm l1 n1 = bterm l2 n2.\nProof using.\n sp; allrw; sp.\nQed.\n\nTheorem selectbt_map {gtsi gtso}: forall lbt n \n (f: (@terms.BTerm NVar gtsi) -> (@terms.BTerm NVar gtso)) ,\n n selectbt (map f lbt) n = f (selectbt lbt n).\nProof using.\n induction lbt; introv Hlt. inverts Hlt.\n simpl. destruct n; subst. reflexivity.\n unfold selectbt in *. allsimpl.\n assert (n < (length lbt)) by omega.\n auto.\nQed.\n\n\nTheorem eq_maps_bt: forall (B : Type) (f : BTerm -> B) \n (g : BTerm -> B) (la lc : list BTerm),\n length la = length lc \n -> (forall n : nat, n < length la \n -> f (selectbt la n) = g (selectbt lc n)) \n -> map f la = map g lc.\nProof using. unfold selectbt. introv H2 H3. apply eq_maps2 in H3; auto. \nQed.\n\nLemma vterm_inj: injective_fun vterm.\nProof using.\n introv Hf. inverts Hf. auto.\nQed.\n\nLemma map_eq_lift_vterm: forall lvi lvo, \n map vterm lvi = map vterm lvo -> lvi = lvo.\nProof using.\n intros.\n apply map_eq_injective with (f:=vterm); auto.\n exact vterm_inj.\nQed.\n\n(*\nGlobal Instance deqNterm : Deq NTerm.\nProof.\n intros a b. exists (NTerm_beq a b).\n apply NTerm_beq_correct.\nDefined.\n*)\n\nGlobal Instance deq_nterm : DeqSumbool NTerm.\nProof using deqnvar hdeq.\n intros x.\n nterm_ind1 x as [v1 | o1 lbt1 Hind] Case; intros y.\n\n - Case \"vterm\".\n destruct y as [v2 | o lbt2]; [ | right; intro Hc; inverts Hc].\n destruct (decideP (v1=v2)); subst;\n [ left; auto; fail\n | right; intro Hc; inverts Hc; sp\n ].\n\n - Case \"oterm\".\n destruct y as [v2 | o2 lbt2]; [ right; intro Hc; inverts Hc | ].\n destruct (decideP (o1=o2)); subst; [ | right; intro Hc; inverts Hc;sp].\n assert ((lbt1=lbt2) + (lbt1 <> lbt2)) as Hbt.\n Focus 2.\n dorn Hbt; subst; [left; auto | right; intro Hc; inverts Hc;sp ]; fail.\n revert lbt2.\n induction lbt1.\n destruct lbt2; [left; auto | right; intro Hc; inverts Hc;sp ]; fail.\n destruct lbt2; [ right; intro Hc; inverts Hc; fail | ].\n destruct a as [lv1 nt1]. destruct b as [lv2 nt2].\n lapply (IHlbt1);\n [ | introv Hin; apply Hind with (lv:=lv); eauto; right; auto].\n intro bdec.\n destruct (bdec lbt2); subst; [ | right; intro Hc; inverts Hc;sp;fail ].\n destruct (decideP (lv1=lv2));\n subst; [ | right; intro Hc; inverts Hc;sp;fail ].\n destruct (Hind nt1 lv2 (injL(eq_refl _) ) nt2); subst;\n [left; auto | right; intro Hc; inverts Hc;sp ].\nDefined.\n\nLemma lin_lift_vterm :\n forall v lv,\n LIn v lv <=> LIn (vterm v) (map vterm lv).\nProof using.\n induction lv; [sp | ]. simpl.\n rw <- IHlv; split; intros hp; try (dorn hp); sp; subst; sp.\n inverts hp. sp.\nQed.\n\n\nLemma map_removevars:\nforall lvi lvr,\n map vterm (remove_nvars lvi lvr)\n = @lremove _ _ (map vterm lvi) (map vterm lvr).\nProof using.\n(* simpl.\n clear gts. *)\n intros. apply map_diff_commute.\n introv Hc. inverts Hc. auto.\nQed.\n\nOpen Scope list_scope.\n\nDefinition all_vars_bt (bt : BTerm) := free_vars_bterm bt ++ bound_vars_bterm bt.\n\nLemma all_vars_ot : forall o lbt, \n eq_set\n (all_vars (oterm o lbt))\n (flat_map all_vars_bt lbt).\nProof using.\n intros. unfold all_vars. simpl. unfold all_vars_bt.\n rewrite <- flat_map_fapp. refl.\nQed.\n\n\nTheorem nil_remove_nvars_iff: forall l1 l2 : list NVar,\n (remove_nvars l1 l2) = [] <=> (forall x : NVar, LIn x l2 -> LIn x l1).\nProof using.\n intros. rw <- null_iff_nil. apply null_remove_nvars.\nQed.\n\nTheorem nil_rv_single_iff: forall lv v ,\n (remove_nvars lv [v]) = [] <=> (LIn v lv).\nProof using.\n intros. rw <- null_iff_nil. rw null_remove_nvars.\n split; intro Hyp.\n apply Hyp. left. auto.\n introv Hin. apply in_list1 in Hin; subst; auto.\nQed.\n\nTheorem selectbt_eq_in: forall lv nt lbt n,\n bterm lv nt = selectbt lbt n\n -> n < length lbt\n -> LIn (bterm lv nt) lbt.\nProof using.\n introv Heq Hlt. rw Heq.\n apply selectbt_in; trivial.\nQed.\n\nLemma flat_map_closed_terms:\n forall (lnt : list NTerm), lforall closed lnt\n -> flat_map free_vars lnt = [].\nProof using.\n unfold lforall, closed. introv Hfr.\n apply flat_map_empty. trivial.\nQed.\n\nLemma flat_map_progs:\n forall lnt, lforall isprogram lnt\n -> flat_map free_vars lnt = [].\nProof using.\n unfold lforall, closed. introv Hfr.\n apply flat_map_empty. introv Hin.\n apply Hfr in Hin. inverts Hin. auto.\nQed.\n\nTheorem disjoint_lbt_bt :\n forall vs lbt lv nt,\n disjoint vs (flat_map bound_vars_bterm lbt)\n -> LIn (bterm lv nt) lbt\n -> disjoint vs lv.\nProof using.\n introv Hink1 Hin.\n apply disjoint_sym in Hink1; rw disjoint_flat_map_l in Hink1.\n apply Hink1 in Hin.\n simpl in Hin. rw disjoint_app_l in Hin.\n repnd; apply disjoint_sym. trivial.\nQed.\n\n\n\nDefinition selectnt (n:nat) (lnt : list NTerm): NTerm :=\n nth n lnt (vterm nvarx).\n\nLemma deq_bterm : DeqSumbool BTerm.\nProof using deqnvar hdeq.\n intros btx bty. destruct btx as [lvx ntx].\n destruct bty as [lvy nty].\n destruct (deq_nterm ntx nty);\n destruct (decideP (lvx=lvy)); subst;sp;\n right; introv Heq;\n inverts Heq; cpx.\nQed. \n\n\nInductive nt_wf2 : NTerm -> [univ] :=\n | wfvt2 : forall nv : NVar, nt_wf2 (vterm nv)\n | wfot2 : forall (o : Opid) (lnt : list BTerm),\n length lnt = length (OpBindings o)\n -> (forall n, n < (length lnt) ->\n num_bvars (selectbt lnt n) = nth n (OpBindings o) 0\n # bt_wf2 (selectbt lnt n))\n -> nt_wf2 (oterm o lnt)\n with bt_wf2 : BTerm -> [univ] :=\n wfbt2 : forall (lnv : list NVar) (nt : NTerm),\n nt_wf2 nt -> bt_wf2 (bterm lnv nt).\n\n(** mainly for convenience in proofs *)\nTheorem selectbt_in2: forall (n : nat) (bts : list BTerm),\n n < length bts -> { bt : BTerm & (LIn bt bts # (selectbt bts n)=bt) }.\nProof using.\n intros. exists (selectbt bts n).\n split;auto. apply selectbt_in; trivial.\nDefined.\n\nLemma nt_wf_nt_wf2 : forall t, (nt_wf t) <=> (nt_wf2 t).\nProof using.\n assert (0= num_bvars (bterm [] (vterm nvarx))) as XX by auto.\n nterm_ind1 t as [?| o lbt Hind] Case; split; introv Hyp; sp.\n - inverts Hyp as Hl Hyp. constructor. apply_length Hyp;sp.\n introv hlt. unfold selectbt. rw <- Hyp.\n rw XX. rw map_nth; sp;[].\n fold (selectbt lbt n).\n pose proof (selectbt_in2 n lbt hlt) as Hbt.\n exrepnd. destruct bt as [lv nt].\n applydup Hind in Hbt1.\n rw Hbt0. constructor.\n apply Hl in Hbt1. inverts Hbt1.\n sp3.\n - inverts Hyp as Hl Hyp. constructor.\n + introv Hin. apply in_selectbt in Hin; auto;[].\n exrepnd. applydup Hyp in Hin1.\n rw Hin0 in Hin2. destruct l as [lv nt].\n constructor. exrepnd. invertsn Hin2.\n applysym selectbt_in in Hin1. rw Hin0 in Hin1.\n apply Hind in Hin1. sp3.\n + eapply (tiff_snd (eq_list2 _ 0 _ _)). rw map_length.\n split; auto;[]. introv Hlt. apply Hyp in Hlt.\n repnd. rw <- Hlt0.\n rw XX. rw map_nth. sp.\nQed.\n\n\n\nDefinition bin_rel_nterm :=\n binrel_list (vterm nvarx).\n\nTheorem isprogram_ot_implies_eauto2 :\n forall o bts,\n isprogram (oterm o bts)\n -> (forall n, n< length bts -> isprogram_bt (selectbt bts n)).\nProof using.\n introv Hp Hlt. apply isprogram_ot_iff in Hp.\n apply selectbt_in in Hlt. exrepnd.\n eauto with slow.\nQed.\n\n\nLemma isprogram_bt_nobnd :\n forall t ,\n isprogram_bt (bterm [] t)\n -> isprogram (t).\nProof using.\n unfold isprogram_bt, closed_bt, isprogram, closed; intros ? Hxx; spc; allsimpl.\n match goal with\n [H: (bt_wf _) |- _ ] => inverts H\n end.\n assumption.\nQed.\n\n\nLemma free_vars_list_app :\n forall (ts1 ts2 : list NTerm),\n free_vars_list (ts1 ++ ts2)\n = free_vars_list ts1 ++ free_vars_list ts2.\nProof using.\n induction ts1; simpl; sp.\n rw IHts1; simpl.\n rw app_assoc; sp.\nQed.\n\n\n\nLemma isprog_ntwf_eauto : forall t, isprogram t -> nt_wf t.\nProof using. unfold isprogram. spc.\nQed.\n\nTheorem isprogram_ot_if_eauto :\n forall o bts,\n map num_bvars bts = OpBindings o\n -> (forall bt, LIn bt bts -> isprogram_bt bt)\n -> isprogram (oterm o bts).\nProof using.\n intros. apply isprogram_ot_iff;spc.\nQed.\n\nDefinition getOpidBTerms (t: NTerm) : option (Opid * list BTerm):=\nmatch t with\n| terms.vterm _ => None\n| terms.oterm o lb => Some (o, lb)\nend.\n\nLemma isprogramd :\n forall v, isprogram v\n -> {o : Opid $ {lbt : list BTerm $ v = oterm o lbt}}.\nProof using.\n introv Hpr.\n invertsn Hpr.\n destruct v; inverts Hpr.\n eexists; eexists ; eauto.\nQed.\n\n\n(* Move *)\nLemma fold_combine : forall {A B} (v:A) (t:B), \n [(v,t)] = (combine [v] [t]).\nProof using.\n intros. simpl. auto.\nQed.\n\n\n\n(* Lemma noncan_not_value : forall e,\n isnoncan e\n -> isvalue e\n -> False.\nProof using.\n introv Hisnc Hisv.\n destruct e as [?| o lbt]; allsimpl; cpx.\n destruct o; cpx.\n inverts Hisv.\nQed. *)\n\nTheorem isprogram_ot_if_eauto2 :\n forall o bts,\n map num_bvars bts = OpBindings o\n -> (forall n, n< length bts -> isprogram_bt (selectbt bts n))\n -> isprogram (oterm o bts).\nProof using.\n introv Hn Hp. apply isprogram_ot_iff; dands; spcf.\n introv Hin. apply in_selectbt in Hin. exrepnd.\n eauto with slow.\n rw <- Hin0.\n eauto with slow. \nQed.\n\n\n\nLemma closed_implies:\n forall (t : NTerm),\n closed t -> (forall x, !LIn x (free_vars t)).\nProof using.\n introv cl.\n unfold closed in cl.\n allrw; simpl; try (complete sp).\nQed.\n\n\n\n\nLemma list_nil_btwf: forall es,\n(forall l : BTerm, LIn l (map (bterm []) es) -> bt_wf l)\n<->\n(forall l : NTerm, LIn l es -> nt_wf l).\nProof using.\n intros ?.\n split; intros H ? Hin.\n- apply (bt_wf_iff []).\n apply H. apply in_map; auto. \n- apply in_map_iff in Hin. exrepnd. subst.\n constructor; auto. \nQed.\n\nRequire Import Coq.Program.Basics.\n\nOpen Scope program_scope.\n\nLemma flat_map_bterm_nil : forall gts lnt,\nflat_map free_vars_bterm\n (map ((@terms.bterm NVar gts) []) lnt) = \nflat_map free_vars lnt.\nProof.\n induction lnt; auto.\n simpl. f_equal; auto.\nQed.\n\nLemma flat_map_vterm : forall gts (lv: list NVar),\nflat_map free_vars_bterm\n (map ((@terms.bterm NVar gts) [] ∘ terms.vterm) lv) = lv.\nProof using.\n induction lv; auto.\n simpl. f_equal; auto.\nQed.\n\n\nLemma subset_flat_map_lbt:\nforall lbt (l lv : list NVar) (n : NTerm),\nLIn (bterm l n) lbt ->\nsubsetv (flat_map free_vars_bterm lbt) lv \n-> subsetv (free_vars n) (l ++ lv).\nProof using.\n intros ? ? ? ? Hin Hs.\n rewrite subset_flat_map in Hs.\n rewrite subsetv_prop.\n apply_clear Hs in Hin.\n simpl in Hin.\n rewrite subsetv_prop in Hin.\n intros x Hn. specialize (Hin x).\n rewrite in_remove_nvars in Hin.\n rewrite in_app_iff; destruct (dmemvar x l); cpx.\nQed.\n\nLemma select_selectbt : forall n lbt (b:BTerm),\nselect n lbt = Some b\n<-> (selectbt lbt n = b /\\ n < length lbt).\nProof using.\n intros ? ? ?.\n split; intros Hin.\n- pose proof Hin.\n apply select_lt in Hin. split;[|assumption].\n apply nth_select1 with (def:= bterm [] (vterm nvarx))in Hin.\n unfold selectbt.\n congruence.\n- repnd. eapply nth_select3; auto.\n apply Hin0.\nQed.\n\n\nLemma size_pos : forall (t:NTerm), \n 0<(size t).\nProof.\n intros. destruct t; simpl; omega.\nQed.\n\nDefinition preservesVarclass (ta tb : NTerm) :Prop :=\nforall vc,\nvarsOfClass (all_vars ta) vc\n-> varsOfClass (all_vars tb) vc.\n\nDefinition preservesVarclassBT (ta tb : BTerm) :Prop :=\nforall vc,\nvarsOfClass (all_vars_bt ta) vc\n-> varsOfClass (all_vars_bt tb) vc.\n\nLemma subsetAllVarsLbt : forall o lbt bt, \n LIn bt lbt -> subset (all_vars_bt bt) (all_vars (oterm o lbt)).\nProof.\n intros ? ? ? Hin.\n rewrite all_vars_ot.\n unfold all_vars_bt.\n eapply subset_trans;\n [|apply subset_flat_map_r; apply Hin].\n apply subset_refl.\nQed.\n\nLemma varsOfClassOT : forall o lbt c,\n varsOfClass (all_vars (oterm o lbt)) c\n -> forall bt, LIn bt lbt -> varsOfClass (all_vars_bt bt) c.\nProof using.\n intros ? ? ? Hv ? Hin ? Hinn.\n apply Hv. revert Hinn.\n apply subsetAllVarsLbt.\n assumption.\nQed.\n\nLemma map0lbt : forall (lbt: list BTerm),\nmap num_bvars lbt = repeat 0 (Datatypes.length lbt)\n-> lbt = map (bterm []) (map get_nt lbt).\nProof using.\n induction lbt; simpl; auto.\n intro Hn.\n destruct a. inverts Hn as Hn Hnn. unfold num_bvars in Hn.\n simpl in Hn. dlist_len_name l Hh.\n simpl. f_equal. eauto.\nQed.\n\n\nDefinition allvars_bterm : forall lv nt,\n eq_set \n (all_vars_bt (bterm lv nt))\n (lv ++ all_vars nt).\nProof using.\n clear.\n intros ? ?. apply eqsetv_prop.\n intro. unfold all_vars, all_vars_bt.\n simpl.\n repeat rewrite in_app_iff.\n repeat rewrite in_remove_nvars.\n destruct (decideP (LIn x lv)); (* firstorder does not know about decidability *)\n firstorder.\nQed.\n\n\nLemma flat_map_free_var_vterm: forall lv:list NVar, flat_map free_vars (map vterm lv)=lv.\nProof using.\n induction lv;sp;simpl;f_equal;sp.\nQed.\n\nLemma flat_map_bound_var_vterm: forall lv:list NVar, flat_map bound_vars (map vterm lv)=[].\nProof using.\n induction lv;sp;simpl;f_equal;sp.\nQed.\n\nLemma size_subterm4 :\n forall (lb : list (BTerm)) (nt : NTerm) (lv : list NVar),\n LIn (bterm lv nt) lb -> size nt < S (addl (map size_bterm lb)).\nProof using.\n induction lb; auto; simpl; try tauto;[].\n intros ? ? Hin. dorn Hin.\n- subst. simpl. omega.\n- apply IHlb in Hin. omega.\nQed.\n\n\nLemma subsetAllVarsLbt2 : forall lbt lv (nt : NTerm), \n LIn (bterm lv nt) lbt -> subset (all_vars nt) (flat_map all_vars_bt lbt).\nProof using.\n clear.\n intros.\n eapply subset_trans;\n [|eapply subset_flat_map_r; eauto].\n rewrite allvars_bterm.\n apply subset_app_l.\n refl.\nQed.\n\nLemma subsetBoundVarsLbt3 : forall (lbt : list BTerm) (lv : list NVar) (nt : NTerm), \n LIn (bterm lv nt) lbt -> subset lv (flat_map bound_vars_bterm lbt).\nProof using.\n intros.\n eapply subset_trans;\n [|eapply subset_flat_map_r; eauto].\n apply subset_app_r.\n refl.\nQed.\n\n\nLemma flat_map_bterm_nil_allvars:\n forall (lnt : list NTerm),\n flat_map all_vars_bt (map (terms.bterm []) lnt) = flat_map all_vars lnt.\nProof using.\n intros. rewrite flat_map_map.\n apply eq_flat_maps.\n intros ? Hin.\n unfold compose, all_vars_bt.\n simpl.\n refl.\nQed.\n\nLemma subsetAllVarsLbt3\n : forall (lbt : list BTerm) (lv : list NVar) (nt : terms.NTerm),\n LIn (bterm lv nt) lbt -> subset lv (flat_map all_vars_bt lbt).\nProof.\n introv Hin.\n eapply transitivity;\n [|apply subset_flat_map_r; eauto].\n rewrite allvars_bterm.\n apply subset_app_r. refl. \nQed.\n\nEnd terms4Generic.\n\nLtac varsOfClassSimpl :=\nrepeat match goal with\n[ H: varsOfClass (all_vars (oterm ?o ?lbt)) true |- _ ] =>\n specialize (varsOfClassOT _ _ _ H); clear H; intro H;\n repeat match goal with\n | [HH : LIn _ lbt |- _] => apply (fun lin => (conj lin (H _ lin))) in HH\n end; repnd;\nrepeat match goal with\n[H:context [varsOfClass (all_vars_bt (bterm _ _)) true] |- _]\n => setoid_rewrite allvars_bterm in H (* if it fails, continuing may cause a loop *)\nend;\nrepeat rewrite @varsOfClassApp in *\nend.\n\n\n\n\n(* Move *)\nHint Rewrite @flat_map_bterm_nil @flat_map_free_var_vterm\n remove_nvars_eq : SquiggleEq.\n\n\nHint Rewrite @all_vars_ot @allvars_bterm : allvarsSimpl.\n\nHint Rewrite @all_vars_ot @allvars_bterm @varsOfClassApp : SquiggleEq.\n\n\nHint Resolve isprogram_ot_if_eauto : slow.\nHint Immediate isprogram_get_cterm.\nHint Resolve isprog_implies : isprog.\nHint Extern 100 (LIn _ _) => complete (simpl; sp) : isprog.\nHint Resolve nt_wf_implies : slow.\nHint Resolve nt_wf_eq: slow.\nHint Resolve is_program_ot_nth_nobnd : slow.\nHint Resolve deq_bterm.\nHint Immediate deq_nterm.\nHint Immediate isprogram_get_cterm.\nHint Resolve isprog_ntwf_eauto : slow.\nTactic Notation \"disjoint_reasoningv\" :=\n (allunfold all_vars); repeat( progress disjoint_reasoning).\nLtac destruct_bterms:=\nrepeat match goal with\n[bt : BTerm |- _] =>\n let btlv := fresh bt \"lv\" in\n let btnt := fresh bt \"nt\" in\n destruct bt as [btlv btnt]\nend.\n\nLtac noRepDis :=\n(repeat match goal with\n[H: no_repeats [] |- _] => clear H\n|[H: no_repeats (_::_) |- _] =>\n let Hnrd := fresh \"Hnrd\" in\n apply no_repeats_as_disjoint in H;\n destruct H as [Hnrd H]\nend); disjoint_reasoningv; \nrewrite in_single_iff in *; subst; tauto; try tauto.\n\n(* try to move to list.v . disjoint_reasoningv performs \n some non-list-based unfolding which may\n be done using a database *)\nLtac inauto:=\n(repeat match goal with\n[H: no_repeats [] |- _] => clear H\n|[H: no_repeats (_::_) |- _] =>\n let Hnrd := fresh \"Hnrd\" in\n apply no_repeats_as_disjoint in H;\n destruct H as [Hnrd H]\nend); disjoint_reasoningv; \nunfold subset in *;\nunfold disjoint in *;\nrepeat match goal with \n| [H:context[LIn _ (_::_) ] |- _] => simpl in H; try setoid_rewrite or_false_r in H\n| [|- context[LIn _ (_::_)]] => simpl; try setoid_rewrite or_false_r\n| [H:context[LIn _ (flat_map _ _) ] |- _] => setoid_rewrite in_flat_map in H\n| [|- context[LIn _ (flat_map _ _)]] => setoid_rewrite in_flat_map\n| [H:context[LIn _ (map _ _)]|- _] => setoid_rewrite in_map_iff in H\n| [|- context[LIn _ (map _ _)]] => setoid_rewrite in_map_iff\n| [H:context[LIn _ (remove_nvars _ _)]|- _] => setoid_rewrite in_remove_nvars in H; simpl in H\n| [|- context[LIn _ (remove_nvars _ _)]] => setoid_rewrite in_remove_nvars; simpl\n| [H: _ = []|- _] => apply null_iff_nil in H; unfold null in H; simpl in H\n| [|- _ = []] => apply null_iff_nil; unfold null; simpl\n| [|- context[LIn _ (map _ _)]] => setoid_rewrite in_map_iff\nend;\nsubst.\n\n\n\n\n\nLocal Ltac \nillFormedCase :=\n (try reflexivity; try (simpl;rewrite flat_map_vterm; reflexivity)).\n\n\n\n\n(* Move *)\nLtac destructbtdeep2 bt tac :=\n let btlv := fresh bt \"lv\" in\n let btnt := fresh bt \"nt\" in\n let btlv1 := fresh btlv \"1\" in\n let btlv2 := fresh btlv \"2\" in\n let btlv3 := fresh btlv \"3\" in\n destruct bt as [btlv btnt];\n destruct btlv as [| btlv1]; tac;\n try(destruct btlv as [| btlv2]; tac);\n try(destruct btlv as [| btlv3]; tac).\n\nLtac destructlbt lbt tac :=\n repeat (\n let b := fresh \"b\" in\n destruct lbt as [| b lbt];tac; []).\n\nHint Rewrite memvar_singleton : SquiggleEq.\n\nHint Rewrite remove_nvars_cons_r : SquiggleEq2.\n\nHint Rewrite\n <- beq_var_refl : SquiggleEq.\n\nLtac disjoint_flat_allv :=\nrepeat match goal with\n[ Hdis : disjoint ?lv (flat_map all_vars_bt ?lbt) ,\n Hin : LIn _ ?lbt |- _]\n => rewrite disjoint_flat_map_r in Hdis; specialize (Hdis _ Hin); unfold all_vars_bt in Hdis;\n simpl in Hdis\nend.\n\n\nLtac disjoint_reasoning2 :=\nmatch goal with\n| [ |- disjoint _ (_ ++ _) ] => apply disjoint_app_r;split\n| [ |- disjoint (_ ++ _) _ ] => apply disjoint_app_l;split\n| [ |- disjoint _ (_ :: (_ :: _)) ] => apply disjoint_cons_r;split\n| [ |- disjoint (_ :: (_ :: _)) _ ] => apply disjoint_cons_l;split\n| [ |- disjoint _ (_ :: ?v) ] => notNil v;apply disjoint_cons_r;split\n| [ |- disjoint (_ :: ?v) _ ] => notNil v;apply disjoint_cons_l;split\n| [ |- disjoint _ _ ] => (sp;fail || apply disjoint_sym; sp;fail)\n| [ |- _ <> _] => apply disjoint_neq_iff\n| [ |- ! (LIn _ _)] => apply disjoint_singleton_l\n(** important to leave it the way it was .. so that repeat progress won't loop*)\n| [ H: disjoint _ (_ ++ _) |- _ ] => apply disjoint_app_r in H;sp\n| [ H: disjoint (_ ++ _) _ |- _ ] => apply disjoint_app_l in H;sp\n| [ H: disjoint _ (_ :: (_ :: _)) |- _ ] => apply disjoint_cons_r in H;sp\n| [ H: disjoint (_ :: (_ :: _)) _ |- _ ] => apply disjoint_cons_l in H;sp\n| [ H: disjoint _ (_ :: ?v) |- _ ] => notNil v;apply disjoint_cons_r in H;sp\n| [ H: disjoint (_ :: ?v) _ |- _ ] => notNil v;apply disjoint_cons_l in H;sp\n| [ H: !(disjoint _ []) |- _ ] => provefalse; apply H; apply disjoint_nil_r\n| [ H: !(disjoint [] _) |- _ ] => provefalse; apply H; apply disjoint_nil_l\n| [ H: (disjoint _ []) |- _ ] => clear H\n| [ H: (disjoint [] _) |- _ ] => clear H\n| [ H: ! (LIn _ _) |- _] => apply disjoint_singleton_l in H\n| [ H: _ <> _ |- _] => apply disjoint_neq_iff in H\nend.\n\nTactic Notation \"disjoint_reasoningv2\" :=\n (unfold all_vars in *); repeat( progress disjoint_reasoning2).\n \nLtac disjoint_flat2 :=\ndisjoint_reasoning2; disjoint_flat_allv;disjoint_reasoningv2.\n\n\nHint Resolve subsetAllVarsLbt2 : subset. \n\nHint Rewrite remove_var_nil remove_nvars_nil_r: SquiggleEq.\n\n Ltac rwHyps :=\n unfold closed, closed_bt in *;\n repeat match goal with\n [ H: _ = _ |- _] => repeat rewrite H; hide_hyp H\n end; show_hyps.\n\n\n\n\n\n Hint Resolve @subsetAllVarsLbt3 @subsetBoundVarsLbt3 : subset.\n\n\n\nLemma isProgramLNoBnd {O V} {deqv: Deq V} {gtso : GenericTermSig O}\n (lbt: list (@BTerm V O)) m:\n map num_bvars lbt = repeat 0 m\n -> lforall isprogram_bt lbt\n -> lforall isprogram (map get_nt lbt).\nProof using.\n revert m. \n induction lbt; unfold lforall; simpl in *;[ firstorder; fail | ].\n intros ? Hm.\n simpl in *.\n simpl.\n destruct m; [invertsn Hm | ].\n simpl in *. inverts Hm as Hma Hm.\n rewrite Hma in Hm.\n specialize (IHlbt _ Hm).\n destruct a as [lv nt].\n destruct lv; [ | inverts Hma].\n revert IHlbt. revert Hm. unfold lforall. clear.\n intros.\n pose proof (H _ ltac:(left; refl)).\n apply isprogram_bt_nobnd in H1.\n firstorder; subst; simpl; firstorder.\nQed.\n\n\nLemma map0lbt2 {V O}: forall (lbt: list (@BTerm V O)) m,\nmap num_bvars lbt = repeat 0 m\n-> lbt = map (bterm []) (map get_nt lbt).\nProof using.\n induction lbt; simpl; auto.\n intros ? Hn.\n destruct a. inverts Hn as Hn Hnn. unfold num_bvars in Hn.\n simpl in Hn. dlist_len_name l Hh.\n destruct m; invertsn Hn.\n destruct l; invertsn Hn.\n simpl. f_equal. eauto.\nQed.\n\nHint Rewrite @noDupApp @all_vars_ot @allvars_bterm @varsOfClassConsIff @noDupConsIff: SquiggleEq.\n\nLemma wft_ntwf {Opid V} {gts : GenericTermSig Opid}: forall t: @NTerm V Opid, wft t =true -> nt_wf t.\nProof using.\n induction t as [x | o lbt Hind] using NTerm_better_ind; intros Hwf; try (constructor; fail).\n simpl in Hwf.\n apply andb_eq_true in Hwf. repnd.\n setoid_rewrite assert_beq_list in Hwf0.\n constructor; auto.\n rewrite ball_map_true in Hwf.\n intros l. destruct l. intros. constructor.\n eapply Hind; eauto.\n specialize (Hwf _ H).\n simpl in Hwf. assumption.\n Qed. \n\n\nHint Rewrite @flat_map_bterm_nil_allvars: SquiggleEq.\n\n", "meta": {"author": "aa755", "repo": "SquiggleEq", "sha": "d78583e28d7dc87bd5b2de29cfc439dc96385ce1", "save_path": "github-repos/coq/aa755-SquiggleEq", "path": "github-repos/coq/aa755-SquiggleEq/SquiggleEq-d78583e28d7dc87bd5b2de29cfc439dc96385ce1/terms2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.12085323565689977, "lm_q1q2_score": 0.05948252875379548}} {"text": "(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n definitions from the previous chapter: *)\n\nFrom LF Require Export Basics.\n\n(** For the [Require Export] to work, Coq needs to be able to\n find a compiled version of [Basics.v], called [Basics.vo], in a directory\n associated with the prefix [LF]. This file is analogous to the [.class]\n files compiled from [.java] source files and the [.o] files compiled from\n [.c] files.\n\n First create a file named [_CoqProject] containing the following line\n (if you obtained the whole volume \"Logical Foundations\" as a single\n archive, a [_CoqProject] should already exist and you can skip this step):\n\n [-Q . LF]\n\n This maps the current directory (\"[.]\", which contains [Basics.v],\n [Induction.v], etc.) to the prefix (or \"logical directory\") \"[LF]\".\n PG and CoqIDE read [_CoqProject] automatically, so they know to where to\n look for the file [Basics.vo] corresponding to the library [LF.Basics].\n\n Once [_CoqProject] is thus created, there are various ways to build\n [Basics.vo]:\n\n - In Proof General: The compilation can be made to happen automatically\n when you submit the [Require] line above to PG, by setting the emacs\n variable [coq-compile-before-require] to [t]. You can also use the\n menu option \"Coq -> Auto Compilation -> Compile Before Require\".\n\n - In CoqIDE: Open [Basics.v]; then, in the \"Compile\" menu, click\n on \"Compile Buffer\".\n\n - From the command line: Generate a [Makefile] using the [coq_makefile]\n utility, that comes installed with Coq (if you obtained the whole\n volume as a single archive, a [Makefile] should already exist\n and you can skip this step):\n\n [coq_makefile -f _CoqProject *.v -o Makefile]\n\n Note: You should rerun that command whenever you add or remove Coq files\n to the directory.\n\n Then you can compile [Basics.v] by running [make] with the corresponding\n [.vo] file as a target:\n\n [make Basics.vo]\n\n All files in the directory can be compiled by giving no arguments:\n\n [make]\n\n Under the hood, [make] uses the Coq compiler, [coqc]. You can also\n run [coqc] directly:\n\n [coqc -Q . LF Basics.v]\n\n But [make] also calculates dependencies between source files to compile\n them in the right order, so [make] should generally be prefered over\n explicit [coqc].\n\n If you have trouble (e.g., if you get complaints about missing\n identifiers later in the file), it may be because the \"load path\"\n for Coq is not set up correctly. The [Print LoadPath.] command\n may be helpful in sorting out such issues.\n\n In particular, if you see a message like\n\n [Compiled library Foo makes inconsistent assumptions over\n library Bar]\n\n check whether you have multiple installations of Coq on your machine.\n It may be that commands (like [coqc]) that you execute in a terminal\n window are getting a different version of Coq than commands executed by\n Proof General or CoqIDE.\n\n - Another common reason is that the library [Bar] was modified and\n recompiled without also recompiling [Foo] which depends on it. Recompile\n [Foo], or everything if too many files are affected. (Using the third\n solution above: [make clean; make].)\n\n One more tip for CoqIDE users: If you see messages like [Error:\n Unable to locate library Basics], a likely reason is\n inconsistencies between compiling things _within CoqIDE_ vs _using\n [coqc] from the command line_. This typically happens when there\n are two incompatible versions of [coqc] installed on your\n system (one associated with CoqIDE, and one associated with [coqc]\n from the terminal). The workaround for this situation is\n compiling using CoqIDE only (i.e. choosing \"make\" from the menu),\n and avoiding using [coqc] directly at all. *)\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left, using an easy argument based on\n simplification. We also observed that proving the fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n n = n + 0.\n\n(** ... can't be done in the same simple way. Just applying\n [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through fine, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n n = n + 0.\nProof.\n intros n. destruct n as [| n'] eqn:E.\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** We could use [destruct n'] to get one step further, but,\n since [n] can be arbitrarily large, if we just go on like this\n we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n inductively defined sets, we usually need a more powerful\n reasoning principle: _induction_.\n\n Recall (from high school, a discrete math course, etc.) the\n _principle of induction over natural numbers_: If [P(n)] is some\n proposition involving a natural number [n] and we want to show\n that [P] holds for all numbers [n], we can reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same: we begin with the goal of proving\n [P(n)] for all [n] and break it down (by applying the [induction]\n tactic) into two separate subgoals: one where we must show [P(O)]\n and another where we must show [P(n') -> P(S n')]. Here's how\n this works for the theorem at hand: *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. Since there are two subgoals, the [as...] clause\n has two parts, separated by [|]. (Strictly speaking, we can omit\n the [as...] clause and Coq will choose names for us. In practice,\n this is a bad idea, as Coq's automatic choices tend to be\n confusing.)\n\n In the first subgoal, [n] is replaced by [0]. No new variables\n are introduced (so the first part of the [as...] is empty), and\n the goal becomes [0 = 0 + 0], which follows by simplification.\n\n In the second subgoal, [n] is replaced by [S n'], and the\n assumption [n' + 0 = n'] is added to the context with the name\n [IHn'] (i.e., the Induction Hypothesis for [n']). These two names\n are specified in the second part of the [as...] clause. The goal\n in this case becomes [S n' = (S n') + 0], which simplifies to\n [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** (The use of the [intros] tactic in these proofs is actually\n redundant. When applied to a goal that contains quantified\n variables, the [induction] tactic will automatically move them\n into the context as needed.) *)\n\n(** **** Exercise: 2 stars, standard, recommended (basic_induction) \n\n Prove the following using induction. You might need previously\n proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n (* SOLUTION: *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n (* SOLUTION: *)\n intros n m. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n (* SOLUTION: *)\n intros n m. induction m as [| m' IHm'].\n - (* m = 0 *)\n simpl. rewrite <- plus_n_O. reflexivity.\n - (* m = S m' *)\n simpl. rewrite <- IHm'. rewrite <- plus_n_Sm.\n reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n (* SOLUTION: *)\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (double_plus) \n\n Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n (* SOLUTION: *)\n intros n. induction n as [|n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite plus_comm. simpl. rewrite IHn'. reflexivity. Qed.\n (** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (evenb_S) \n\n One inconvenient aspect of our definition of [evenb n] is the\n recursive call on [n - 2]. This makes proofs about [evenb n]\n harder when done by induction on [n], since we may need an\n induction hypothesis about [n - 2]. The following lemma gives an\n alternative characterization of [evenb (S n)] that works better\n with induction: *)\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n (* SOLUTION: *)\n intros n.\n induction n as [| n' IHn'].\n - (* n = 0 *) simpl. reflexivity.\n - (* n = S n' *)\n rewrite IHn'. rewrite negb_involutive. simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (destruct_induction) \n\n Briefly explain the difference between the tactics [destruct]\n and [induction].\n\n(* SOLUTION: *)\n Both are used to perform case analysis on an element of an\n inductively defined type; [induction] also generates an induction\n hypothesis, while [destruct] does not.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_destruct_induction : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n broken into a sequence of theorems, with later proofs referring to\n earlier theorems. But sometimes a proof will require some\n miscellaneous fact that is too trivial and of too little general\n interest to bother giving it its own top-level name. In such\n cases, it is convenient to be able to simply state and prove the\n needed \"sub-theorem\" right at the point where it is used. The\n [assert] tactic allows us to do this. *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (We can also name the assertion with [as] just as\n we did above with [destruct] and [induction], i.e., [assert (0 + n\n = n) as H].) Note that we surround the proof of this assertion\n with curly braces [{ ... }], both for readability and so that,\n when using Coq interactively, we can see more easily when we have\n finished this sub-proof. The second goal is the same as the one\n at the point where we invoke [assert] except that, in the context,\n we now have the assumption [H] that [0 + n = n]. That is,\n [assert] generates one subgoal where we must prove the asserted\n fact and a second subgoal where we can use the asserted fact to\n make progress on whatever we were trying to prove in the first\n place. *)\n\n(** Another example of [assert]... *)\n\n(** For example, suppose we want to prove that [(n + m) + (p + q)\n = (m + n) + (p + q)]. The only difference between the two sides of\n the [=] is that the arguments [m] and [n] to the first inner [+]\n are swapped, so it seems we should be able to use the\n commutativity of addition ([plus_comm]) to rewrite one into the\n other. However, the [rewrite] tactic is not very smart about\n _where_ it applies the rewrite. There are three uses of [+] here,\n and it turns out that doing [rewrite -> plus_comm] will affect\n only the _outer_ one... *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)... seems\n like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work... Coq rewrites the wrong plus! :-( *)\nAbort.\n\n(** To use [plus_comm] at the point where we need it, we can introduce\n a local lemma stating that [n + m = m + n] (for the particular [m]\n and [n] that we are talking about here), prove this lemma using\n [plus_comm], and then use it to do the desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n { rewrite -> plus_comm. reflexivity. }\n rewrite -> H. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** What constitutes a successful proof of a mathematical claim?\n The question has challenged philosophers for millennia, but a\n rough and ready definition could be this: A proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true --\n an unassailable argument for the truth of [P]. That is, a proof\n is an act of communication.\n\n Acts of communication may involve different sorts of readers. On\n one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is that [P] can be mechanically\n derived from a certain set of formal logical rules, and the proof\n is a recipe that guides the program in checking this fact. Such\n recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n and will thus necessarily be _informal_. Here, the criteria for\n success are less clearly specified. A \"valid\" proof is one that\n makes the reader believe [P]. But the same proof may be read by\n many different readers, some of whom may be convinced by a\n particular way of phrasing the argument, while others may not be.\n Some readers may be particularly pedantic, inexperienced, or just\n plain thick-headed; the only way to convince them will be to make\n the argument in painstaking detail. But other readers, more\n familiar in the area, may find all this detail so overwhelming\n that they lose the overall thread; all they want is to be told the\n main ideas, since it is easier for them to fill in the details for\n themselves than to wade through a written presentation of them.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader.\n\n In practice, however, mathematicians have developed a rich set of\n conventions and idioms for writing about complex mathematical\n objects that -- at least within a certain community -- make\n communication fairly reliable. The conventions of this stylized\n form of communication give a fairly clear standard for judging\n proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can\n completely forget about informal ones! Formal proofs are useful\n in many ways, but they are _not_ very efficient ways of\n communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this. For a human, however, it\n is difficult to make much sense of it. We can use comments and\n bullets to show the structure a little more clearly... *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** ... and if you're used to Coq you may be able to step\n through the tactics one after the other in your mind and imagine\n the state of the context and goal stack at each point, but if the\n proof were even a little bit more complicated this would be next\n to impossible.\n\n A (pedantic) mathematician might write the proof something like\n this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n n + (m + p) = (n + m) + p.\n\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n\n 0 + (m + p) = (0 + m) + p.\n\n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n\n n' + (m + p) = (n' + m) + p.\n\n We must show\n\n (S n') + (m + p) = ((S n') + m) + p.\n\n By the definition of [+], this follows from\n\n S (n' + (m + p)) = S ((n' + m) + p),\n\n which is immediate from the induction hypothesis. _Qed_. *)\n\n(** The overall form of the proof is basically similar, and of\n course this is no accident: Coq has been designed so that its\n [induction] tactic generates the same sub-goals, in the same\n order, as the bullet points that a mathematician would write. But\n there are significant differences of detail: the formal proof is\n much more explicit in some ways (e.g., the use of [reflexivity])\n but much less explicit in others (in particular, the \"proof state\"\n at any given point in the Coq proof is completely implicit,\n whereas the informal proof reminds the reader several times where\n things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal) \n\n Translate your solution for [plus_comm] into an informal proof:\n\n Theorem: Addition is commutative.\n\n Proof: (* SOLUTION: *)\n Let natural numbers [n] and [m] be given. We show [n + m = m +\n n] by induction on [m].\n\n - First, suppose [m = 0]. We must show [n + 0 = 0 + n]. By\n the definition of [+], we know [0 + n = n], and we have\n already shown (lemma [plus_n_O]) that [n + 0 = n]. Thus,\n showing [n + 0 = 0 + n] is equivalent to showing [n = n],\n which is true by reflexivity.\n\n - Next, suppose [m = S m'] for some [m'], where [n + m'] = [m'\n + n]. We must show that [n + (S m') = (S m') + n]. By the\n definition of [+] and the induction hypothesis, [(S m') + n =\n S (m' + n) = S (n + m')]. It remains to show [n + (S m') = S\n (n + m')], which is precisely lemma [plus_n_Sm].\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_plus_comm_informal : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_refl_informal) \n\n Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n\n Theorem: [true = n =? n] for any [n].\n\n Proof: (* SOLUTION: *)\n By induction on [n].\n\n - First, suppose [n = 0]. We must show [true = 0 =? 0]. This\n follows directly from the definition of [eqb].\n\n - Next, suppose [n = S n'], where [true = n' =? n']. We\n must show [true = (S n') =? (S n')]. This\n follows directly from the induction hypothesis and the\n definition of [eqb].\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, standard, recommended (mult_comm) \n\n Use [assert] to help prove [plus_swap]. You don't need to\n use induction yet. *)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n (* SOLUTION: *)\n intros n m p.\n rewrite -> plus_assoc.\n assert (H: n + m = m + n).\n { rewrite <- plus_comm. reflexivity. }\n rewrite -> H. rewrite -> plus_assoc. reflexivity. Qed.\n\nTheorem mult_m_Sn : forall m n : nat,\n m * (S n) = m + (m * n).\nProof.\n induction m as [| m' IHm'].\n - (* m = 0 *)\n intros n. simpl. reflexivity.\n - (* m = S m' *)\n intros n.\n simpl.\n rewrite -> IHm'.\n rewrite -> plus_swap.\n reflexivity. Qed.\n\n(** Now prove commutativity of multiplication. You will probably\n want to define and prove a \"helper\" theorem to be used\n in the proof of this one. Hint: what is [n * (1 + k)]? *)\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n (* SOLUTION: *)\n intros m n.\n induction m as [| m' IHm'].\n - (* m = 0 *)\n simpl. rewrite mult_0_r. reflexivity.\n - (* m = S m' *)\n simpl.\n rewrite -> IHm'.\n rewrite -> mult_m_Sn.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (more_exercises) \n\n Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n true = (n <=? n).\nProof.\n (* SOLUTION: *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem zero_nbeq_S : forall n:nat,\n 0 =? (S n) = false.\nProof.\n (* SOLUTION: *)\n reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n (* SOLUTION: *)\n intros b. destruct b eqn:E.\n - reflexivity.\n - reflexivity. Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n (* SOLUTION: *)\n intros n m p. induction p as [| p' IHp'].\n - (* p = 0 *)\n intros H.\n simpl. rewrite -> H. reflexivity.\n - (* p = S p' *)\n intros H.\n simpl. rewrite -> IHp'.\n + reflexivity.\n + rewrite -> H. reflexivity. Qed.\n\nTheorem S_nbeq_0 : forall n:nat,\n (S n) =? 0 = false.\nProof.\n (* SOLUTION: *)\n reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n (* SOLUTION: *)\n intros n. simpl. rewrite <- plus_n_O.\n reflexivity. Qed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n (* SOLUTION: *)\n intros b c. destruct b eqn:Eb.\n - destruct c eqn:Ec.\n + reflexivity.\n + reflexivity.\n - destruct c eqn:Ec.\n + reflexivity.\n + reflexivity. Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* SOLUTION: *)\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite IHn'.\n rewrite -> plus_assoc.\n reflexivity. Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n (* SOLUTION: *)\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> mult_plus_distr_r. rewrite IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_refl) *)\n\nTheorem eqb_refl : forall n : nat,\n true = (n =? n).\nProof.\n (* SOLUTION: *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (plus_swap') \n\n The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to: [replace (t) with (u)]\n replaces (all copies of) expression [t] in the goal by expression\n [u], and generates [t = u] as an additional subgoal. This is often\n useful when a plain [rewrite] acts on the wrong part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n (* SOLUTION: *)\n intros n m p.\n rewrite -> plus_assoc.\n replace (n+m) with (m+n).\n { rewrite plus_assoc.\n reflexivity. }\n rewrite -> plus_comm.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (binary_commute) \n\n Recall the [incr] and [bin_to_nat] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that the following diagram commutes:\n\n incr\n bin ----------------------> bin\n | |\n bin_to_nat | | bin_to_nat\n | |\n v v\n nat ----------------------> nat\n S\n\n That is, incrementing a binary number and then converting it to\n a (unary) natural number yields the same result as first converting\n it to a natural number and then incrementing.\n Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n Before you start working on this exercise, copy the definitions of\n [incr] and [bin_to_nat] from your solution to the [binary]\n exercise here so that this file can be graded on its own. If you\n want to change your original definitions to make the property\n easier to prove, feel free to do so! *)\n\n(* SOLUTION: *)\nInductive bin : Type :=\n | Z\n | B0 (n : bin)\n | B1 (n : bin).\n\nFixpoint incr (m:bin) : bin :=\n match m with\n | Z => B1 Z\n | B0 m' => B1 m'\n | B1 m' => B0 (incr m')\n end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n match m with\n | Z => O\n | B0 m' => 2 * bin_to_nat m'\n | B1 m' => 1 + 2 * bin_to_nat m'\n end.\n\nTheorem bin_to_nat_pres_incr : forall b : bin,\n bin_to_nat (incr b) = 1 + bin_to_nat b.\nProof.\n intros b.\n induction b as [| b' IHb' | b' IHb'].\n - (* b = 0 *)\n reflexivity.\n - (* b = 2*b' *)\n reflexivity.\n - (* b = 1 + 2*b' *)\n simpl. rewrite -> IHb'.\n simpl. rewrite <- plus_n_Sm.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_commute : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) \n\n This is a further continuation of the previous exercises about\n binary numbers. You may find you need to go back and change your\n earlier definitions to get things to work here.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. *)\n\nFixpoint nat_to_bin (n:nat) : bin\n (* SOLUTION: *) :=\n match n with\n | O => Z\n | S n' => incr (nat_to_bin n')\n end.\n\n(** Prove that, if we start with any [nat], convert it to binary, and\n convert it back, we get the same [nat] we started with. (Hint: If\n your definition of [nat_to_bin] involved any extra functions, you\n may need to prove a subsidiary lemma showing how such functions\n relate to [nat_to_bin].) *)\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n (* SOLUTION: *)\n induction n as [|n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl.\n rewrite bin_to_nat_pres_incr.\n rewrite IHn'.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_a : option (nat*string) := None.\n\n(** (b) One might naturally expect that we should also prove the\n opposite direction -- that starting with a binary number,\n converting to a natural, and then back to binary should yield\n the same number we started with. However, this is not the\n case! Explain (in a comment) what the problem is. *)\n\n(* SOLUTION: *)\n(* Answer to (b): [0] has many representations: it can be written [Z],\n [B0 Z], [Bo (B0 Z)], and so on. For these alternate representations,\n if you do [bin_to_nat] then [nat_to_bin], you don't get back what\n you started with. (Any other number also has many\n representations, after applying constructors to the multiple\n representations of zero.) *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_b : option (nat*string) := None.\n\n(** (c) Define a normalization function -- i.e., a function\n [normalize] going directly from [bin] to [bin] (i.e., _not_ by\n converting to [nat] and back) such that, for any binary number\n [b], converting [b] to a natural and then back to binary yields\n [(normalize b)]. Prove it. (Warning: This part is a bit\n tricky -- you may end up defining several auxiliary lemmas.\n One good way to find out what you need is to start by trying\n to prove the main statement, see where you get stuck, and see\n if you can find a lemma -- perhaps requiring its own inductive\n proof -- that will allow the main proof to make progress.) Don't\n define this using [nat_to_bin] and [bin_to_nat]! *)\n\n(* SOLUTION: *)\nFixpoint double_bin (b:bin) : bin :=\n match b with\n | Z => Z\n | _ => B0 b\n end.\n\nFixpoint normalize (b:bin) : bin :=\n match b with\n | Z => Z\n | B0 b' => double_bin (normalize b')\n | B1 b' => B1 (normalize b')\n end.\n\nLemma double_incr : forall b, double_bin (incr b) = incr (incr (double_bin b)).\nProof.\n destruct b eqn:E.\n - (* Z *) reflexivity.\n - (* B0 *) reflexivity.\n - (* B1 *) reflexivity.\nQed.\n\nLemma incr_double : forall b, incr (double_bin b) = B1 b.\nProof.\n destruct b eqn:E.\n - (* Z *) reflexivity.\n - (* B0 *) reflexivity.\n - (* B1 *) reflexivity.\nQed.\n\nLemma nat_to_bin_double : forall n, nat_to_bin (double n) = double_bin (nat_to_bin n).\nProof.\n induction n as [|n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite IHn'. rewrite <- double_incr. reflexivity.\nQed.\n\nTheorem bin_nat_bin : forall b, nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n induction b as [|b' IHb'|b' IHb'].\n - (* Z *) reflexivity.\n - (* B0 *) simpl.\n rewrite <- plus_n_O.\n rewrite <- double_plus.\n rewrite -> nat_to_bin_double.\n rewrite IHb'.\n reflexivity.\n - (* B1 *) simpl.\n rewrite <- plus_n_O.\n rewrite <- double_plus.\n rewrite -> nat_to_bin_double.\n rewrite IHb'.\n rewrite incr_double.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_c : option (nat*string) := None.\n(** [] *)\n\n(* 04 Mar 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/a6src/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.22270014398423357, "lm_q1q2_score": 0.05921161964192536}} {"text": "(** * Postscript *)\n\n(** Congratulations: We've made it to the end! *)\n\n(* ################################################################# *)\n(** * Looking Back *)\n\n(** We've covered quite a bit of ground so far. Here's a quick review...\n\n - _Functional programming_:\n - \"declarative\" programming style (recursion over immutable\n data structures, rather than looping over mutable arrays\n or pointer structures)\n - higher-order functions\n - polymorphism *)\n\n(**\n - _Logic_, the mathematical basis for software engineering:\n\n logic calculus\n -------------------- ~ ----------------------------\n software engineering mechanical/civil engineering\n\n - inductively defined sets and relations\n - inductive proofs\n - proof objects *)\n\n(**\n - _Coq_, an industrial-strength proof assistant\n - functional core language\n - core tactics\n - automation\n*)\n\n(* ################################################################# *)\n(** * Looking Forward *)\n\n(** If what you've seen so far has whetted your interest, you have two\n choices for further reading in the _Software Foundations_ series:\n\n - _Programming Language Foundations_ (volume 2, by a set of\n authors similar to this book's) covers material that\n might be found in a graduate course on the theory of\n programming languages, including Hoare logic, operational\n semantics, and type systems.\n\n - _Verified Functional Algorithms_ (volume 3, by Andrew\n Appel) builds on the themes of functional programming and\n program verification in Coq, addressing a range of topics\n that might be found in a standard data structures course,\n with an eye to formal verification. *)\n\n(* ################################################################# *)\n(** * Other sources *)\n\n(** Here are some other good places to learn more...\n\n - This book includes some optional chapters covering topics\n that you may find useful. Take a look at the table of contents and the chapter dependency diagram to find\n them.\n\n - For questions about Coq, the [#coq] area of Stack\n Overflow (https://stackoverflow.com/questions/tagged/coq)\n is an excellent community resource.\n\n - Here are some great books on functional programming\n - Learn You a Haskell for Great Good, by Miran Lipovaca\n [Lipovaca 2011] (in Bib.v).\n - Real World Haskell, by Bryan O'Sullivan, John Goerzen,\n and Don Stewart [O'Sullivan 2008] (in Bib.v)\n - ...and many other excellent books on Haskell, OCaml,\n Scheme, Racket, Scala, F sharp, etc., etc.\n\n - And some further resources for Coq:\n - Certified Programming with Dependent Types, by Adam\n Chlipala [Chlipala 2013] (in Bib.v).\n - Interactive Theorem Proving and Program Development:\n Coq'Art: The Calculus of Inductive Constructions, by Yves\n Bertot and Pierre Casteran [Bertot 2004] (in Bib.v).\n\n - If you're interested in real-world applications of formal\n verification to critical software, see the Postscript chapter\n of _Programming Language Foundations_.\n\n - For applications of Coq in building verified systems, the\n lectures and course materials for the 2017 DeepSpec Summer\n School are a great resource.\n https://deepspec.org/event/dsss17/index.html\n*)\n\n(* Wed Jan 9 12:02:47 EST 2019 *)\n", "meta": {"author": "carliros", "repo": "software-foundations-book", "sha": "fea3e774d18d2434c7296cedbf52756c5ab8dbdd", "save_path": "github-repos/coq/carliros-software-foundations-book", "path": "github-repos/coq/carliros-software-foundations-book/software-foundations-book-fea3e774d18d2434c7296cedbf52756c5ab8dbdd/logical-foundations-2019/dotv/Postscript.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.058758352426678775}} {"text": "(** * Postscript *)\n\n\n(** Congratulations: You've made it to the end! *)\n\n(** * Looking Back... *)\n\n(** We've covered a lot of ground. The topics might be summarized like this:\n\n - _Functional programming_:\n - \"declarative\" programming style (recursion over persistent\n data structures, rather than looping over mutable arrays\n or pointer structures)\n - higher-order functions\n - polymorphism *)\n\n(**\n - _Logic_, the mathematical basis for software engineering:\n\n logic calculus\n -------------------- = ----------------------------\n software engineering mechanical/civil engineering\n\n\n - inductively defined sets and relations\n - inductive proofs\n - proof objects *)\n\n(**\n - _Coq_, an industrial-strength proof assistant\n - functional core language\n - core tactics\n - automation\n*)\n\n(**\n - _Foundations of programming languages_\n\n - notations and definitional techniques for precisely specifying\n - abstract syntax\n - operational semantics\n - big-step style\n - small-step style\n - type systems\n\n - program equivalence\n\n - Hoare logic\n\n - fundamental metatheory of type systems\n\n - progress and preservation\n\n - theory of subtyping\n*)\n\n(* ###################################################################### *)\n(** * Looking Forward... *)\n\n(** Some good places to go for more...\n\n - This book includes several optional chapters covering topics\n that you may find useful. If you've been using it in the\n context of a course, take a look at the table of contents\n and the chapter dependency diagram.\n\n - Cutting-edge conferences on programming languages and formal\n verification:\n - POPL\n - PLDI\n - OOPSLA\n - ICFP\n - CAV\n - (and many others)\n\n - More on functional programming\n - Learn You a Haskell for Great Good, by Miran\n Lipovaca [Lipovaca 2011].\n - and many other texts on Haskell, OCaml, Scheme, Scala,\n ...\n\n - More on Hoare logic and program verification\n - The Formal Semantics of Programming Languages: An\n Introduction, by Glynn Winskel [Winskel 1993].\n - Many practical verification tools, e.g. Microsoft's\n Boogie system, Java Extended Static Checking, etc.\n\n - More on the foundations of programming languages:\n - Types and Programming Languages, by Benjamin\n C. Pierce [Pierce 2002].\n - Practical Foundations for Programming Languages, by\n Robert Harper [Harper 2016].\n - Foundations for Programming Languages, by John\n C. Mitchell [Mitchell 1996].\n\n - More on Coq:\n - Certified Programming with Dependent Types, by Adam\n Chlipala [Chlipala 2013].\n - Interactive Theorem Proving and Program Development:\n Coq'Art: The Calculus of Inductive Constructions, by Yves\n Bertot and Pierre Casteran [Bertot 2004].\n - Iron Lambda (http://iron.ouroborus.net/) is a collection\n of ​Coq formalisations for functional languages of\n increasing complexity. It fills part of the gap between\n the end of the​ Software Foundations course and what\n appears in current research papers. The collection has\n at least Progress and Preservation theorems for a number\n of variants of STLC and the polymorphic\n lambda-calculus (System F). *)\n\n(* $Date: 2016-05-26 17:51:14 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "colinmccabe", "repo": "software-foundations", "sha": "d581e89d47978ed9acc9e2a64ba6209a614fd9f1", "save_path": "github-repos/coq/colinmccabe-software-foundations", "path": "github-repos/coq/colinmccabe-software-foundations/software-foundations-d581e89d47978ed9acc9e2a64ba6209a614fd9f1/Postscript.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.12765261702501562, "lm_q1q2_score": 0.05835469635306014}} {"text": "(** * UseTactics: Tactic Library for Coq: A Gentle Introduction *)\n\n(* Chapter written and maintained by Arthur Chargueraud *)\n\n(** Coq comes with a set of builtin tactics, such as [reflexivity],\n [intros], [inversion] and so on. While it is possible to conduct\n proofs using only those tactics, you can significantly increase\n your productivity by working with a set of more powerful tactics.\n This chapter describes a number of such useful tactics, which, for\n various reasons, are not yet available by default in Coq. These\n tactics are defined in the [LibTactics.v] file. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\n\nRequire Import Coq.Arith.Arith.\n\nFrom PLF Require Import Maps.\nFrom PLF Require Import Imp.\nFrom PLF Require Import Types.\nFrom PLF Require Import Smallstep.\nFrom PLF Require Import LibTactics.\n\nFrom PLF Require Stlc.\nFrom PLF Require Equiv.\nFrom PLF Require Imp.\nFrom PLF Require References.\nFrom PLF Require Smallstep.\nFrom PLF Require Hoare.\nFrom PLF Require Sub.\n\n(** Remark: SSReflect is another package providing powerful tactics.\n The library \"LibTactics\" differs from \"SSReflect\" in two respects:\n - \"SSReflect\" was primarily developed for proving mathematical\n theorems, whereas \"LibTactics\" was primarily developed for proving\n theorems on programming languages. In particular, \"LibTactics\"\n provides a number of useful tactics that have no counterpart in the\n \"SSReflect\" package.\n - \"SSReflect\" entirely rethinks the presentation of tactics,\n whereas \"LibTactics\" mostly stick to the traditional\n presentation of Coq tactics, simply providing a number of\n additional tactics. For this reason, \"LibTactics\" is\n probably easier to get started with than \"SSReflect\". *)\n\n(** This chapter is a tutorial focusing on the most useful features\n from the \"LibTactics\" library. It does not aim at presenting all\n the features of \"LibTactics\". The detailed specification of tactics\n can be found in the source file [LibTactics.v]. Further documentation\n as well as demos can be found at http://www.chargueraud.org/softs/tlc/. *)\n\n(** In this tutorial, tactics are presented using examples taken from\n the core chapters of the \"Software Foundations\" course. To illustrate\n the various ways in which a given tactic can be used, we use a\n tactic that duplicates a given goal. More precisely, [dup] produces\n two copies of the current goal, and [dup n] produces [n] copies of it. *)\n\n\n(* ################################################################# *)\n(** * Tactics for Naming and Performing Inversion *)\n\n(** This section presents the following tactics:\n - [introv], for naming hypotheses more efficiently,\n - [inverts], for improving the [inversion] tactic. *)\n\n\n(* ================================================================= *)\n(** ** The Tactic [introv] *)\n\nModule IntrovExamples.\n Import Stlc.\n Import Imp.\n Import STLC.\n\n(** The tactic [introv] allows to automatically introduce the\n variables of a theorem and explicitly name the hypotheses\n involved. In the example shown next, the variables [c],\n [st], [st1] and [st2] involved in the statement of determinism\n need not be named explicitly, because their name where already\n given in the statement of the lemma. On the contrary, it is\n useful to provide names for the two hypotheses, which we\n name [E1] and [E2], respectively. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st \\\\ st1 ->\n c / st \\\\ st2 ->\n st1 = st2.\nProof.\n introv E1 E2. (* was [intros c st st1 st2 E1 E2] *)\nAbort.\n\n(** When there is no hypothesis to be named, one can call\n [introv] without any argument. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n introv. (* was [intros X P Q] *)\nAbort.\n\n(** The tactic [introv] also applies to statements in which\n [forall] and [->] are interleaved. *)\n\nTheorem ceval_deterministic': forall c st st1,\n (c / st \\\\ st1) ->\n forall st2,\n (c / st \\\\ st2) ->\n st1 = st2.\nProof.\n introv E1 E2. (* was [intros c st st1 E1 st2 E2] *)\nAbort.\n\n(** Like the arguments of [intros], the arguments of [introv]\n can be structured patterns. *)\n\nTheorem exists_impl: forall X (P : X -> Prop) (Q : Prop) (R : Prop),\n (forall x, P x -> Q) ->\n ((exists x, P x) -> Q).\nProof.\n introv [x H2]. eauto.\n (* same as [intros X P Q R H1 [x H2].], which is itself short\n for [intros X P Q R H1 H2. destruct H2 as [x H2].] *)\nQed.\n\n(** Remark: the tactic [introv] works even when definitions\n need to be unfolded in order to reveal hypotheses. *)\n\nEnd IntrovExamples.\n\n\n(* ================================================================= *)\n(** ** The Tactic [inverts] *)\n\nModule InvertsExamples.\n Import Stlc.\n Import Equiv.\n Import Imp.\n Import STLC.\n\n(** The [inversion] tactic of Coq is not very satisfying for\n three reasons. First, it produces a bunch of equalities\n which one typically wants to substitute away, using [subst].\n Second, it introduces meaningless names for hypotheses.\n Third, a call to [inversion H] does not remove [H] from the\n context, even though in most cases an hypothesis is no longer\n needed after being inverted. The tactic [inverts] address all\n of these three issues. It is intented to be used in place of\n the tactic [inversion]. *)\n\n(** The following example illustrates how the tactic [inverts H]\n behaves mostly like [inversion H] except that it performs\n some substitutions in order to eliminate the trivial equalities\n that are being produced by [inversion]. *)\n\nTheorem skip_left: forall c,\n cequiv (SKIP;; c) c.\nProof.\n introv. split; intros H.\n dup. (* duplicate the goal for comparison *)\n (* was... *)\n - inversion H. subst. inversion H2. subst. assumption.\n (* now... *)\n - inverts H. inverts H2. assumption.\nAbort.\n\n(** A slightly more interesting example appears next. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st \\\\ st1 ->\n c / st \\\\ st2 ->\n st1 = st2.\nProof.\n introv E1 E2. generalize dependent st2.\n induction E1; intros st2 E2.\n admit. admit. (* skip some basic cases *)\n dup. (* duplicate the goal for comparison *)\n (* was: *)\n - inversion E2. subst. admit.\n (* now: *)\n - inverts E2. admit.\nAbort.\n\n(** The tactic [inverts H as.] is like [inverts H] except that the\n variables and hypotheses being produced are placed in the goal\n rather than in the context. This strategy allows naming those\n new variables and hypotheses explicitly, using either [intros]\n or [introv]. *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n c / st \\\\ st1 ->\n c / st \\\\ st2 ->\n st1 = st2.\nProof.\n introv E1 E2. generalize dependent st2.\n (induction E1); intros st2 E2;\n inverts E2 as.\n - (* E_Skip *) reflexivity.\n - (* E_Ass *)\n (* Observe that the variable [n] is not automatically\n substituted because, contrary to [inversion E2; subst],\n the tactic [inverts E2] does not substitute the equalities\n that exist before running the inversion. *)\n (* new: *) subst n.\n reflexivity.\n - (* E_Seq *)\n (* Here, the newly created variables can be introduced\n using intros, so they can be assigned meaningful names,\n for example [st3] instead of [st'0]. *)\n (* new: *) intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n { (* Proof of assertion *) apply IHE1_1; assumption. }\n subst st3.\n apply IHE1_2. assumption.\n (* E_IfTrue *)\n - (* b1 reduces to true *)\n (* In an easy case like this one, there is no need to\n provide meaningful names, so we can just use [intros] *)\n (* new: *) intros.\n apply IHE1. assumption.\n - (* b1 reduces to false (contradiction) *)\n (* new: *) intros.\n rewrite H in H5. inversion H5.\n (* The other cases are similiar *)\nAbort.\n\n(** In the particular case where a call to [inversion] produces\n a single subgoal, one can use the syntax [inverts H as H1 H2 H3]\n for calling [inverts] and naming the new hypotheses [H1], [H2]\n and [H3]. In other words, the tactic [inverts H as H1 H2 H3] is\n equivalent to [inverts H as; introv H1 H2 H3]. An example follows. *)\n\nTheorem skip_left': forall c,\n cequiv (SKIP;; c) c.\nProof.\n introv. split; intros H.\n inverts H as U V. (* new hypotheses are named [U] and [V] *)\n inverts U. assumption.\nAbort.\n\n(** A more involved example appears next. In particular, this example\n shows that the name of the hypothesis being inverted can be reused. *)\n\nExample typing_nonexample_1 :\n ~ exists T,\n has_type empty\n (tabs x TBool\n (tabs y TBool\n (tapp (tvar x) (tvar y))))\n T.\nProof.\n dup 3.\n\n (* The old proof: *)\n - intros C. destruct C.\n inversion H. subst. clear H.\n inversion H5. subst. clear H5.\n inversion H4. subst. clear H4.\n inversion H2. subst. clear H2.\n inversion H1.\n\n (* The new proof: *)\n - intros C. destruct C.\n inverts H as H1.\n inverts H1 as H2.\n inverts H2 as H3 H4.\n inverts H3 as H5.\n inverts H5.\n\n (* The new proof, alternative: *)\n - intros C. destruct C.\n inverts H as H.\n inverts H as H.\n inverts H as H1 H2.\n inverts H1 as H1.\n inverts H1.\nQed.\n\nEnd InvertsExamples.\n\n(** Note: in the rare cases where one needs to perform an inversion\n on an hypothesis [H] without clearing [H] from the context,\n one can use the tactic [inverts keep H], where the keyword [keep]\n indicates that the hypothesis should be kept in the context. *)\n\n\n\n\n(* ################################################################# *)\n(** * Tactics for N-ary Connectives *)\n\n(** Because Coq encodes conjunctions and disjunctions using binary\n constructors [/\\] and [\\/], working with a conjunction or a\n disjunction of [N] facts can sometimes be quite cumbursome.\n For this reason, \"LibTactics\" provides tactics offering direct\n support for n-ary conjunctions and disjunctions. It also provides\n direct support for n-ary existententials. *)\n\n(** This section presents the following tactics:\n - [splits] for decomposing n-ary conjunctions,\n - [branch] for decomposing n-ary disjunctions,\n - [exists] for proving n-ary existentials. *)\n\nModule NaryExamples.\n Import References.\n Import Smallstep.\n Import STLCRef.\n\n(* ================================================================= *)\n(** ** The Tactic [splits] *)\n\n(** The tactic [splits] applies to a goal made of a conjunction\n of [n] propositions and it produces [n] subgoals. For example,\n it decomposes the goal [G1 /\\ G2 /\\ G3] into the three subgoals\n [G1], [G2] and [G3]. *)\n\nLemma demo_splits : forall n m,\n n > 0 /\\ n < m /\\ m < n+10 /\\ m <> 3.\nProof.\n intros. splits.\nAbort.\n\n\n(* ================================================================= *)\n(** ** The Tactic [branch] *)\n\n(** The tactic [branch k] can be used to prove a n-ary disjunction.\n For example, if the goal takes the form [G1 \\/ G2 \\/ G3],\n the tactic [branch 2] leaves only [G2] as subgoal. The following\n example illustrates the behavior of the [branch] tactic. *)\n\nLemma demo_branch : forall n m,\n n < m \\/ n = m \\/ m < n.\nProof.\n intros.\n destruct (lt_eq_lt_dec n m) as [[H1|H2]|H3].\n - branch 1. apply H1.\n - branch 2. apply H2.\n - branch 3. apply H3.\nQed.\n\n\n(* ================================================================= *)\n(** ** The Tactic [exists] *)\n\n(** Coq supports n-ary existentials. For example, instead of\n writing [exists t', exists st', t / st ==> t' / st'], one\n may write [exists t' st', t / st ==> t' / st'].\n\n Coq also supports a n-ary version of the tactic [exists],\n which is used for providing witnesses. For example\n [exists a, b, c] is short for [exists a; exists b; exists c].\n\n Note: for historical reasons, the library \"LibTactics\" also\n supports a syntax without comas: [exists a b c].\n\n The following example illustrates n-ary existentials. *)\n\nTheorem progress : forall ST t T st,\n has_type empty ST t T ->\n store_well_typed ST st ->\n value t \\/ exists t' st', t / st ==> t' / st'.\n (* was: [value t \\/ exists t', exists st', t / st ==> t' / st'] *)\nProof with eauto.\n intros ST t T st Ht HST. remember (@empty ty) as Gamma.\n (induction Ht); subst; try solve_by_invert...\n - (* T_App *)\n right. destruct IHHt1 as [Ht1p | Ht1p]...\n + (* t1 is a value *)\n inversion Ht1p; subst; try solve_by_invert.\n destruct IHHt2 as [Ht2p | Ht2p]...\n (* t2 steps *)\n inversion Ht2p as [t2' [st' Hstep]].\n exists (tapp (tabs x T t) t2'), st'...\n (* was: [exists (tapp (tabs x T t) t2'). exists st'...] *)\nAbort.\n\n(** Remark: a similar facility for n-ary existentials is provided\n by the module [Coq.Program.Syntax] from the standard library.\n ([Coq.Program.Syntax] supports existentials up to arity 4;\n [LibTactics] supports them up to arity 10. *)\n\nEnd NaryExamples.\n\n\n(* ################################################################# *)\n(** * Tactics for Working with Equality *)\n\n(** One of the major weakness of Coq compared with other interactive\n proof assistants is its relatively poor support for reasoning\n with equalities. The tactics described next aims at simplifying\n pieces of proof scripts manipulating equalities. *)\n\n(** This section presents the following tactics:\n - [asserts_rewrite] for introducing an equality to rewrite with,\n - [cuts_rewrite], which is similar except that its subgoals are swapped,\n - [substs] for improving the [subst] tactic,\n - [fequals] for improving the [f_equal] tactic,\n - [applys_eq] for proving [P x y] using an hypothesis [P x z],\n automatically producing an equality [y = z] as subgoal. *)\n\nModule EqualityExamples.\n\n\n(* ================================================================= *)\n(** ** The Tactics [asserts_rewrite] and [cuts_rewrite] *)\n\n(** The tactic [asserts_rewrite (E1 = E2)] replaces [E1] with [E2] in\n the goal, and produces the goal [E1 = E2]. *)\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n dup.\n (* The old proof: *)\n intros n m.\n assert (H: 0 + n = n). reflexivity. rewrite -> H.\n reflexivity.\n\n (* The new proof: *)\n intros n m.\n asserts_rewrite (0 + n = n).\n reflexivity. (* subgoal [0+n = n] *)\n reflexivity. (* subgoal [n*m = m*n] *)\nQed.\n\n(*** Remark: the syntax [asserts_rewrite (E1 = E2) in H] allows\n rewriting in the hypothesis [H] rather than in the goal. *)\n\n(** The tactic [cuts_rewrite (E1 = E2)] is like\n [asserts_rewrite (E1 = E2)], except that the equality [E1 = E2]\n appears as first subgoal. *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n cuts_rewrite (0 + n = n).\n reflexivity. (* subgoal [n*m = m*n] *)\n reflexivity. (* subgoal [0+n = n] *)\nQed.\n\n(** More generally, the tactics [asserts_rewrite] and [cuts_rewrite]\n can be provided a lemma as argument. For example, one can write\n [asserts_rewrite (forall a b, a*(S b) = a*b+a)].\n This formulation is useful when [a] and [b] are big terms,\n since there is no need to repeat their statements. *)\n\nTheorem mult_0_plus'' : forall u v w x y z: nat,\n (u + v) * (S (w * x + y)) = z.\nProof.\n intros. asserts_rewrite (forall a b, a*(S b) = a*b+a).\n (* first subgoal: [forall a b, a*(S b) = a*b+a] *)\n (* second subgoal: [(u + v) * (w * x + y) + (u + v) = z] *)\nAbort.\n\n\n(* ================================================================= *)\n(** ** The Tactic [substs] *)\n\n(** The tactic [substs] is similar to [subst] except that it\n does not fail when the goal contains \"circular equalities\",\n such as [x = f x]. *)\n\nLemma demo_substs : forall x y (f:nat->nat),\n x = f x ->\n y = x ->\n y = f x.\nProof.\n intros. substs. (* the tactic [subst] would fail here *)\n assumption.\nQed.\n\n\n(* ================================================================= *)\n(** ** The Tactic [fequals] *)\n\n(** The tactic [fequals] is similar to [f_equal] except that it\n directly discharges all the trivial subgoals produced. Moreover,\n the tactic [fequals] features an enhanced treatment of equalities\n between tuples. *)\n\nLemma demo_fequals : forall (a b c d e : nat) (f : nat->nat->nat->nat->nat),\n a = 1 ->\n b = e ->\n e = 2 ->\n f a b c d = f 1 2 c 4.\nProof.\n intros. fequals.\n (* subgoals [a = 1], [b = 2] and [c = c] are proved, [d = 4] remains *)\nAbort.\n\n\n(* ================================================================= *)\n(** ** The Tactic [applys_eq] *)\n\n(** The tactic [applys_eq] is a variant of [eapply] that introduces\n equalities for subterms that do not unify. For example, assume\n the goal is the proposition [P x y] and assume we have the\n assumption [H] asserting that [P x z] holds. We know that we can\n prove [y] to be equal to [z]. So, we could call the tactic\n [assert_rewrite (y = z)] and change the goal to [P x z], but\n this would require copy-pasting the values of [y] and [z].\n With the tactic [applys_eq], we can call [applys_eq H 1], which\n proves the goal and leaves only the subgoal [y = z]. The value [1]\n given as argument to [applys_eq] indicates that we want an equality\n to be introduced for the first argument of [P x y] counting from\n the right. The three following examples illustrate the behavior\n of a call to [applys_eq H 1], a call to [applys_eq H 2], and a\n call to [applys_eq H 1 2]. *)\n\nAxiom big_expression_using : nat->nat. (* Used in the example *)\n\nLemma demo_applys_eq_1 : forall (P:nat->nat->Prop) x y z,\n P x (big_expression_using z) ->\n P x (big_expression_using y).\nProof.\n introv H. dup.\n\n (* The old proof: *)\n assert (Eq: big_expression_using y = big_expression_using z).\n admit. (* Assume we can prove this equality somehow. *)\n rewrite Eq. apply H.\n\n (* The new proof: *)\n applys_eq H 1.\n admit. (* Assume we can prove this equality somehow. *)\nAbort.\n\n(** If the mismatch was on the first argument of [P] instead of\n the second, we would have written [applys_eq H 2]. Recall\n that the occurences are counted from the right. *)\n\nLemma demo_applys_eq_2 : forall (P:nat->nat->Prop) x y z,\n P (big_expression_using z) x ->\n P (big_expression_using y) x.\nProof.\n introv H. applys_eq H 2.\nAbort.\n\n(** When we have a mismatch on two arguments, we want to produce\n two equalities. To achieve this, we may call [applys_eq H 1 2].\n More generally, the tactic [applys_eq] expects a lemma and a\n sequence of natural numbers as arguments. *)\n\nLemma demo_applys_eq_3 : forall (P:nat->nat->Prop) x1 x2 y1 y2,\n P (big_expression_using x2) (big_expression_using y2) ->\n P (big_expression_using x1) (big_expression_using y1).\nProof.\n introv H. applys_eq H 1 2.\n (* produces two subgoals:\n [big_expression_using x1 = big_expression_using x2]\n [big_expression_using y1 = big_expression_using y2] *)\nAbort.\n\nEnd EqualityExamples.\n\n\n(* ################################################################# *)\n(** * Some Convenient Shorthands *)\n\n(** This section of the tutorial introduces a few tactics\n that help make proof scripts shorter and more readable:\n - [unfolds] (without argument) for unfolding the head definition,\n - [false] for replacing the goal with [False],\n - [gen] as a shorthand for [dependent generalize],\n - [skip] for skipping a subgoal even if it contains existential variables,\n - [sort] for re-ordering the proof context by moving moving all\n propositions at the bottom. *)\n\n\n(* ================================================================= *)\n(** ** The Tactic [unfolds] *)\n\nModule UnfoldsExample.\n Import Hoare.\n\n(** The tactic [unfolds] (without any argument) unfolds the\n head constant of the goal. This tactic saves the need to\n name the constant explicitly. *)\n\nLemma bexp_eval_true : forall b st,\n beval st b = true ->\n (bassn b) st.\nProof.\n intros b st Hbe. dup.\n\n (* The old proof: *)\n unfold bassn. assumption.\n\n (* The new proof: *)\n unfolds. assumption.\nQed.\n\n(** Remark: contrary to the tactic [hnf], which may unfold several\n constants, [unfolds] performs only a single step of unfolding. *)\n\n(** Remark: the tactic [unfolds in H] can be used to unfold the\n head definition of the hypothesis [H]. *)\n\nEnd UnfoldsExample.\n\n\n(* ================================================================= *)\n(** ** The Tactics [false] and [tryfalse] *)\n\n(** The tactic [false] can be used to replace any goal with [False].\n In short, it is a shorthand for [exfalso].\n Moreover, [false] proves the goal if it contains an absurd\n assumption, such as [False] or [0 = S n], or if it contains\n contradictory assumptions, such as [x = true] and [x = false]. *)\n\nLemma demo_false : forall n,\n S n = 1 ->\n n = 0.\nProof.\n intros. destruct n. reflexivity. false.\nQed.\n\n(** The tactic [false] can be given an argument: [false H] replace\n the goals with [False] and then applies [H]. *)\n\nLemma demo_false_arg :\n (forall n, n < 0 -> False) ->\n 3 < 0 ->\n 4 < 0.\nProof.\n intros H L. false H. apply L.\nQed.\n\n(** The tactic [tryfalse] is a shorthand for [try solve [false]]:\n it tries to find a contradiction in the goal. The tactic\n [tryfalse] is generally called after a case analysis. *)\n\nLemma demo_tryfalse : forall n,\n S n = 1 ->\n n = 0.\nProof.\n intros. destruct n; tryfalse. reflexivity.\nQed.\n\n\n(* ================================================================= *)\n(** ** The Tactic [gen] *)\n\n(** The tactic [gen] is a shortand for [generalize dependent]\n that accepts several arguments at once. An invokation of\n this tactic takes the form [gen x y z]. *)\n\nModule GenExample.\n Import Stlc.\n Import STLC.\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (update Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma ([x:=v]t) S.\nProof.\n dup.\n\n (* The old proof: *)\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n induction t; intros; simpl.\n admit. admit. admit. admit. admit. admit.\n\n (* The new proof: *)\n introv Htypt Htypv. gen S Gamma.\n induction t; intros; simpl.\n admit. admit. admit. admit. admit. admit.\nAbort.\n\nEnd GenExample.\n\n\n(* ================================================================= *)\n(** ** The Tactics [skip], [skip_rewrite] and [skip_goal] *)\n\n(** Temporarily admitting a given subgoal is very useful when\n constructing proofs. It gives the ability to focus first\n on the most interesting cases of a proof. The tactic [skip]\n is like [admit] except that it also works when the proof\n includes existential variables. Recall that existential\n variables are those whose name starts with a question mark,\n (e.g., [?24]), and which are typically introduced by [eapply]. *)\n\nModule SkipExample.\n Import Stlc.\n Import STLC.\n\nNotation \" t '/' st '==>a*' t' \" := (multi (astep st) t t')\n (at level 40, st at level 39).\n\nExample astep_example1 :\n (3 + (3 * 4)) / { --> 0 } ==>a* 15.\nProof.\n eapply multi_step. skip. (* the tactic [admit] would not work here *)\n eapply multi_step. skip. skip.\n (* Note that because some unification variables have\n not been instantiated, we still need to write\n [Abort] instead of [Qed] at the end of the proof. *)\nAbort.\n\n(** The tactic [skip H: P] adds the hypothesis [H: P] to the context,\n without checking whether the proposition [P] is true.\n It is useful for exploiting a fact and postponing its proof.\n Note: [skip H: P] is simply a shorthand for [assert (H:P). skip.] *)\n\nTheorem demo_skipH : True.\nProof.\n skip H: (forall n m : nat, (0 + n) * m = n * m).\nAbort.\n\n(** The tactic [skip_rewrite (E1 = E2)] replaces [E1] with [E2] in\n the goal, without checking that [E1] is actually equal to [E2]. *)\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n dup.\n\n (* The old proof: *)\n intros n m.\n assert (H: 0 + n = n). skip. rewrite -> H.\n reflexivity.\n\n (* The new proof: *)\n intros n m.\n skip_rewrite (0 + n = n).\n reflexivity.\nQed.\n\n(** Remark: the tactic [skip_rewrite] can in fact be given a lemma\n statement as argument, in the same way as [asserts_rewrite]. *)\n\n(** The tactic [skip_goal] adds the current goal as hypothesis.\n This cheat is useful to set up the structure of a proof by\n induction without having to worry about the induction hypothesis\n being applied only to smaller arguments. Using [skip_goal], one\n can construct a proof in two steps: first, check that the main\n arguments go through without waisting time on fixing the details\n of the induction hypotheses; then, focus on fixing the invokations\n of the induction hypothesis. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st \\\\ st1 ->\n c / st \\\\ st2 ->\n st1 = st2.\nProof.\n (* The tactic [skip_goal] creates an hypothesis called [IH]\n asserting that the statment of [ceval_deterministic] is true. *)\n skip_goal.\n (* Of course, if we call [assumption] here, then the goal is solved\n right away, but the point is to do the proof and use [IH]\n only at the places where we need an induction hypothesis. *)\n introv E1 E2. gen st2.\n (induction E1); introv E2; inverts E2 as.\n - (* E_Skip *) reflexivity.\n - (* E_Ass *)\n subst n.\n reflexivity.\n - (* E_Seq *)\n intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n { (* Proof of assertion *)\n (* was: [apply IHE1_1; assumption.] *)\n (* new: *) eapply IH. eapply E1_1. eapply Red1. }\n subst st3.\n (* was: apply IHE1_2. assumption.] *)\n (* new: *) eapply IH. eapply E1_2. eapply Red2.\n (* The other cases are similiar. *)\nAbort.\n\nEnd SkipExample.\n\n\n(* ================================================================= *)\n(** ** The Tactic [sort] *)\n\nModule SortExamples.\n Import Imp.\n\n(** The tactic [sort] reorganizes the proof context by placing\n all the variables at the top and all the hypotheses at the\n bottom, thereby making the proof context more readable. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st \\\\ st1 ->\n c / st \\\\ st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2.\n (induction E1); intros st2 E2; inverts E2.\n admit. admit. (* Skipping some trivial cases *)\n sort. (* Observe how the context is reorganized *)\nAbort.\n\nEnd SortExamples.\n\n\n(* ################################################################# *)\n(** * Tactics for Advanced Lemma Instantiation *)\n\n(** This last section describes a mechanism for instantiating a lemma\n by providing some of its arguments and leaving other implicit.\n Variables whose instantiation is not provided are turned into\n existentential variables, and facts whose instantiation is not\n provided are turned into subgoals.\n\n Remark: this instantion mechanism goes far beyond the abilities of\n the \"Implicit Arguments\" mechanism. The point of the instantiation\n mechanism described in this section is that you will no longer need\n to spend time figuring out how many underscore symbols you need to\n write. *)\n\n(** In this section, we'll use a useful feature of Coq for decomposing\n conjunctions and existentials. In short, a tactic like [intros] or\n [destruct] can be provided with a pattern [(H1 & H2 & H3 & H4 & H5)],\n which is a shorthand for [[H1 [H2 [H3 [H4 H5]]]]]]. For example,\n [destruct (H _ _ _ Htypt) as [T [Hctx Hsub]].] can be rewritten in\n the form [destruct (H _ _ _ Htypt) as (T & Hctx & Hsub).] *)\n\n\n(* ================================================================= *)\n(** ** Working of [lets] *)\n\n(** When we have a lemma (or an assumption) that we want to exploit,\n we often need to explicitly provide arguments to this lemma,\n writing something like:\n [destruct (typing_inversion_var _ _ _ Htypt) as (T & Hctx & Hsub).]\n The need to write several times the \"underscore\" symbol is tedious.\n Not only we need to figure out how many of them to write down, but\n it also makes the proof scripts look prettly ugly. With the tactic\n [lets], one can simply write:\n [lets (T & Hctx & Hsub): typing_inversion_var Htypt.]\n\n In short, this tactic [lets] allows to specialize a lemma on a bunch\n of variables and hypotheses. The syntax is [lets I: E0 E1 .. EN],\n for building an hypothesis named [I] by applying the fact [E0] to the\n arguments [E1] to [EN]. Not all the arguments need to be provided,\n however the arguments that are provided need to be provided in the\n correct order. The tactic relies on a first-match algorithm based on\n types in order to figure out how the to instantiate the lemma with\n the arguments provided. *)\n\nModule ExamplesLets.\n Import Sub.\n\n(* To illustrate the working of [lets], assume that we want to\n exploit the following lemma. *)\n\nAxiom typing_inversion_var : forall (G:context) (x:string) (T:ty),\n has_type G (tvar x) T ->\n exists S, G x = Some S /\\ subtype S T.\n\n(** First, assume we have an assumption [H] with the type of the form\n [has_type G (tvar x) T]. We can obtain the conclusion of the\n lemma [typing_inversion_var] by invoking the tactics\n [lets K: typing_inversion_var H], as shown next. *)\n\nLemma demo_lets_1 : forall (G:context) (x:string) (T:ty),\n has_type G (tvar x) T ->\n True.\nProof.\n intros G x T H. dup.\n\n (* step-by-step: *)\n lets K: typing_inversion_var H.\n destruct K as (S & Eq & Sub).\n admit.\n\n (* all-at-once: *)\n lets (S & Eq & Sub): typing_inversion_var H.\n admit.\nAbort.\n\n(** Assume now that we know the values of [G], [x] and [T] and we\n want to obtain [S], and have [has_type G (tvar x) T] be produced\n as a subgoal. To indicate that we want all the remaining arguments\n of [typing_inversion_var] to be produced as subgoals, we use a\n triple-underscore symbol [___]. (We'll later introduce a shorthand\n tactic called [forwards] to avoid writing triple underscores.) *)\n\nLemma demo_lets_2 : forall (G:context) (x:string) (T:ty), True.\nProof.\n intros G x T.\n lets (S & Eq & Sub): typing_inversion_var G x T ___.\nAbort.\n\n(** Usually, there is only one context [G] and one type [T] that are\n going to be suitable for proving [has_type G (tvar x) T], so\n we don't really need to bother giving [G] and [T] explicitly.\n It suffices to call [lets (S & Eq & Sub): typing_inversion_var x].\n The variables [G] and [T] are then instantiated using existential\n variables. *)\n\nLemma demo_lets_3 : forall (x:string), True.\nProof.\n intros x.\n lets (S & Eq & Sub): typing_inversion_var x ___.\nAbort.\n\n(** We may go even further by not giving any argument to instantiate\n [typing_inversion_var]. In this case, three unification variables\n are introduced. *)\n\nLemma demo_lets_4 : True.\nProof.\n lets (S & Eq & Sub): typing_inversion_var ___.\nAbort.\n\n(** Note: if we provide [lets] with only the name of the lemma as\n argument, it simply adds this lemma in the proof context, without\n trying to instantiate any of its arguments. *)\n\nLemma demo_lets_5 : True.\nProof.\n lets H: typing_inversion_var.\nAbort.\n\n(** A last useful feature of [lets] is the double-underscore symbol,\n which allows skipping an argument when several arguments have\n the same type. In the following example, our assumption quantifies\n over two variables [n] and [m], both of type [nat]. We would like\n [m] to be instantiated as the value [3], but without specifying a\n value for [n]. This can be achieved by writting [lets K: H __ 3]. *)\n\nLemma demo_lets_underscore :\n (forall n m, n <= m -> n < m+1) ->\n True.\nProof.\n intros H.\n\n (* If we do not use a double underscore, the first argument,\n which is [n], gets instantiated as 3. *)\n lets K: H 3. (* gives [K] of type [forall m, 3 <= m -> 3 < m+1] *)\n clear K.\n\n (* The double underscore preceeding [3] indicates that we want\n to skip a value that has the type [nat] (because [3] has\n the type [nat]). So, the variable [m] gets instiated as [3]. *)\n lets K: H __ 3. (* gives [K] of type [?X <= 3 -> ?X < 3+1] *)\n clear K.\nAbort.\n\n\n(** Note: one can write [lets: E0 E1 E2] in place of [lets H: E0 E1 E2].\n In this case, the name [H] is chosen arbitrarily.\n\n Note: the tactics [lets] accepts up to five arguments. Another\n syntax is available for providing more than five arguments.\n It consists in using a list introduced with the special symbol [>>],\n for example [lets H: (>> E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 10)]. *)\n\nEnd ExamplesLets.\n\n\n(* ================================================================= *)\n(** ** Working of [applys], [forwards] and [specializes] *)\n\n(** The tactics [applys], [forwards] and [specializes] are\n shorthand that may be used in place of [lets] to perform\n specific tasks.\n\n - [forwards] is a shorthand for instantiating all the arguments\n of a lemma. More precisely, [forwards H: E0 E1 E2 E3] is the\n same as [lets H: E0 E1 E2 E3 ___], where the triple-underscore\n has the same meaning as explained earlier on.\n\n - [applys] allows building a lemma using the advanced instantion\n mode of [lets], and then apply that lemma right away. So,\n [applys E0 E1 E2 E3] is the same as [lets H: E0 E1 E2 E3]\n followed with [eapply H] and then [clear H].\n\n - [specializes] is a shorthand for instantiating in-place\n an assumption from the context with particular arguments.\n More precisely, [specializes H E0 E1] is the same as\n [lets H': H E0 E1] followed with [clear H] and [rename H' into H].\n\n Examples of use of [applys] appear further on. Several examples of\n use of [forwards] can be found in the tutorial chapter [UseAuto]. *)\n\n\n(* ================================================================= *)\n(** ** Example of Instantiations *)\n\nModule ExamplesInstantiations.\n Import Sub.\n\n(** The following proof shows several examples where [lets] is used\n instead of [destruct], as well as examples where [applys] is used\n instead of [apply]. The proof also contains some holes that you\n need to fill in as an exercise. *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (update Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma ([x:=v]t) S.\nProof with eauto.\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n (induction t); intros; simpl.\n - (* tvar *)\n rename s into y.\n\n (* An example where [destruct] is replaced with [lets]. *)\n (* old: destruct (typing_inversion_var _ _ _ Htypt) as [T [Hctx Hsub]].*)\n (* new: *) lets (T&Hctx&Hsub): typing_inversion_var Htypt.\n unfold update, t_update in Hctx.\n destruct (beq_stringP x y)...\n + (* x=y *)\n subst.\n inversion Hctx; subst. clear Hctx.\n apply context_invariance with empty...\n intros x Hcontra.\n\n (* A more involved example. *)\n (* old: destruct (free_in_context _ _ S empty Hcontra)\n as [T' HT']... *)\n (* new: *)\n lets [T' HT']: free_in_context S (@empty ty) Hcontra...\n inversion HT'.\n - (* tapp *)\n\n (* Exercise: replace the following [destruct] with a [lets]. *)\n (* old: destruct (typing_inversion_app _ _ _ _ Htypt)\n as [T1 [Htypt1 Htypt2]]. eapply T_App... *)\n (* FILL IN HERE *) admit.\n\n - (* tabs *)\n rename s into y. rename t into T1.\n\n (* Here is another example of using [lets]. *)\n (* old: destruct (typing_inversion_abs _ _ _ _ _ Htypt). *)\n (* new: *) lets (T2&Hsub&Htypt2): typing_inversion_abs Htypt.\n\n (* An example of where [apply with] can be replaced with [applys]. *)\n (* old: apply T_Sub with (TArrow T1 T2)... *)\n (* new: *) applys T_Sub (TArrow T1 T2)...\n apply T_Abs...\n destruct (beq_stringP x y).\n + (* x=y *)\n eapply context_invariance...\n subst.\n intros x Hafi. unfold update, t_update.\n destruct (beq_stringP y x)...\n + (* x<>y *)\n apply IHt. eapply context_invariance...\n intros z Hafi. unfold update, t_update.\n destruct (beq_stringP y z)...\n subst. rewrite false_beq_string...\n - (* ttrue *)\n lets: typing_inversion_true Htypt...\n - (* tfalse *)\n lets: typing_inversion_false Htypt...\n - (* tif *)\n lets (Htyp1&Htyp2&Htyp3): typing_inversion_if Htypt...\n - (* tunit *)\n (* An example where [assert] can be replaced with [lets]. *)\n (* old: assert (subtype TUnit S)\n by apply (typing_inversion_unit _ _ Htypt)... *)\n (* new: *) lets: typing_inversion_unit Htypt...\n \nAdmitted.\n\nEnd ExamplesInstantiations.\n\n\n(* ################################################################# *)\n(** * Summary *)\n\n(** In this chapter we have presented a number of tactics that help make\n proof script more concise and more robust on change.\n\n - [introv] and [inverts] improve naming and inversions.\n\n - [false] and [tryfalse] help discarding absurd goals.\n\n - [unfolds] automatically calls [unfold] on the head definition.\n\n - [gen] helps setting up goals for induction.\n\n - [cases] and [cases_if] help with case analysis.\n\n - [splits], [branch] and [exists] to deal with n-ary constructs.\n\n - [asserts_rewrite], [cuts_rewrite], [substs] and [fequals] help\n working with equalities.\n\n - [lets], [forwards], [specializes] and [applys] provide means\n of very conveniently instantiating lemmas.\n\n - [applys_eq] can save the need to perform manual rewriting steps\n before being able to apply lemma.\n\n - [skip], [skip_rewrite] and [skip_goal] give the flexibility to\n choose which subgoals to try and discharge first.\n\n Making use of these tactics can boost one's productivity in Coq proofs.\n\n If you are interested in using [LibTactics.v] in your own developments,\n make sure you get the lastest version from:\n http://www.chargueraud.org/softs/tlc/.\n\n*)\n\n(** $Date$ *)\n", "meta": {"author": "kolya-vasiliev", "repo": "programming-language-foundations-2018", "sha": "f1f8daf251503979ec11a9e206515af07924321a", "save_path": "github-repos/coq/kolya-vasiliev-programming-language-foundations-2018", "path": "github-repos/coq/kolya-vasiliev-programming-language-foundations-2018/programming-language-foundations-2018-f1f8daf251503979ec11a9e206515af07924321a/UseTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.15002882814282253, "lm_q1q2_score": 0.05774791797486534}} {"text": "Set Warnings \"-notation-overridden,-parsing\".\n\nFrom Coq Require Import Arith.Arith.\n\nRequire Import maps.\nRequire Import imp.\nRequire Import types.\nRequire Import smallstep.\nRequire Import libtactics.\n\nRequire stlc.\nRequire equiv.\nRequire imp.\nRequire references.\nRequire smallstep.\nRequire hoare.\nRequire sub.\n\n\n(* タクティックintrov *)\nModule IntrovExamples.\n Import stlc.\n Import imp.\n Import STLC.\n\n(*\nintrov : 仮定をintro\n *)\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n introv E1 E2. Abort.\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n introv. Abort.\n\nTheorem ceval_deterministic': forall c st st1,\n (st =[ c ]=> st1) ->\n forall st2,\n (st =[ c ]=> st2) ->\n st1 = st2.\nProof.\n introv E1 E2. Abort.\n\nTheorem exists_impl: forall X (P : X -> Prop) (Q : Prop) (R : Prop),\n (forall x, P x -> Q) ->\n ((exists x, P x) -> Q).\nProof.\n introv [x H2]. eauto.\nQed.\n\nEnd IntrovExamples.\n\n\n(* タクティックinverts *)\nModule InvertsExamples.\n Import stlc.\n Import equiv.\n Import imp.\n Import STLC.\n\nTheorem skip_left: forall c,\n cequiv (SKIP;; c) c.\nProof.\n introv. split; intros H.\n dup. - inversion H. subst. inversion H2. subst. assumption.\n - inverts H. inverts H2. assumption.\nAbort.\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n introv E1 E2. generalize dependent st2.\n induction E1; intros st2 E2.\n admit. admit. dup. - inversion E2. subst. admit.\n - inverts E2. admit.\nAbort.\n\n(* 。 inverts H as.では、生成される変数と仮定がコンテキストではなくゴールに置かれます。 この戦略により、 これらの変数と仮定にintrosやintrovを使って明示的に名前を付けることができるようになります。 *)\nTheorem ceval_deterministic': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n introv E1 E2. generalize dependent st2.\n (induction E1); intros st2 E2;\n inverts E2 as.\n - reflexivity.\n -\n \n subst n.\n reflexivity.\n -\n \n intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n { apply IHE1_1; assumption. }\n subst st3.\n apply IHE1_2. assumption.\n -\n \n intros.\n apply IHE1. assumption.\n -\n intros.\n rewrite H in H5. inversion H5.\nAbort.\n\nExample typing_nonexample_1 :\n ~ exists T,\n has_type empty\n (abs x Bool\n (abs y Bool\n (app (var x) (var y))))\n T.\nProof.\n dup 3.\n\n - intros C. destruct C.\n inversion H. subst. clear H.\n inversion H5. subst. clear H5.\n inversion H4. subst. clear H4.\n inversion H2. subst. clear H2.\n inversion H1.\n\n - intros C. destruct C.\n inverts H as H1.\n inverts H1 as H2.\n inverts H2 as H3 H4.\n inverts H3 as H5.\n inverts H5.\n\n - intros C. destruct C.\n inverts H as H.\n inverts H as H.\n inverts H as H1 H2.\n inverts H1 as H1.\n inverts H1.\nQed.\n\nEnd InvertsExamples.\n\n\n\n(* n-引数論理演算のためのタクティック *)\n(*\nsplits :n個の and を分解します\nbranch :n個の or を分解します\n*)\nModule NaryExamples.\n Import references.\n Import smallstep.\n Import STLCRef.\n\nLemma demo_splits : forall n m,\n n > 0 /\\ n < m /\\ m < n+10 /\\ m <> 3.\nProof.\n intros. splits.\nAbort.\n\nLemma demo_branch : forall n m,\n n < m \\/ n = m \\/ m < n.\nProof.\n intros.\n destruct (lt_eq_lt_dec n m) as [[H1|H2]|H3].\n - branch 1. apply H1.\n - branch 2. apply H2.\n - branch 3. apply H3.\nQed.\n\nEnd NaryExamples.\n\n\n\n(* 等式を扱うタクティック *)\n(*\nasserts_rewrite : 書き換えのための等式を導入します\ncuts_rewrite : サブゴールが交換される以外は同じです\nsubsts : subst タクティックを改良します\nfequals : f_equal タクティックを改良します\napplys_eq : 仮定 P x z を使って、等式 y = z をサブゴールとして自動生成することで、 P x y を証明します\n*)\nModule EqualityExamples.\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n dup.\n intros n m.\n assert (H: 0 + n = n). reflexivity. rewrite -> H.\n reflexivity.\n\n intros n m.\n asserts_rewrite (0 + n = n).\n reflexivity. reflexivity. Qed.\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n cuts_rewrite (0 + n = n).\n reflexivity. reflexivity. Qed.\n\n(* タクティック asserts_rewrite と cuts_rewrite は補題を引数としてとることができます。 *)\nTheorem mult_0_plus'' : forall u v w x y z: nat,\n (u + v) * (S (w * x + y)) = z.\nProof.\n intros. asserts_rewrite (forall a b, a*(S b) = a*b+a).\nAbort.\n\n(*\nタクティック substs\nゴールが x = f x のような「循環する等式」を含むときも失敗しません。\n*)\nLemma demo_substs : forall x y (f:nat->nat),\n x = f x ->\n y = x ->\n y = f x.\nProof.\n intros. substs. assumption.\nQed.\n\n(*\nタクティック fequals\nタクティック fequals は f_equal と同様ですが、 生成される自明なサブゴールを直接解決してしまう点が違います。 さらに、タクティック fequals はタプル間の等式の扱いが強化されています。\n *)\n\nLemma demo_fequals : forall (a b c d e : nat) (f : nat->nat->nat->nat->nat),\n a = 1 ->\n b = e ->\n e = 2 ->\n f a b c d = f 1 2 c 4.\nProof.\n intros. fequals.\nAbort.\n\nAxiom big_expression_using : nat->nat.\nLemma demo_applys_eq_1 : forall (P:nat->nat->Prop) x y z,\n P x (big_expression_using z) ->\n P x (big_expression_using y).\nProof.\n introv H. dup.\n\n assert (Eq: big_expression_using y = big_expression_using z).\n admit. rewrite Eq. apply H.\n\n applys_eq H 1.\n admit. Abort.\n\nLemma demo_applys_eq_2 : forall (P:nat->nat->Prop) x y z,\n P (big_expression_using z) x ->\n P (big_expression_using y) x.\nProof.\n introv H. applys_eq H 2.\nAbort.\n\nLemma demo_applys_eq_3 : forall (P:nat->nat->Prop) x1 x2 y1 y2,\n P (big_expression_using x2) (big_expression_using y2) ->\n P (big_expression_using x1) (big_expression_using y1).\nProof.\n introv H. applys_eq H 1 2.\nAbort.\n\nEnd EqualityExamples.\n\n\n\n\n(* 便利な略記法をいくつか *)\n(*\nunfolds (引数なし): 先頭の定義を unfold します\nfalse : ゴールを False で置換します\ngen : dependent generalize の略記法です\nadmits : 承認した事実に名前をつけます\nadmit_rewrite : 承認した等式で書き換えます\nadmit_goal : 帰納法の仮定を、減少していることを示さないで使えるようにします\nsort : 全ての命題を証明コンテキストの下へ動かします\n*)\nModule UnfoldsExample.\n Import hoare.\n\nLemma bexp_eval_true : forall b st,\n beval st b = true ->\n (bassn b) st.\nProof.\n intros b st Hbe. dup.\n\n unfold bassn. assumption.\n\n unfolds. assumption.\nQed.\nEnd UnfoldsExample.\n\nLemma demo_false : forall n,\n S n = 1 ->\n n = 0.\nProof.\n intros. destruct n. reflexivity. false.\nQed.\n\nLemma demo_false_arg :\n (forall n, n < 0 -> False) ->\n 3 < 0 ->\n 4 < 0.\nProof.\n intros H L. false H. apply L.\nQed.\n\nLemma demo_tryfalse : forall n,\n S n = 1 ->\n n = 0.\nProof.\n intros. destruct n; tryfalse. reflexivity.\nQed.\n\n(* genは generalize dependent の略記法 *)\nModule GenExample.\n Import stlc.\n Import STLC.\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (update Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma ([x:=v]t) S.\nProof.\n dup.\n\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n induction t; intros; simpl.\n admit. admit. admit. admit. admit. admit.\n\n introv Htypt Htypv. gen S Gamma.\n induction t; intros; simpl.\n admit. admit. admit. admit. admit. admit.\nAbort.\n\nEnd GenExample.\n\nModule SkipExample.\n Import stlc.\n Import STLC.\n\nTheorem demo_admits : True.\nProof.\n admits H: (forall n m : nat, (0 + n) * m = n * m).\nAbort.\n\nTheorem mult_plus_0 : forall n m : nat,\n (n + 0) * m = n * m.\nProof.\n dup 3.\n\n intros n m.\n assert (H: n + 0 = n). admit. rewrite -> H. clear H.\n reflexivity.\n\n intros n m.\n admit_rewrite (n + 0 = n).\n reflexivity.\n\n intros n m.\n admit_rewrite (forall a, a + 0 = a).\n reflexivity.\nAdmitted.\n\n(* タクティックadmit_goalは現在のゴールを仮定として追加します。 このごまかしは帰納法による証明の構造の構成の際に、 帰納法の仮定がより小さい引数だけに適用されるかを心配しないで済むため有用です。 admit_goalを使うことで、証明を次の2ステップで構成できます: 最初に、帰納法の仮定の細部の調整に時間を浪費せずに、主要な議論が通るかをチェックし、 その後、帰納法の仮定の呼び出しの調整にフォーカスするというステップです。 *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n admit_goal.\n introv E1 E2. gen st2.\n (induction E1); introv E2; inverts E2 as.\n - reflexivity.\n -\n subst n.\n reflexivity.\n -\n intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n {\n \n eapply IH. eapply E1_1. eapply Red1. }\n subst st3.\neapply IH. eapply E1_2. eapply Red2.\nAbort.\n\nEnd SkipExample.\n\nModule SortExamples.\n Import imp.\n\n(* タクティックsortは証明コンテキストを再構成し、変数が上に仮定が下になるようにします。 これにより、証明コンテキストはより読みやすくなります。 *)\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2.\n (induction E1); intros st2 E2; inverts E2.\n admit. admit. sort. Abort.\n\nEnd SortExamples.\n\n\n(* 高度な補題具体化のためのタクティック *)\n\n(* 利用したい補題(または仮定)がある場合、大抵、この補題に明示的に引数を与える必要があります。 例えば次のような形です: destruct (typing_inversion_var _ _ _ Htypt) as (T & Hctx & Hsub). 何回も'_'記号を書かなければならないのは面倒です。 何回書くかを計算しなければならないだけでなく、このことで証明記述がかなり汚なくもなります。 タクティックletsを使うことで、次のように簡単に書くことができます: lets (T & Hctx & Hsub): typing_inversion_var Htypt. *)\nModule ExamplesLets.\n Import sub.\n\n\nImport sub.\n\nAxiom typing_inversion_var : forall (G:context) (x:string) (T:ty),\n has_type G (var x) T ->\n exists S, G x = Some S /\\ subtype S T.\n\nLemma demo_lets_1 : forall (G:context) (x:string) (T:ty),\n has_type G (var x) T ->\n True.\nProof.\n intros G x T H. dup.\n\n lets K: typing_inversion_var H.\n destruct K as (S & Eq & Sub).\n admit.\n\n lets (S & Eq & Sub): typing_inversion_var H.\n admit.\nAbort.\n\nLemma demo_lets_2 : forall (G:context) (x:string) (T:ty), True.\nProof.\n intros G x T.\n lets (S & Eq & Sub): typing_inversion_var G x T ___.\nAbort.\n\nLemma demo_lets_3 : forall (x:string), True.\nProof.\n intros x.\n lets (S & Eq & Sub): typing_inversion_var x ___.\nAbort.\n\nLemma demo_lets_4 : True.\nProof.\n lets (S & Eq & Sub): typing_inversion_var ___.\nAbort.\n\nLemma demo_lets_5 : True.\nProof.\n lets H: typing_inversion_var.\nAbort.\n\nLemma demo_lets_underscore :\n (forall n m, n <= m -> n < m+1) ->\n True.\nProof.\n intros H.\n\n lets K: H 3. clear K.\n\n lets K: H __ 3. clear K.\nAbort.\n\nEnd ExamplesLets.\n\n(*\nforwardsは補題のすべての引数を具体化する略記法です。 より詳しくは、forwards H: E0 E1 E2 E3 は lets H: E0 E1 E2 E3 ___ と同じです。ここで ___ の意味は前に説明した通りです。\napplysは、letsの高度な具体化モードにより補題を構築し、 それをすぐに使うことにあたります。 これから、applys E0 E1 E2 E3 は、 lets H: E0 E1 E2 E3 の後 eapply H、clear H と続けることと同じです。\nspecializesは、コンテキストの仮定を特定の引数でその場で具体化することの略記法です。 より詳しくは、specializes H E0 E1 は lets H': H E0 E1 の後 clear H、rename H' into H と続けることと同じです。\n *)\n\nModule ExamplesInstantiations.\n Import sub.\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (update Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma ([x:=v]t) S.\nProof with eauto.\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n (induction t); intros; simpl.\n -\n rename s into y.\n\nlets (T&Hctx&Hsub): typing_inversion_var Htypt.\n unfold update, t_update in Hctx.\n destruct (eqb_stringP x y)...\n +\n subst.\n inversion Hctx; subst. clear Hctx.\n apply context_invariance with empty...\n intros x Hcontra.\n\n lets [T' HT']: free_in_context S (@empty ty) Hcontra...\n inversion HT'.\n -\n\n \n \n \n admit.\n\n -\n rename s into y. rename t into T1.\n\nlets (T2&Hsub&Htypt2): typing_inversion_abs Htypt.\n\napplys T_Sub (Arrow T1 T2)...\n apply T_Abs...\n destruct (eqb_stringP x y).\n +\n eapply context_invariance...\n subst.\n intros x Hafi. unfold update, t_update.\n destruct (eqb_stringP y x)...\n +\n apply IHt. eapply context_invariance...\n intros z Hafi. unfold update, t_update.\n destruct (eqb_stringP y z)...\n subst. rewrite false_eqb_string...\n -\n lets: typing_inversion_true Htypt...\n -\n lets: typing_inversion_false Htypt...\n -\n lets (Htyp1&Htyp2&Htyp3): typing_inversion_if Htypt...\n -\n \n \n lets: typing_inversion_unit Htypt...\n\nAdmitted.\n\nEnd ExamplesInstantiations.\n\n(* inversionの名前付けをよりよくするintrovとinverts。 *)\n(* 証明できないゴールを捨てやすくするfalseとtryfalse。 *)\n(* 先頭の定義を展開する(unfoldする)unfolds。 *)\n(* 帰納法の状況を整えやすくするgen。 *)\n(* 場合分けをよりよくするcasesとcases_if。 *)\n(* n-引数コンストラクタを扱うsplitsとbranch。 *)\n(* 等価性を扱いやすくするasserts_rewrite、cuts_rewrite、substs、fequals。 *)\n(* 補題の具体化と使用方法を表現するlets、forwards、specializes、applys。 *)\n(* 補題を適用する前に行う書き換えを自動化するapplys_eq。 *)\n(* 柔軟に集中、無視するサブゴールを選ぶadmits、admit_rewrite、admit_goal。 *)\n", "meta": {"author": "NeM-T", "repo": "sfc", "sha": "e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e", "save_path": "github-repos/coq/NeM-T-sfc", "path": "github-repos/coq/NeM-T-sfc/sfc-e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e/practice/Coq/SF/2nd/usetactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11757214282138605, "lm_q1q2_score": 0.05694960444844862}} {"text": "(** **** SNU 4190.310, 2016 Spring *)\n\n(** Assignment 08 *)\n(** Due: 2016/12/07 23:59 *)\n\n(* Important: \n - Do NOT import other files.\n\n - You are NOT allowed to use the [admit] tactic.\n\n - You are ALLOWED to use any tactics including:\n [tauto], [intuition], [firstorder], [omega].\n\n - Just leave [exact FILL_IN_HERE] for those problems that you fail to prove.\n*)\n\nRequire Export Coq.Bool.Bool.\nRequire Export Coq.Arith.Arith.\nRequire Export Coq.Arith.EqNat.\nRequire Export Coq.omega.Omega.\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Maps.\nRequire Export Imp.\n\nDefinition FILL_IN_HERE {T: Type} : T. Admitted.\n\nDefinition Assertion := state -> Prop.\n\nDefinition assert_implies (P Q : Assertion) : Prop :=\n forall st, P st -> Q st.\n\nNotation \"P ->> Q\" :=\n (assert_implies P Q) (at level 80) : hoare_spec_scope.\nOpen Scope hoare_spec_scope.\n\nNotation \"P <<->> Q\" :=\n (P ->> Q /\\ Q ->> P) (at level 80) : hoare_spec_scope.\n\nDefinition hoare_triple\n (P:Assertion) (c:com) (Q:Assertion) : Prop :=\n forall st st',\n c / st \\\\ st' ->\n P st ->\n Q st'.\n\nNotation \"{{ P }} c {{ Q }}\" :=\n (hoare_triple P c Q) (at level 90, c at next level)\n : hoare_spec_scope.\n\nDefinition assn_sub X a P : Assertion :=\n fun (st : state) =>\n P (t_update st X (aeval st a)).\n\nNotation \"P [ X |-> a ]\" := (assn_sub X a P) (at level 10).\n\nDefinition bassn b : Assertion :=\n fun st => (beval st b = true).\n\n(** A couple of useful facts about [bassn]: *)\n\nLemma bexp_eval_true : forall b st,\n beval st b = true -> (bassn b) st.\nProof.\n intros b st Hbe.\n unfold bassn. assumption. Qed.\n\nLemma bexp_eval_false : forall b st,\n beval st b = false -> ~ ((bassn b) st).\nProof.\n intros b st Hbe contra.\n unfold bassn in contra.\n rewrite -> contra in Hbe. inversion Hbe. Qed.\n\nTheorem hoare_asgn : forall Q X a,\n {{Q [X |-> a]}} (X ::= a) {{Q}}.\nProof.\n unfold hoare_triple.\n intros Q X a st st' HE HQ.\n inversion HE. subst.\n unfold assn_sub in HQ. assumption. Qed.\n\nTheorem hoare_consequence_pre : forall (P P' Q : Assertion) c,\n {{P'}} c {{Q}} ->\n P ->> P' ->\n {{P}} c {{Q}}.\nProof.\n intros P P' Q c Hhoare Himp.\n intros st st' Hc HP. apply (Hhoare st st'). \n assumption. apply Himp. assumption. Qed.\n\nTheorem hoare_consequence_post : forall (P Q Q' : Assertion) c,\n {{P}} c {{Q'}} ->\n Q' ->> Q ->\n {{P}} c {{Q}}.\nProof.\n intros P Q Q' c Hhoare Himp.\n intros st st' Hc HP. \n apply Himp.\n apply (Hhoare st st'). \n assumption. assumption. Qed.\n\nTheorem hoare_consequence : forall (P P' Q Q' : Assertion) c,\n {{P'}} c {{Q'}} ->\n P ->> P' ->\n Q' ->> Q ->\n {{P}} c {{Q}}.\nProof.\n intros P P' Q Q' c Hht HPP' HQ'Q.\n apply hoare_consequence_pre with (P' := P').\n apply hoare_consequence_post with (Q' := Q').\n assumption. assumption. assumption. Qed.\n\nTheorem hoare_skip : forall P,\n {{P}} SKIP {{P}}.\nProof.\n intros P st st' H HP. inversion H. subst.\n assumption. Qed.\n\nTheorem hoare_seq : forall P Q R c1 c2,\n {{Q}} c2 {{R}} ->\n {{P}} c1 {{Q}} ->\n {{P}} c1;;c2 {{R}}.\nProof.\n intros P Q R c1 c2 H1 H2 st st' H12 Pre.\n inversion H12; subst.\n apply (H1 st'0 st'); try assumption.\n apply (H2 st st'0); assumption. Qed.\n\nTheorem hoare_if_wp : forall P1 P2 Q b c1 c2,\n {{P1}} c1 {{Q}} ->\n {{P2}} c2 {{Q}} ->\n {{fun st => (beval st b = true -> P1 st) /\\ (beval st b = false -> P2 st) }} \n (IFB b THEN c1 ELSE c2 FI) \n {{Q}}.\nProof.\n intros Q1 Q2 Q b c1 c2 HTrue HFalse st st' HE [HQ1 HQ2].\n inversion HE; subst; eauto. \nQed.\n\nLemma hoare_while : forall P b c,\n {{fun st => P st /\\ bassn b st}} c {{P}} ->\n {{P}} WHILE b DO c END {{fun st => P st /\\ ~ (bassn b st)}}.\nProof.\n intros P b c Hhoare st st' He HP.\n (* Like we've seen before, we need to reason by induction\n on [He], because, in the \"keep looping\" case, its hypotheses\n talk about the whole loop instead of just [c]. *)\n remember (WHILE b DO c END) as wcom eqn:Heqwcom.\n induction He;\n try (inversion Heqwcom); subst; clear Heqwcom.\n - (* E_WhileEnd *)\n split. assumption. apply bexp_eval_false. assumption.\n - (* E_WhileLoop *)\n apply IHHe2. reflexivity.\n apply (Hhoare st st'). assumption.\n split. assumption. apply bexp_eval_true. assumption.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/08/D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.11596071214366646, "lm_q1q2_score": 0.05662169197343281}} {"text": "(** * UseTactics: Tactic Library for Coq: A Gentle Introduction *)\n\n(* Chapter maintained by Arthur Chargueraud *)\n\n(** Coq comes with a set of builtin tactics, such as [reflexivity],\n [intros], [inversion] and so on. While it is possible to conduct \n proofs using only those tactics, you can significantly increase \n your productivity by working with a set of more powerful tactics. \n This chapter describes a number of such very useful tactics, which, \n for various reasons, are not yet available by default in Coq.\n These tactics are defined in the [LibTactics.v] file. *)\n\nRequire Import LibTactics. \n\n(** Remark: SSReflect is another package providing powerful tactics.\n The library \"LibTactics\" differs from \"SSReflect\" in two respects:\n - \"SSReflect\" was primarily developed for proving mathematical\n theorems, whereas \"LibTactics\" was primarily developed for proving\n theorems on programming languages. In particular, \"LibTactics\" \n provides a number of useful tactics that have no counterpart in the \n \"SSReflect\" package.\n - \"SSReflect\" entirely rethinks the presentation of tactics,\n whereas \"LibTactics\" mostly stick to the traditional\n presentation of Coq tactics, simply providing a number of\n additional tactics. For this reason, \"LibTactics\" is\n probably easier to get started with than \"SSReflect\". *)\n\n(** This chapter is a tutorial focusing on the most useful features\n from the \"LibTactics\" library. It does not aim at presenting all\n the features of \"LibTactics\". The detailed specification of tactics\n can be found in the source file [LibTactics.v]. Further documentation \n as well as demos can be found at http://www.chargueraud.org/softs/tlc/ . *)\n\n(** In this tutorial, tactics are presented using examples taken from\n the core chapters of the \"Software Foundations\" course. To illustrate \n the various ways in which a given tactic can be used, we use a \n tactic that duplicates a given goal. More precisely, [dup] produces \n two copies of the current goal, and [dup n] produces [n] copies of it. *)\n\n\n(* ####################################################### *)\n(** * Tactics for introduction and case analysis *)\n\n(** This section presents the following tactics:\n - [introv], for naming hypotheses more efficiently,\n - [inverts], for improving the [inversion] tactic,\n - [cases], for performing a case analysis without losing information,\n - [cases_if], for automating case analysis on the argument of [if]. *)\n\n\n(* ####################################################### *)\n(** ** The tactic [introv] *)\n\nModule IntrovExamples.\n Require Import Stlc.\n Import Imp STLC. \n\n(** The tactic [introv] allows to automatically introduce the \n variables of a theorem and explicitly name the hypotheses \n involved. In the example shown next, the variables [c], \n [st], [st1] and [st2] involved in the statement of determinism\n need not be named explicitly, because their name where already\n given in the statement of the lemma. On the contrary, it is\n useful to provide names for the two hypotheses, which we \n name [E1] and [E2], respectively. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof.\n introv E1 E2. (* was [intros c st st1 st2 E1 E2] *)\nAbort.\n\n(** When there is no hypothesis to be named, one can call \n [introv] without any argument. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n introv. (* was [intros X P Q] *)\nAbort.\n\n(** The tactic [introv] also applies to statements in which\n [forall] and [->] are interleaved. *)\n \nTheorem ceval_deterministic': forall c st st1,\n (c / st || st1) -> forall st2, (c / st || st2) -> st1 = st2.\nProof.\n introv E1 E2. (* was [intros c st st1 E1 st2 E2] *)\nAbort.\n\n(** Like the arguments of [intros], the arguments of [introv] \n can be structured patterns. *)\n\nTheorem exists_impl: forall X (P : X -> Prop) (Q : Prop) (R : Prop),\n (forall x, P x -> Q) ->\n ((exists x, P x) -> Q).\nProof.\n introv [x H2]. eauto.\n (* same as [intros X P Q R H1 [x H2].], which is itself short \n for [intros X P Q R H1 H2. destruct H2 as [x H2].] *)\nQed.\n\n(** Remark: the tactic [introv] works even when definitions \n need to be unfolded in order to reveal hypotheses. *)\n\nEnd IntrovExamples.\n\n\n(* ####################################################### *)\n(** ** The tactic [inverts] *)\n\nModule InvertsExamples.\n Require Import Stlc Equiv Imp.\n Import STLC.\n\n(** The [inversion] tactic of Coq is not very satisfying for\n three reasons. First, it produces a bunch of equalities \n which one typically wants to substitute away, using [subst].\n Second, it introduces meaningless names for hypotheses.\n Third, a call to [inversion H] does not remove [H] from the\n context, even though in most cases an hypothesis is no longer \n needed after being inverted. The tactic [inverts] address all \n of these three issues. It is intented to be used in place of\n the tactic [inversion]. *)\n\n(** The following example illustrates how the tactic [inverts H] \n behaves mostly like [inversion H] except that it performs \n some substitutions in order to eliminate the trivial equalities\n that are being produced by [inversion]. *)\n\nTheorem skip_left: forall c,\n cequiv (SKIP;; c) c.\nProof. \n introv. split; intros H. \n dup. (* duplicate the goal for comparison *)\n (* was: *)\n inversion H. subst. inversion H2. subst. assumption.\n (* now: *)\n inverts H. inverts H2. assumption.\nAbort.\n\n(** A slightly more interesting example appears next. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n introv E1 E2. generalize dependent st2.\n (ceval_cases (induction E1) Case); intros st2 E2.\n admit. admit. (* skip some basic cases *)\n dup. (* duplicate the goal for comparison *)\n (* was: *) inversion E2. subst. admit.\n (* now: *) inverts E2. admit.\nAbort.\n\n(** The tactic [inverts H as.] is like [inverts H] except that the \n variables and hypotheses being produced are placed in the goal\n rather than in the context. This strategy allows naming those\n new variables and hypotheses explicitly, using either [intros] \n or [introv]. *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n introv E1 E2. generalize dependent st2.\n (ceval_cases (induction E1) Case); intros st2 E2; \n inverts E2 as.\n Case \"E_Skip\". reflexivity.\n Case \"E_Ass\". \n (* Observe that the variable [n] is not automatically \n substituted because, contrary to [inversion E2; subst],\n the tactic [inverts E2] does not substitute the equalities\n that exist before running the inversion. *) \n (* new: *) subst n. \n reflexivity.\n Case \"E_Seq\". \n (* Here, the newly created variables can be introduced\n using intros, so they can be assigned meaningful names,\n for example [st3] instead of [st'0]. *)\n (* new: *) intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n SCase \"Proof of assertion\". apply IHE1_1; assumption.\n subst st3.\n apply IHE1_2. assumption. \n Case \"E_IfTrue\". \n SCase \"b1 evaluates to true\".\n (* In an easy case like this one, there is no need to\n provide meaningful names, so we can just use [intros] *)\n (* new: *) intros. \n apply IHE1. assumption.\n SCase \"b1 evaluates to false (contradiction)\".\n (* new: *) intros.\n rewrite H in H5. inversion H5.\n (* The other cases are similiar *)\nAbort.\n\n(** In the particular case where a call to [inversion] produces \n a single subgoal, one can use the syntax [inverts H as H1 H2 H3] \n for calling [inverts] and naming the new hypotheses [H1], [H2] \n and [H3]. In other words, the tactic [inverts H as H1 H2 H3] is\n equivalent to [inverts H as; introv H1 H2 H3]. An example follows. *)\n\nTheorem skip_left': forall c,\n cequiv (SKIP;; c) c.\nProof. \n introv. split; intros H.\n inverts H as U V. (* new hypotheses are named [U] and [V] *)\n inverts U. assumption.\nAbort.\n\n(** A more involved example appears next. In particular, this example\n shows that the name of the hypothesis being inverted can be reused. *)\n\nExample typing_nonexample_1 :\n ~ exists T,\n has_type empty \n (tabs x TBool\n (tabs y TBool\n (tapp (tvar x) (tvar y))))\n T.\nProof.\n dup 3.\n\n (* The old proof: *)\n intros C. destruct C.\n inversion H. subst. clear H.\n inversion H5. subst. clear H5.\n inversion H4. subst. clear H4.\n inversion H2. subst. clear H2.\n inversion H5. subst. clear H5.\n inversion H1. \n\n (* The new proof: *)\n intros C. destruct C.\n inverts H as H1.\n inverts H1 as H2.\n inverts H2 as H3.\n inverts H3 as H4.\n inverts H4.\n\n (* The new proof, alternative: *)\n intros C. destruct C.\n inverts H as H.\n inverts H as H.\n inverts H as H.\n inverts H as H.\n inverts H.\nQed.\n\nEnd InvertsExamples.\n\n(** Note: in the rare cases where one needs to perform an inversion\n on an hypothesis [H] without clearing [H] from the context,\n one can use the tactic [inverts keep H], where the keyword [keep]\n indicates that the hypothesis should be kept in the context. *)\n\n\n\n\n(* ####################################################### *)\n(** * Tactics for n-ary connectives *)\n\n(** Because Coq encodes conjunctions and disjunctions using binary \n constructors [/\\] and [\\/], working with a conjunction or a\n disjunction of [N] facts can sometimes be quite cumbursome.\n For this reason, \"LibTactics\" provides tactics offering direct\n support for n-ary conjunctions and disjunctions. It also provides\n direct support for n-ary existententials. *)\n\n(** This section presents the following tactics:\n - [splits] for decomposing n-ary conjunctions,\n - [branch] for decomposing n-ary disjunctions,\n - [exists] for proving n-ary existentials. *)\n \nModule NaryExamples.\n Require Import References SfLib. \n Import STLCRef.\n\n\n(* ####################################################### *)\n(** ** The tactic [splits] *)\n\n(** The tactic [splits] applies to a goal made of a conjunction \n of [n] propositions and it produces [n] subgoals. For example,\n it decomposes the goal [G1 /\\ G2 /\\ G3] into the three subgoals\n [G1], [G2] and [G3]. *)\n\nLemma demo_splits : forall n m,\n n > 0 /\\ n < m /\\ m < n+10 /\\ m <> 3.\nProof.\n intros. splits.\nAbort.\n\n\n(* ####################################################### *)\n(** ** The tactic [branch] *)\n\n(** The tactic [branch k] can be used to prove a n-ary disjunction.\n For example, if the goal takes the form [G1 \\/ G2 \\/ G3],\n the tactic [branch 2] leaves only [G2] as subgoal. The following\n example illustrates the behavior of the [branch] tactic. *)\n\nLemma demo_branch : forall n m,\n n < m \\/ n = m \\/ m < n.\nProof.\n intros.\n destruct (lt_eq_lt_dec n m) as [[H1|H2]|H3].\n branch 1. apply H1.\n branch 2. apply H2.\n branch 3. apply H3.\nQed.\n\n\n(* ####################################################### *)\n(** ** The tactic [exists] *)\n\n(** The library \"LibTactics\" introduces a notation for n-ary\n existentials. For example, one can write [exists x y z, H]\n instead of [exists x, exists y, exists z, H]. Similarly,\n the library provides a n-ary tactic [exists a b c], which is a\n shorthand for [exists a; exists b; exists c]. The following\n example illustrates both the notation and the tactic for\n dealing with n-ary existentials. *)\n\nTheorem progress : forall ST t T st,\n has_type empty ST t T ->\n store_well_typed ST st ->\n value t \\/ exists t' st', t / st ==> t' / st'.\n (* was: [value t \\/ exists t', exists st', t / st ==> t' / st'] *)\nProof with eauto.\n intros ST t T st Ht HST. remember (@empty ty) as Gamma.\n (has_type_cases (induction Ht) Case); subst; try solve by inversion...\n Case \"T_App\".\n right. destruct IHHt1 as [Ht1p | Ht1p]...\n SCase \"t1 is a value\".\n inversion Ht1p; subst; try solve by inversion.\n destruct IHHt2 as [Ht2p | Ht2p]...\n SSCase \"t2 steps\".\n inversion Ht2p as [t2' [st' Hstep]].\n exists (tapp (tabs x T t) t2') st'...\n (* was: [exists (tapp (tabs x T t) t2'). exists st'...] *)\nAbort.\n\n(** Remark: a similar facility for n-ary existentials is provided\n by the module [Coq.Program.Syntax] from the standard library.\n ([Coq.Program.Syntax] supports existentials up to arity 4;\n [LibTactics] supports them up to arity 10. *)\n\nEnd NaryExamples.\n\n\n(* ####################################################### *)\n(** * Tactics for working with equality *)\n\n(** One of the major weakness of Coq compared with other interactive\n proof assistants is its relatively poor support for reasoning\n with equalities. The tactics described next aims at simplifying\n pieces of proof scripts manipulating equalities. *)\n\n(** This section presents the following tactics:\n - [asserts_rewrite] for introducing an equality to rewrite with,\n - [cuts_rewrite], which is similar except that its subgoals are swapped,\n - [substs] for improving the [subst] tactic,\n - [fequals] for improving the [f_equal] tactic,\n - [applys_eq] for proving [P x y] using an hypothesis [P x z],\n automatically producing an equality [y = z] as subgoal. *)\n\nModule EqualityExamples.\n\n\n(* ####################################################### *)\n(** ** The tactics [asserts_rewrite] and [cuts_rewrite] *)\n\n(** The tactic [asserts_rewrite (E1 = E2)] replaces [E1] with [E2] in\n the goal, and produces the goal [E1 = E2]. *)\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n dup.\n (* The old proof: *)\n intros n m.\n assert (H: 0 + n = n). reflexivity. rewrite -> H. \n reflexivity.\n \n (* The new proof: *)\n intros n m.\n asserts_rewrite (0 + n = n).\n reflexivity. (* subgoal [0+n = n] *)\n reflexivity. (* subgoal [n*m = m*n] *)\nQed.\n\n(*** Remark: the syntax [asserts_rewrite (E1 = E2) in H] allows\n rewriting in the hypothesis [H] rather than in the goal. *)\n\n(** The tactic [cuts_rewrite (E1 = E2)] is like\n [asserts_rewrite (E1 = E2)], except that the equality [E1 = E2]\n appears as first subgoal. *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n cuts_rewrite (0 + n = n).\n reflexivity. (* subgoal [n*m = m*n] *)\n reflexivity. (* subgoal [0+n = n] *)\nQed.\n\n(** More generally, the tactics [asserts_rewrite] and [cuts_rewrite] \n can be provided a lemma as argument. For example, one can write \n [asserts_rewrite (forall a b, a*(S b) = a*b+a)]. \n This formulation is useful when [a] and [b] are big terms,\n since there is no need to repeat their statements. *)\n\nTheorem mult_0_plus'' : forall u v w x y z: nat,\n (u + v) * (S (w * x + y)) = z.\nProof.\n intros. asserts_rewrite (forall a b, a*(S b) = a*b+a).\n (* first subgoal: [forall a b, a*(S b) = a*b+a] *)\n (* second subgoal: [(u + v) * (w * x + y) + (u + v) = z] *)\nAbort.\n\n\n(* ####################################################### *)\n(** ** The tactic [substs] *)\n\n(** The tactic [substs] is similar to [subst] except that it\n does not fail when the goal contains \"circular equalities\",\n such as [x = f x]. *)\n\nLemma demo_substs : forall x y (f:nat->nat), \n x = f x -> y = x -> y = f x.\nProof.\n intros. substs. (* the tactic [subst] would fail here *) \n assumption.\nQed.\n\n\n(* ####################################################### *)\n(** ** The tactic [fequals] *)\n\n(** The tactic [fequals] is similar to [f_equal] except that it \n directly discharges all the trivial subgoals produced. Moreover, \n the tactic [fequals] features an enhanced treatment of equalities\n between tuples. *)\n\nLemma demo_fequals : forall (a b c d e : nat) (f : nat->nat->nat->nat->nat),\n a = 1 -> b = e -> e = 2 -> \n f a b c d = f 1 2 c 4.\nProof.\n intros. fequals. \n (* subgoals [a = 1], [b = 2] and [c = c] are proved, [d = 4] remains *)\nAbort.\n\n\n(* ####################################################### *)\n(** ** The tactic [applys_eq] *)\n\n(** The tactic [applys_eq] is a variant of [eapply] that introduces\n equalities for subterms that do not unify. For example, assume\n the goal is the proposition [P x y] and assume we have the\n assumption [H] asserting that [P x z] holds. We know that we can \n prove [y] to be equal to [z]. So, we could call the tactic\n [assert_rewrite (y = z)] and change the goal to [P x z], but\n this would require copy-pasting the values of [y] and [z].\n With the tactic [applys_eq], we can call [applys_eq H 1], which\n proves the goal and leaves only the subgoal [y = z]. The value [1]\n given as argument to [applys_eq] indicates that we want an equality\n to be introduced for the first argument of [P x y] counting from\n the right. The three following examples illustrate the behavior\n of a call to [applys_eq H 1], a call to [applys_eq H 2], and a\n call to [applys_eq H 1 2]. *)\n\nAxiom big_expression_using : nat->nat. (* Used in the example *)\n \nLemma demo_applys_eq_1 : forall (P:nat->nat->Prop) x y z, \n P x (big_expression_using z) -> \n P x (big_expression_using y).\nProof.\n introv H. dup.\n\n (* The old proof: *)\n assert (Eq: big_expression_using y = big_expression_using z).\n admit. (* Assume we can prove this equality somehow. *)\n rewrite Eq. apply H.\n\n (* The new proof: *)\n applys_eq H 1.\n admit. (* Assume we can prove this equality somehow. *)\nQed.\n\n(** If the mismatch was on the first argument of [P] instead of\n the second, we would have written [applys_eq H 2]. Recall\n that the occurences are counted from the right. *)\n\nLemma demo_applys_eq_2 : forall (P:nat->nat->Prop) x y z, \n P (big_expression_using z) x -> \n P (big_expression_using y) x.\nProof.\n introv H. applys_eq H 2.\nAbort.\n\n(** When we have a mismatch on two arguments, we want to produce\n two equalities. To achieve this, we may call [applys_eq H 1 2].\n More generally, the tactic [applys_eq] expects a lemma and a\n sequence of natural numbers as arguments. *)\n\nLemma demo_applys_eq_3 : forall (P:nat->nat->Prop) x1 x2 y1 y2, \n P (big_expression_using x2) (big_expression_using y2) -> \n P (big_expression_using x1) (big_expression_using y1).\nProof.\n introv H. applys_eq H 1 2.\n (* produces two subgoals:\n [big_expression_using x1 = big_expression_using x2]\n [big_expression_using y1 = big_expression_using y2] *)\nAbort.\n\nEnd EqualityExamples.\n\n\n(* ####################################################### *)\n(** * Some convenient shorthands *)\n\n(** This section of the tutorial introduces a few tactics \n that help make proof scripts shorter and more readable:\n - [unfolds] (without argument) for unfolding the head definition,\n - [false] for replacing the goal with [False],\n - [gen] as a shorthand for [dependent generalize],\n - [skip] for skipping a subgoal even if it contains existential variables,\n - [sort] for re-ordering the proof context by moving moving all\n propositions at the bottom. *)\n\n\n(* ####################################################### *)\n(** ** The tactic [unfolds] *)\n\nModule UnfoldsExample.\n Require Import Hoare.\n\n(** The tactic [unfolds] (without any argument) unfolds the\n head constant of the goal. This tactic saves the need to \n name the constant explicitly. *)\n\nLemma bexp_eval_true : forall b st,\n beval st b = true -> (bassn b) st.\nProof.\n intros b st Hbe. dup.\n\n (* The old proof: *)\n unfold bassn. assumption.\n\n (* The new proof: *)\n unfolds. assumption. \nQed.\n\n(** Remark: contrary to the tactic [hnf], which may unfold several\n constants, [unfolds] performs only a single step of unfolding. *)\n\n(** Remark: the tactic [unfolds in H] can be used to unfold the \n head definition of the hypothesis [H]. *)\n\nEnd UnfoldsExample.\n\n\n(* ####################################################### *)\n(** ** The tactics [false] and [tryfalse] *)\n\n(** The tactic [false] can be used to replace any goal with [False].\n In short, it is a shorthand for [apply ex_falso_quodlibet]. \n Moreover, [false] proves the goal if it contains an absurd \n assumption, such as [False] or [0 = S n], or if it contains\n contradictory assumptions, such as [x = true] and [x = false]. *)\n\nLemma demo_false : \n forall n, S n = 1 -> n = 0.\nProof.\n intros. destruct n. reflexivity. false.\nQed.\n\n(** The tactic [false] can be given an argument: [false H] replace\n the goals with [False] and then applies [H]. *)\n\nLemma demo_false_arg : \n (forall n, n < 0 -> False) -> (3 < 0) -> 4 < 0.\nProof.\n intros H L. false H. apply L.\nQed.\n\n(** The tactic [tryfalse] is a shorthand for [try solve [false]]:\n it tries to find a contradiction in the goal. The tactic\n [tryfalse] is generally called after a case analysis. *)\n\nLemma demo_tryfalse : \n forall n, S n = 1 -> n = 0.\nProof.\n intros. destruct n; tryfalse. reflexivity.\nQed.\n\n\n(* ####################################################### *)\n(** ** The tactic [gen] *)\n\n(** The tactic [gen] is a shortand for [generalize dependent]\n that accepts several arguments at once. An invokation of \n this tactic takes the form [gen x y z]. *)\n\nModule GenExample.\n Require Import Stlc.\n Import STLC.\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (extend Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma ([x:=v]t) S.\nProof.\n dup.\n\n (* The old proof: *)\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n induction t; intros; simpl.\n admit. admit. admit. admit. admit. admit.\n\n (* The new proof: *)\n introv Htypt Htypv. gen S Gamma. \n induction t; intros; simpl.\n admit. admit. admit. admit. admit. admit.\nQed.\n\nEnd GenExample.\n\n\n(* ####################################################### *)\n(** ** The tactics [skip], [skip_rewrite] and [skip_goal] *)\n\n(** Temporarily admitting a given subgoal is very useful when\n constructing proofs. It gives the ability to focus first \n on the most interesting cases of a proof. The tactic [skip]\n is like [admit] except that it also works when the proof \n includes existential variables. Recall that existential \n variables are those whose name starts with a question mark, \n e.g. [?24], and which are typically introduced by [eapply]. *)\n\nModule SkipExample.\n Require Import Stlc.\n Import STLC.\n\nExample astep_example1 : \n (APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state ==>a* (ANum 15).\nProof.\n eapply multi_step. skip. (* the tactic [admit] would not work here *)\n eapply multi_step. skip. skip.\n (* Note that because some unification variables have\n not been instantiated, we still need to write\n [Abort] instead of [Qed] at the end of the proof. *)\nAbort.\n\n(** The tactic [skip H: P] adds the hypothesis [H: P] to the context, \n without checking whether the proposition [P] is true. \n It is useful for exploiting a fact and postponing its proof. \n Note: [skip H: P] is simply a shorthand for [assert (H:P). skip.] *)\n\nTheorem demo_skipH : True.\nProof.\n skip H: (forall n m : nat, (0 + n) * m = n * m).\nAbort.\n\n(** The tactic [skip_rewrite (E1 = E2)] replaces [E1] with [E2] in\n the goal, without checking that [E1] is actually equal to [E2]. *)\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n dup.\n\n (* The old proof: *)\n intros n m.\n assert (H: 0 + n = n). skip. rewrite -> H. \n reflexivity.\n\n (* The new proof: *)\n intros n m.\n skip_rewrite (0 + n = n).\n reflexivity.\nQed.\n\n(** Remark: the tactic [skip_rewrite] can in fact be given a lemma\n statement as argument, in the same way as [asserts_rewrite]. *)\n\n(** The tactic [skip_goal] adds the current goal as hypothesis.\n This cheat is useful to set up the structure of a proof by\n induction without having to worry about the induction hypothesis \n being applied only to smaller arguments. Using [skip_goal], one\n can construct a proof in two steps: first, check that the main\n arguments go through without waisting time on fixing the details\n of the induction hypotheses; then, focus on fixing the invokations\n of the induction hypothesis. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n (* The tactic [skip_goal] creates an hypothesis called [IH] \n asserting that the statment of [ceval_deterministic] is true. *)\n skip_goal.\n (* Of course, if we call [assumption] here, then the goal is solved\n right away, but the point is to do the proof and use [IH]\n only at the places where we need an induction hypothesis. *)\n introv E1 E2. gen st2.\n (ceval_cases (induction E1) Case); introv E2; inverts E2 as.\n Case \"E_Skip\". reflexivity.\n Case \"E_Ass\". \n subst n. \n reflexivity.\n Case \"E_Seq\". \n intros st3 Red1 Red2.\n assert (st' = st3) as EQ1.\n SCase \"Proof of assertion\". \n (* was: [apply IHE1_1; assumption.] *)\n (* new: *) eapply IH. eapply E1_1. eapply Red1.\n subst st3.\n (* was: apply IHE1_2. assumption.] *)\n (* new: *) eapply IH. eapply E1_2. eapply Red2.\n (* The other cases are similiar. *)\nAbort.\n\nEnd SkipExample.\n\n\n(* ####################################################### *)\n(** ** The tactic [sort] *)\n\nModule SortExamples.\n Require Import Imp.\n\n(** The tactic [sort] reorganizes the proof context by placing\n all the variables at the top and all the hypotheses at the\n bottom, thereby making the proof context more readable. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n intros c st st1 st2 E1 E2.\n generalize dependent st2.\n (ceval_cases (induction E1) Case); intros st2 E2; inverts E2.\n admit. admit. (* Skipping some trivial cases *)\n sort. (* Observe how the context is reorganized *)\nAbort.\n\nEnd SortExamples.\n\n\n(* ####################################################### *)\n(** * Tactics for advanced lemma instantiation *)\n\n(** This last section describes a mechanism for instantiating a lemma \n by providing some of its arguments and leaving other implicit. \n Variables whose instantiation is not provided are turned into \n existentential variables, and facts whose instantiation is not \n provided are turned into subgoals. \n \n Remark: this instantion mechanism goes far beyond the abilities of \n the \"Implicit Arguments\" mechanism. The point of the instantiation \n mechanism described in this section is that you will no longer need \n to spend time figuring out how many underscore symbols you need to \n write. *)\n\n(** In this section, we'll use a useful feature of Coq for decomposing\n conjunctions and existentials. In short, a tactic like [intros] or\n [destruct] can be provided with a pattern [(H1 & H2 & H3 & H4 & H5)],\n which is a shorthand for [[H1 [H2 [H3 [H4 H5]]]]]]. For example,\n [destruct (H _ _ _ Htypt) as [T [Hctx Hsub]].] can be rewritten in\n the form [destruct (H _ _ _ Htypt) as (T & Hctx & Hsub).] *)\n\n\n(* ####################################################### *)\n(** ** Working of [lets] *)\n\n(** When we have a lemma (or an assumption) that we want to exploit,\n we often need to explicitly provide arguments to this lemma,\n writing something like:\n [destruct (typing_inversion_var _ _ _ Htypt) as (T & Hctx & Hsub).]\n The need to write several times the \"underscore\" symbol is tedious.\n Not only we need to figure out how many of them to write down, but\n it also makes the proof scripts look prettly ugly. With the tactic\n [lets], one can simply write:\n [lets (T & Hctx & Hsub): typing_inversion_var Htypt.]\n \n In short, this tactic [lets] allows to specialize a lemma on a bunch \n of variables and hypotheses. The syntax is [lets I: E0 E1 .. EN], \n for building an hypothesis named [I] by applying the fact [E0] to the \n arguments [E1] to [EN]. Not all the arguments need to be provided,\n however the arguments that are provided need to be provided in the\n correct order. The tactic relies on a first-match algorithm based on \n types in order to figure out how the to instantiate the lemma with\n the arguments provided. *)\n\nModule ExamplesLets.\n Require Import Sub.\n\n(* To illustrate the working of [lets], assume that we want to\n exploit the following lemma. *)\n\nAxiom typing_inversion_var : forall (G:context) (x:id) (T:ty),\n has_type G (tvar x) T ->\n exists S, G x = Some S /\\ subtype S T.\n\n(** First, assume we have an assumption [H] with the type of the form\n [has_type G (tvar x) T]. We can obtain the conclusion of the\n lemma [typing_inversion_var] by invoking the tactics \n [lets K: typing_inversion_var H], as shown next. *)\n\nLemma demo_lets_1 : forall (G:context) (x:id) (T:ty), \n has_type G (tvar x) T -> True.\nProof.\n intros G x T H. dup. \n\n (* step-by-step: *)\n lets K: typing_inversion_var H.\n destruct K as (S & Eq & Sub). \n admit.\n\n (* all-at-once: *)\n lets (S & Eq & Sub): typing_inversion_var H.\n admit.\n\nQed.\n\n(** Assume now that we know the values of [G], [x] and [T] and we\n want to obtain [S], and have [has_type G (tvar x) T] be produced\n as a subgoal. To indicate that we want all the remaining arguments\n of [typing_inversion_var] to be produced as subgoals, we use a\n triple-underscore symbol [___]. (We'll later introduce a shorthand\n tactic called [forwards] to avoid writing triple underscores.) *)\n\nLemma demo_lets_2 : forall (G:context) (x:id) (T:ty), True.\nProof.\n intros G x T. \n lets (S & Eq & Sub): typing_inversion_var G x T ___.\nAbort.\n\n(** Usually, there is only one context [G] and one type [T] that are\n going to be suitable for proving [has_type G (tvar x) T], so\n we don't really need to bother giving [G] and [T] explicitly.\n It suffices to call [lets (S & Eq & Sub): typing_inversion_var x].\n The variables [G] and [T] are then instantiated using existential \n variables. *)\n\nLemma demo_lets_3 : forall (x:id), True.\nProof.\n intros x. \n lets (S & Eq & Sub): typing_inversion_var x ___.\nAbort.\n\n(** We may go even further by not giving any argument to instantiate\n [typing_inversion_var]. In this case, three unification variables\n are introduced. *)\n\nLemma demo_lets_4 : True.\nProof.\n lets (S & Eq & Sub): typing_inversion_var ___.\nAbort.\n\n(** Note: if we provide [lets] with only the name of the lemma as \n argument, it simply adds this lemma in the proof context, without \n trying to instantiate any of its arguments. *)\n\nLemma demo_lets_5 : True.\nProof.\n lets H: typing_inversion_var.\nAbort.\n\n(** A last useful feature of [lets] is the double-underscore symbol,\n which allows skipping an argument when several arguments have\n the same type. In the following example, our assumption quantifies\n over two variables [n] and [m], both of type [nat]. We would like\n [m] to be instantiated as the value [3], but without specifying a\n value for [n]. This can be achieved by writting [lets K: H __ 3]. *)\n\nLemma demo_lets_underscore : \n (forall n m, n <= m -> n < m+1) -> True.\nProof.\n intros H.\n\n (* If we do not use a double underscore, the first argument,\n which is [n], gets instantiated as 3. *)\n lets K: H 3. (* gives [K] of type [forall m, 3 <= m -> 3 < m+1] *)\n clear K.\n\n (* The double underscore preceeding [3] indicates that we want \n to skip a value that has the type [nat] (because [3] has \n the type [nat]). So, the variable [m] gets instiated as [3]. *)\n lets K: H __ 3. (* gives [K] of type [?X <= 3 -> ?X < 3+1] *)\n clear K.\nAbort.\n\n\n(** Note: one can write [lets: E0 E1 E2] in place of [lets H: E0 E1 E2].\n In this case, the name [H] is chosen arbitrarily.\n\n Note: the tactics [lets] accepts up to five arguments. Another\n syntax is available for providing more than five arguments.\n It consists in using a list introduced with the special symbol [>>],\n for example [lets H: (>> E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 10)]. *)\n\nEnd ExamplesLets.\n\n\n(* ####################################################### *)\n(** ** Working of [applys], [forwards] and [specializes] *)\n\n(** The tactics [applys], [forwards] and [specializes] are \n shorthand that may be used in place of [lets] to perform\n specific tasks.\n\n - [forwards] is a shorthand for instantiating all the arguments\n of a lemma. More precisely, [forwards H: E0 E1 E2 E3] is the \n same as [lets H: E0 E1 E2 E3 ___], where the triple-underscore \n has the same meaning as explained earlier on. \n\n - [applys] allows building a lemma using the advanced instantion\n mode of [lets], and then apply that lemma right away. So,\n [applys E0 E1 E2 E3] is the same as [lets H: E0 E1 E2 E3]\n followed with [eapply H] and then [clear H]. \n \n - [specializes] is a shorthand for instantiating in-place \n an assumption from the context with particular arguments.\n More precisely, [specializes H E0 E1] is the same as \n [lets H': H E0 E1] followed with [clear H] and [rename H' into H].\n\n Examples of use of [applys] appear further on. Several examples of\n use of [forwards] can be found in the tutorial chapter [UseAuto]. *)\n\n\n(* ####################################################### *)\n(** ** Example of instantiations *)\n\nModule ExamplesInstantiations.\n Require Import Sub.\n\n(** The following proof shows several examples where [lets] is used\n instead of [destruct], as well as examples where [applys] is used\n instead of [apply]. The proof also contains some holes that you\n need to fill in as an exercise. *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (extend Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma ([x:=v]t) S.\nProof with eauto.\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n (t_cases (induction t) Case); intros; simpl.\n Case \"tvar\".\n rename i into y.\n\n (* An example where [destruct] is replaced with [lets]. *)\n (* old: destruct (typing_inversion_var _ _ _ Htypt) as [T [Hctx Hsub]].*)\n (* new: *) lets (T&Hctx&Hsub): typing_inversion_var Htypt.\n unfold extend in Hctx.\n destruct (eq_id_dec x y)...\n SCase \"x=y\".\n subst.\n inversion Hctx; subst. clear Hctx.\n apply context_invariance with empty...\n intros x Hcontra.\n\n (* A more involved example. *)\n (* old: destruct (free_in_context _ _ S empty Hcontra) \n as [T' HT']... *)\n (* new: *)\n lets [T' HT']: free_in_context S empty Hcontra...\n inversion HT'.\n Case \"tapp\".\n \n (* Exercise: replace the following [destruct] with a [lets]. *)\n (* old: destruct (typing_inversion_app _ _ _ _ Htypt) \n as [T1 [Htypt1 Htypt2]]. eapply T_App... *)\n (* FILL IN HERE *) admit.\n \n Case \"tabs\".\n rename i into y. rename t into T1.\n\n (* Here is another example of using [lets]. *)\n (* old: destruct (typing_inversion_abs _ _ _ _ _ Htypt). *)\n (* new: *) lets (T2&Hsub&Htypt2): typing_inversion_abs Htypt.\n\n (* An example of where [apply with] can be replaced with [applys]. *)\n (* old: apply T_Sub with (TArrow T1 T2)... *)\n (* new: *) applys T_Sub (TArrow T1 T2)...\n apply T_Abs...\n destruct (eq_id_dec x y).\n SCase \"x=y\".\n eapply context_invariance...\n subst. \n intros x Hafi. unfold extend.\n destruct (eq_id_dec y x)...\n SCase \"x<>y\".\n apply IHt. eapply context_invariance...\n intros z Hafi. unfold extend.\n destruct (eq_id_dec y z)...\n subst. rewrite neq_id...\n Case \"ttrue\".\n lets: typing_inversion_true Htypt...\n Case \"tfalse\".\n lets: typing_inversion_false Htypt...\n Case \"tif\".\n lets (Htyp1&Htyp2&Htyp3): typing_inversion_if Htypt...\n Case \"tunit\". \n (* An example where [assert] can be replaced with [lets]. *)\n (* old: assert (subtype TUnit S) \n by apply (typing_inversion_unit _ _ Htypt)... *)\n (* new: *) lets: typing_inversion_unit Htypt...\n\n \nQed.\n\nEnd ExamplesInstantiations.\n\n\n(* ####################################################### *)\n(** * Summary *)\n\n(** In this chapter we have presented a number of tactics that help make\n proof script more concise and more robust on change. \n \n - [introv] and [inverts] improve naming and inversions.\n\n - [false] and [tryfalse] help discarding absurd goals.\n \n - [unfolds] automatically calls [unfold] on the head definition.\n\n - [gen] helps setting up goals for induction.\n\n - [cases] and [cases_if] help with case analysis.\n \n - [splits], [branch] and [exists] to deal with n-ary constructs.\n\n - [asserts_rewrite], [cuts_rewrite], [substs] and [fequals] help\n working with equalities.\n \n - [lets], [forwards], [specializes] and [applys] provide means\n of very conveniently instantiating lemmas.\n \n - [applys_eq] can save the need to perform manual rewriting steps\n before being able to apply lemma.\n \n - [skip], [skip_rewrite] and [skip_goal] give the flexibility to\n choose which subgoals to try and discharge first.\n\n Making use of these tactics can boost one's productivity in Coq proofs.\n\n If you are interested in using [LibTactics.v] in your own developments, \n make sure you get the lastest version from:\n http://www.chargueraud.org/softs/tlc/ .\n\n*)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "elfi", "repo": "sf", "sha": "169c89f59bec1415ddf8d290a40c533d19f862d5", "save_path": "github-repos/coq/elfi-sf", "path": "github-repos/coq/elfi-sf/sf-169c89f59bec1415ddf8d290a40c533d19f862d5/orig_files/UseTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.16238004072020704, "lm_q1q2_score": 0.05661300907449739}} {"text": "(**\nThis file is part of the Coquelicot formalization of real\nanalysis in Coq: http://coquelicot.saclay.inria.fr/\n\nCopyright (C) 2011-2015 Sylvie Boldo\n#
#\nCopyright (C) 2011-2015 Catherine Lelay\n#
#\nCopyright (C) 2011-2017 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\nFrom Coq Require Import Reals Psatz ssreflect.\n\nRequire Import Rcomplements Rbar Markov Iter Lub.\n\n(** This file first describes [Filter]s that are predicates of type\n[(T -> Prop) -> Prop] used for limits and neighborhoods. Then the\nalgebraic hierarchy of the Coquelicot library is given: from the\n[AbelianGroup] to the [CompleteNormedModule]. Topologies on [R] and\n[R*R] are also given.\n\n #
# More documentation details can be found in #Coquelicot.html#. *)\n\nOpen Scope R_scope.\n\n(** * Filters *)\n\n(** ** Definitions *)\n\nClass Filter {T : Type} (F : (T -> Prop) -> Prop) := {\n filter_true : F (fun _ => True) ;\n filter_and : forall P Q : T -> Prop, F P -> F Q -> F (fun x => P x /\\ Q x) ;\n filter_imp : forall P Q : T -> Prop, (forall x, P x -> Q x) -> F P -> F Q\n}.\n\nGlobal Hint Mode Filter + + : typeclass_instances.\n\nClass ProperFilter' {T : Type} (F : (T -> Prop) -> Prop) := {\n filter_not_empty : not (F (fun _ => False)) ;\n filter_filter' :> Filter F\n}.\n\nClass ProperFilter {T : Type} (F : (T -> Prop) -> Prop) := {\n filter_ex : forall P, F P -> exists x, P x ;\n filter_filter :> Filter F\n}.\n\nGlobal Instance Proper_StrongProper :\n forall {T : Type} (F : (T -> Prop) -> Prop),\n ProperFilter F -> ProperFilter' F.\nProof.\nintros T F [H1 H2].\nconstructor.\nintros H.\nnow destruct (H1 _ H) as [x Hx].\nexact H2.\nQed.\n\nLemma filter_forall :\n forall {T : Type} {F} {FF: @Filter T F} (P : T -> Prop),\n (forall x, P x) -> F P.\nProof.\nintros T F FF P H.\napply filter_imp with (fun _ => True).\neasy.\napply filter_true.\nQed.\n\nLemma filter_const :\n forall {T : Type} {F} {FF: @ProperFilter T F} (P : Prop),\n F (fun _ => P) -> P.\nProof.\nintros T F FF P H.\ndestruct (filter_ex (fun _ => P) H) as [_ H'].\nexact H'.\nQed.\n\n(** ** Limits expressed with filters *)\n\nDefinition filter_le {T : Type} (F G : (T -> Prop) -> Prop) :=\n forall P, G P -> F P.\n\nLemma filter_le_refl :\n forall T F, @filter_le T F F.\nProof.\nnow intros T F P.\nQed.\n\nLemma filter_le_trans :\n forall T F G H, @filter_le T F G -> filter_le G H -> filter_le F H.\nProof.\nintros T F G H FG GH P K.\nnow apply FG, GH.\nQed.\n\nDefinition filtermap {T U : Type} (f : T -> U) (F : (T -> Prop) -> Prop) :=\n fun P => F (fun x => P (f x)).\n\nGlobal Instance filtermap_filter :\n forall T U (f : T -> U) (F : (T -> Prop) -> Prop),\n Filter F -> Filter (filtermap f F).\nProof.\nintros T U f F FF.\nunfold filtermap.\nconstructor.\n- apply filter_true.\n- intros P Q HP HQ.\n now apply filter_and.\n- intros P Q H HP.\n apply (filter_imp (fun x => P (f x))).\n intros x Hx.\n now apply H.\n exact HP.\nQed.\n\nGlobal Instance filtermap_proper_filter' :\n forall T U (f : T -> U) (F : (T -> Prop) -> Prop),\n ProperFilter' F -> ProperFilter' (filtermap f F).\nProof.\nintros T U f F FF.\nunfold filtermap.\nsplit.\n- apply filter_not_empty.\n- apply filtermap_filter.\n apply filter_filter'.\nQed.\n\nGlobal Instance filtermap_proper_filter :\n forall T U (f : T -> U) (F : (T -> Prop) -> Prop),\n ProperFilter F -> ProperFilter (filtermap f F).\nProof.\nintros T U f F FF.\nunfold filtermap.\nsplit.\n- intros P FP.\n destruct (filter_ex _ FP) as [x Hx].\n now exists (f x).\n- apply filtermap_filter.\n apply filter_filter.\nQed.\n\nDefinition filtermapi {T U : Type} (f : T -> U -> Prop) (F : (T -> Prop) -> Prop) :=\n fun P : U -> Prop => F (fun x => exists y, f x y /\\ P y).\n\nGlobal Instance filtermapi_filter :\n forall T U (f : T -> U -> Prop) (F : (T -> Prop) -> Prop),\n F (fun x => (exists y, f x y) /\\ forall y1 y2, f x y1 -> f x y2 -> y1 = y2) ->\n Filter F -> Filter (filtermapi f F).\nProof.\nintros T U f F H FF.\nunfold filtermapi.\nconstructor.\n- apply: filter_imp H => x [[y Hy] H].\n exists y.\n exact (conj Hy I).\n- intros P Q HP HQ.\n apply: filter_imp (filter_and _ _ (filter_and _ _ HP HQ) H).\n intros x [[[y1 [Hy1 Py]] [y2 [Hy2 Qy]]] [[y Hy] Hf]].\n exists y.\n apply (conj Hy).\n split.\n now rewrite (Hf y y1).\n now rewrite (Hf y y2).\n- intros P Q HPQ HP.\n apply: filter_imp HP.\n intros x [y [Hf Py]].\n exists y.\n apply (conj Hf).\n now apply HPQ.\nQed.\n\nGlobal Instance filtermapi_proper_filter' :\n forall T U (f : T -> U -> Prop) (F : (T -> Prop) -> Prop),\n F (fun x => (exists y, f x y) /\\ forall y1 y2, f x y1 -> f x y2 -> y1 = y2) ->\n ProperFilter' F -> ProperFilter' (filtermapi f F).\nProof.\nintros T U f F HF FF.\nunfold filtermapi.\nsplit.\n- intro H.\n apply filter_not_empty.\n apply filter_imp with (2 := H).\n now intros x [y [_ Hy]].\n- apply filtermapi_filter.\n exact HF.\n apply filter_filter'.\nQed.\n\nGlobal Instance filtermapi_proper_filter :\n forall T U (f : T -> U -> Prop) (F : (T -> Prop) -> Prop),\n F (fun x => (exists y, f x y) /\\ forall y1 y2, f x y1 -> f x y2 -> y1 = y2) ->\n ProperFilter F -> ProperFilter (filtermapi f F).\nProof.\nintros T U f F HF FF.\nunfold filtermapi.\nsplit.\n- intros P FP.\n destruct (filter_ex _ FP) as [x [y [_ Hy]]].\n now exists y.\n- apply filtermapi_filter.\n exact HF.\n apply filter_filter.\nQed.\n\nDefinition filterlim {T U : Type} (f : T -> U) F G :=\n filter_le (filtermap f F) G.\n\nLemma filterlim_id :\n forall T (F : (T -> Prop) -> Prop), filterlim (fun x => x) F F.\nProof.\nnow intros T F P HP.\nQed.\n\nLemma filterlim_comp :\n forall T U V (f : T -> U) (g : U -> V) F G H,\n filterlim f F G -> filterlim g G H ->\n filterlim (fun x => g (f x)) F H.\nProof.\nintros T U V f g F G H FG GH P HP.\napply (FG (fun x => P (g x))).\nnow apply GH.\nQed.\n\nLemma filterlim_ext_loc :\n forall {T U F G} {FF : Filter F} (f g : T -> U),\n F (fun x => f x = g x) ->\n filterlim f F G ->\n filterlim g F G.\nProof.\nintros T U F G FF f g Efg Lf P GP.\nspecialize (Lf P GP).\ngeneralize (filter_and _ (fun x : T => P (f x)) Efg Lf).\nunfold filtermap.\napply filter_imp.\nnow intros x [-> H].\nQed.\n\nLemma filterlim_ext :\n forall {T U F G} {FF : Filter F} (f g : T -> U),\n (forall x, f x = g x) ->\n filterlim f F G ->\n filterlim g F G.\nProof.\nintros T U F G FF f g Efg.\napply filterlim_ext_loc.\nnow apply filter_forall.\nQed.\n\nLemma filterlim_filter_le_1 :\n forall {T U F G H} (f : T -> U),\n filter_le G F ->\n filterlim f F H ->\n filterlim f G H.\nProof.\nintros T U F G H f K Hf P HP.\napply K.\nnow apply Hf.\nQed.\n\nLemma filterlim_filter_le_2 :\n forall {T U F G H} (f : T -> U),\n filter_le G H ->\n filterlim f F G ->\n filterlim f F H.\nProof.\nintros T U F G H f K Hf P HP.\napply Hf.\nnow apply K.\nQed.\n\nDefinition filterlimi {T U : Type} (f : T -> U -> Prop) F G :=\n filter_le (filtermapi f F) G.\n\nLemma filterlimi_comp :\n forall T U V (f : T -> U) (g : U -> V -> Prop) F G H,\n filterlim f F G -> filterlimi g G H ->\n filterlimi (fun x => g (f x)) F H.\nProof.\nintros T U V f g F G H FG GH P HP.\napply (FG (fun x => exists y, g x y /\\ P y)).\nnow apply GH.\nQed.\n\nLemma filterlimi_ext_loc :\n forall {T U F G} {FF : Filter F} (f g : T -> U -> Prop),\n F (fun x => forall y, f x y <-> g x y) ->\n filterlimi f F G ->\n filterlimi g F G.\nProof.\nintros T U F G FF f g Efg Lf P GP.\nspecialize (Lf P GP).\ngeneralize (filter_and _ _ Efg Lf).\nunfold filtermapi.\napply filter_imp.\nintros x [H [y [Hy1 Hy2]]].\nexists y.\napply: conj Hy2.\nnow apply H.\nQed.\n\nLemma filterlimi_ext :\n forall {T U F G} {FF : Filter F} (f g : T -> U -> Prop),\n (forall x y, f x y <-> g x y) ->\n filterlimi f F G ->\n filterlimi g F G.\nProof.\nintros T U F G FF f g Efg.\napply filterlimi_ext_loc.\nnow apply filter_forall.\nQed.\n\nLemma filterlimi_lim_ext_loc :\n forall {T U F G} {FF : Filter F} (f : T -> U) (g : T -> U -> Prop),\n F (fun x => g x (f x)) ->\n filterlim f F G ->\n filterlimi g F G.\nProof.\nintros T U F G FF f g HF Hf P HP.\ngeneralize (filter_and (fun x => g x (f x)) _ HF (Hf P HP)).\nunfold filtermapi.\napply: filter_imp.\nintros x [H1 H2].\nnow exists (f x).\nQed.\n\nLemma filterlimi_lim_ext :\n forall {T U F G} {FF : Filter F} (f : T -> U) (g : T -> U -> Prop),\n (forall x, g x (f x)) ->\n filterlim f F G ->\n filterlimi g F G.\nProof.\nintros T U F G FF f g HF.\napply filterlimi_lim_ext_loc.\nnow apply filter_forall.\nQed.\n\nLemma filterlimi_filter_le_1 :\n forall {T U F G H} (f : T -> U -> Prop),\n filter_le G F ->\n filterlimi f F H ->\n filterlimi f G H.\nProof.\nintros T U F G H f K Hf P HP.\napply K.\nnow apply Hf.\nQed.\n\nLemma filterlimi_filter_le_2 :\n forall {T U F G H} (f : T -> U -> Prop),\n filter_le G H ->\n filterlimi f F G ->\n filterlimi f F H.\nProof.\nintros T U F G H f K Hf P HP.\napply Hf.\nnow apply K.\nQed.\n\n(** ** Specific filters *)\n\n(** Filters for pairs *)\n\nInductive filter_prod {T U : Type} (F G : _ -> Prop) (P : T * U -> Prop) : Prop :=\n Filter_prod (Q : T -> Prop) (R : U -> Prop) :\n F Q -> G R -> (forall x y, Q x -> R y -> P (x, y)) -> filter_prod F G P.\n\nGlobal Instance filter_prod_filter :\n forall T U (F : (T -> Prop) -> Prop) (G : (U -> Prop) -> Prop),\n Filter F -> Filter G -> Filter (filter_prod F G).\nProof.\nintros T U F G FF FG.\nconstructor.\n- exists (fun _ => True) (fun _ => True).\n apply filter_true.\n apply filter_true.\n easy.\n- intros P Q [AP BP P1 P2 P3] [AQ BQ Q1 Q2 Q3].\n exists (fun x => AP x /\\ AQ x) (fun x => BP x /\\ BQ x).\n now apply filter_and.\n now apply filter_and.\n intros x y [Px Qx] [Py Qy].\n split.\n now apply P3.\n now apply Q3.\n- intros P Q HI [AP BP P1 P2 P3].\n exists AP BP ; try easy.\n intros x y Hx Hy.\n apply HI.\n now apply P3.\nQed.\n\nGlobal Instance filter_prod_proper' {T1 T2 : Type}\n {F : (T1 -> Prop) -> Prop} {G : (T2 -> Prop) -> Prop}\n {FF : ProperFilter' F} {FG : ProperFilter' G} :\n ProperFilter' (filter_prod F G).\nProof.\n split.\n intros [Q R HQ HR HQR].\n apply FG.\n apply filter_imp with (2 := HR).\n intros y Hy.\n apply FF.\n apply filter_imp with (2 := HQ).\n intros x Hx.\n now apply (HQR x y).\n apply filter_prod_filter.\n apply FF.\n apply FG.\nQed.\n\nGlobal Instance filter_prod_proper {T1 T2 : Type}\n {F : (T1 -> Prop) -> Prop} {G : (T2 -> Prop) -> Prop}\n {FF : ProperFilter F} {FG : ProperFilter G} :\n ProperFilter (filter_prod F G).\nProof.\n split.\n intros P [Q1 Q2 H1 H2 HP].\n case: (filter_ex _ H1) => x1 Hx1.\n case: (filter_ex _ H2) => x2 Hx2.\n exists (x1,x2).\n by apply HP.\n apply filter_prod_filter.\n apply FF.\n apply FG.\nQed.\n\nLemma filterlim_fst :\n forall {T U F G} {FG : Filter G},\n filterlim (@fst T U) (filter_prod F G) F.\nProof.\nintros T U F G FG P HP.\nexists P (fun _ => True) ; try easy.\napply filter_true.\nQed.\n\nLemma filterlim_snd :\n forall {T U F G} {FF : Filter F},\n filterlim (@snd T U) (filter_prod F G) G.\nProof.\nintros T U F G FF P HP.\nexists (fun _ => True) P ; try easy.\napply filter_true.\nQed.\n\nLemma filterlim_pair :\n forall {T U V F G H} {FF : Filter F},\n forall (f : T -> U) (g : T -> V),\n filterlim f F G ->\n filterlim g F H ->\n filterlim (fun x => (f x, g x)) F (filter_prod G H).\nProof.\nintros T U V F G H FF f g Cf Cg P [A B GA HB HP].\nunfold filtermap.\napply (filter_imp (fun x => A (f x) /\\ B (g x))).\nintros x [Af Bg].\nnow apply HP.\napply filter_and.\nnow apply Cf.\nnow apply Cg.\nQed.\n\nLemma filterlim_comp_2 :\n forall {T U V W F G H I} {FF : Filter F},\n forall (f : T -> U) (g : T -> V) (h : U -> V -> W),\n filterlim f F G ->\n filterlim g F H ->\n filterlim (fun x => h (fst x) (snd x)) (filter_prod G H) I ->\n filterlim (fun x => h (f x) (g x)) F I.\nProof.\nintros T U V W F G H I FF f g h Cf Cg Ch.\nchange (fun x => h (f x) (g x)) with (fun x => h (fst (f x, g x)) (snd (f x, g x))).\napply: filterlim_comp Ch.\nnow apply filterlim_pair.\nQed.\n\nLemma filterlimi_comp_2 :\n forall {T U V W F G H I} {FF : Filter F},\n forall (f : T -> U) (g : T -> V) (h : U -> V -> W -> Prop),\n filterlim f F G ->\n filterlim g F H ->\n filterlimi (fun x => h (fst x) (snd x)) (filter_prod G H) I ->\n filterlimi (fun x => h (f x) (g x)) F I.\nProof.\nintros T U V W F G H I FF f g h Cf Cg Ch.\nchange (fun x => h (f x) (g x)) with (fun x => h (fst (f x, g x)) (snd (f x, g x))).\napply: filterlimi_comp Ch.\nnow apply filterlim_pair.\nQed.\n\nLemma prod_filtermap_le {T1 T2 U1 U2 F G} {FF : Filter F} {FG : Filter G}\n (f1 : T1 -> U1) (f2 : T2 -> U2) :\n filter_le (filter_prod (filtermap f1 F) (filtermap f2 G))\n (filtermap (fun x => (f1 (fst x), f2 (snd x))) (filter_prod F G)).\nProof.\nintros P [Q1 Q2 H1 H2 H].\nunfold filtermap.\nsplit with (fun y => exists x, Q1 x /\\ f1 x = y) (fun y => exists x, Q2 x /\\ f2 x = y).\n- apply: filter_imp H1.\n intros x Qx.\n now exists x.\n- apply: filter_imp H2.\n intros x Qx.\n now exists x.\nintros y1 y2 [x1 [Qx1 <-]] [x2 [Qx2 <-]].\nnow apply H.\nQed.\n\nLemma filtermap_prod_le {T1 T2 U1 U2 F G} {FF : Filter F} {FG : Filter G}\n (f1 : T1 -> U1) (f2 : T2 -> U2) :\n filter_le (filtermap (fun x => (f1 (fst x), f2 (snd x))) (filter_prod F G))\n (filter_prod (filtermap f1 F) (filtermap f2 G)).\nProof.\nintros P [Q1 Q2 H1 H2 H].\nunfold filtermap.\nsplit with (fun x => Q1 (f1 x)) (fun x => Q2 (f2 x)).\nnow apply: filter_imp H1.\nnow apply: filter_imp H2.\nintros x1 x2 Qx1 Qx2.\nnow apply H.\nQed.\n\nLemma filterlim_prod {E} {T} {U} {F : (T -> Prop) -> Prop} {FF : Filter F} (g : E -> U -> U -> Prop) (f : T -> U) :\n filterlim (fun x => (f (fst x), f (snd x))) (filter_prod F F) (fun P => exists e, forall u v, g e u v -> P (u, v)) <->\n (forall e, exists P, F P /\\ forall u v : T, P u -> P v -> g e (f u) (f v)).\nProof.\nsplit.\n- intros H e.\n destruct (H (fun '(u, v) => g e u v)) as [P Q HP HQ H'].\n now exists e.\n exists (fun x => P x /\\ Q x).\n split.\n now apply filter_and.\n intros u v Hu Hv.\n now apply H'.\n- intros H P [e He].\n destruct (H e) as [Q [H1 H2]].\n clear H.\n unfold filtermap.\n split with Q Q ; try easy.\n intros x y Hx Hy.\n now apply He, H2.\nQed.\n\n(** Restriction of a filter to a domain *)\n\nDefinition within {T : Type} D (F : (T -> Prop) -> Prop) (P : T -> Prop) :=\n F (fun x => D x -> P x).\n\nGlobal Instance within_filter :\n forall T D F, Filter F -> Filter (@within T D F).\nProof.\nintros T D F FF.\nunfold within.\nconstructor.\n- now apply filter_forall.\n- intros P Q WP WQ.\n apply filter_imp with (fun x => (D x -> P x) /\\ (D x -> Q x)).\n intros x [HP HQ] HD.\n split.\n now apply HP.\n now apply HQ.\n now apply filter_and.\n- intros P Q H FP.\n apply filter_imp with (fun x => (D x -> P x) /\\ (P x -> Q x)).\n intros x [H1 H2] HD.\n apply H2, H1, HD.\n apply filter_and.\n exact FP.\n now apply filter_forall.\nQed.\n\nLemma filter_le_within :\n forall {T} {F : (T -> Prop) -> Prop} {FF : Filter F} D,\n filter_le (within D F) F.\nProof.\nintros T F D P HP.\nunfold within.\nnow apply filter_imp.\nQed.\n\nLemma filterlim_within_ext :\n forall {T U F G} {FF : Filter F} D (f g : T -> U),\n (forall x, D x -> f x = g x) ->\n filterlim f (within D F) G ->\n filterlim g (within D F) G.\nProof.\nintros T U F G FF D f g Efg.\napply filterlim_ext_loc.\nunfold within.\nnow apply filter_forall.\nQed.\n\nDefinition subset_filter {T} (F : (T -> Prop) -> Prop) (dom : T -> Prop) (P : {x|dom x} -> Prop) : Prop :=\n F (fun x => forall H : dom x, P (exist _ x H)).\n\nGlobal Instance subset_filter_filter :\n forall T F (dom : T -> Prop),\n Filter F ->\n Filter (subset_filter F dom).\nProof.\nintros T F dom FF.\nconstructor ; unfold subset_filter.\n- now apply filter_imp with (2 := filter_true).\n- intros P Q HP HQ.\n generalize (filter_and _ _ HP HQ).\n apply filter_imp.\n intros x [H1 H2] H.\n now split.\n- intros P Q H.\n apply filter_imp.\n intros x H' H0.\n now apply H.\nQed.\n\nLemma subset_filter_proper' :\n forall {T F} {FF : Filter F} (dom : T -> Prop),\n (forall P, F P -> ~ ~ exists x, dom x /\\ P x) ->\n ProperFilter' (subset_filter F dom).\nProof.\nintros T F FF dom.\nconstructor.\n2: now apply subset_filter_filter.\nintro H1.\nunfold subset_filter in H1.\nspecialize (H (fun x : T => dom x -> False)).\napply H in H1.\napply H1.\nclear H ; clear H1.\nintro H2.\ndestruct H2 as (x, Hx).\ndestruct Hx as (Hx1, Hx2) ; now apply Hx2.\nQed.\n\nLemma subset_filter_proper :\n forall {T F} {FF : Filter F} (dom : T -> Prop),\n (forall P, F P -> exists x, dom x /\\ P x) ->\n ProperFilter (subset_filter F dom).\nProof.\nintros T F dom FF H.\nconstructor.\n- unfold subset_filter.\n intros P HP.\n destruct (H _ HP) as [x [H1 H2]].\n exists (exist _ x H1).\n now apply H2.\n- now apply subset_filter_filter.\nQed.\n\n(** * Algebraic spaces *)\n(** ** Abelian groups *)\n\nModule AbelianGroup.\n\nRecord mixin_of (G : Type) := Mixin {\n plus : G -> G -> G ;\n opp : G -> G ;\n zero : G ;\n ax1 : forall x y, plus x y = plus y x ;\n ax2 : forall x y z, plus x (plus y z) = plus (plus x y) z ;\n ax3 : forall x, plus x zero = x ;\n ax4 : forall x, plus x (opp x) = zero\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nSection ClassDef.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\nDefinition class (cT : type) := let: Pack _ c _ := cT return class_of cT in c.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion sort : type >-> Sortclass.\nNotation AbelianGroup := type.\n\nEnd Exports.\n\nEnd AbelianGroup.\n\nExport AbelianGroup.Exports.\n\n(** Arithmetic operations *)\n\nSection AbelianGroup1.\n\nContext {G : AbelianGroup}.\n\nDefinition zero := AbelianGroup.zero _ (AbelianGroup.class G).\nDefinition plus := AbelianGroup.plus _ (AbelianGroup.class G).\nDefinition opp := AbelianGroup.opp _ (AbelianGroup.class G).\nDefinition minus x y := (plus x (opp y)).\n\nLemma plus_comm :\n forall x y : G,\n plus x y = plus y x.\nProof.\napply AbelianGroup.ax1.\nQed.\n\nLemma plus_assoc :\n forall x y z : G,\n plus x (plus y z) = plus (plus x y) z.\nProof.\napply AbelianGroup.ax2.\nQed.\n\nLemma plus_zero_r :\n forall x : G,\n plus x zero = x.\nProof.\napply AbelianGroup.ax3.\nQed.\n\nLemma plus_opp_r :\n forall x : G,\n plus x (opp x) = zero.\nProof.\napply AbelianGroup.ax4.\nQed.\n\nLemma plus_zero_l :\n forall x : G,\n plus zero x = x.\nProof.\nintros x.\nnow rewrite plus_comm plus_zero_r.\nQed.\n\nLemma plus_opp_l :\n forall x : G,\n plus (opp x) x = zero.\nProof.\nintros x.\nrewrite plus_comm.\napply plus_opp_r.\nQed.\n\nLemma opp_zero :\n opp zero = zero.\nProof.\nrewrite <- (plus_zero_r (opp zero)).\napply plus_opp_l.\nQed.\n\nLemma minus_zero_r :\n forall x : G,\n minus x zero = x.\nProof.\nintros x.\nunfold minus.\nrewrite opp_zero.\napply plus_zero_r.\nQed.\n\nLemma minus_eq_zero (x : G) :\n minus x x = zero.\nProof.\n apply plus_opp_r.\nQed.\n\nLemma plus_reg_l :\n forall r x y : G,\n plus r x = plus r y -> x = y.\nProof.\nintros r x y H.\nrewrite -(plus_zero_l x) -(plus_opp_l r) -plus_assoc.\nrewrite H.\nnow rewrite plus_assoc plus_opp_l plus_zero_l.\nQed.\n\nLemma plus_reg_r :\n forall r x y : G,\n plus x r = plus y r -> x = y.\nProof.\nintros z x y.\nrewrite !(plus_comm _ z).\nby apply plus_reg_l.\nQed.\n\nLemma opp_opp :\n forall x : G,\n opp (opp x) = x.\nProof.\nintros x.\napply plus_reg_r with (opp x).\nrewrite plus_opp_r.\napply plus_opp_l.\nQed.\n\nLemma opp_plus :\n forall x y : G,\n opp (plus x y) = plus (opp x) (opp y).\nProof.\nintros x y.\napply plus_reg_r with (plus x y).\nrewrite plus_opp_l.\nrewrite plus_assoc.\nrewrite (plus_comm (opp x)).\nrewrite <- (plus_assoc (opp y)).\nrewrite plus_opp_l.\nrewrite plus_zero_r.\napply sym_eq, plus_opp_l.\nQed.\n\nLemma opp_minus (x y : G) :\n opp (minus x y) = minus y x.\nProof.\n rewrite /minus opp_plus opp_opp.\n by apply plus_comm.\nQed.\n\nLemma minus_trans (r x y : G) :\n minus x y = plus (minus x r) (minus r y).\nProof.\n rewrite /minus -!plus_assoc.\n apply f_equal.\n by rewrite plus_assoc plus_opp_l plus_zero_l.\nQed.\n\nEnd AbelianGroup1.\n\n(** Sum *)\n\nSection Sums.\n\nContext {G : AbelianGroup}.\n\nDefinition sum_n_m (a : nat -> G) n m :=\n iter_nat plus zero a n m.\nDefinition sum_n (a : nat -> G) n :=\n sum_n_m a O n.\n\nLemma sum_n_m_Chasles (a : nat -> G) (n m k : nat) :\n (n <= S m)%nat -> (m <= k)%nat\n -> sum_n_m a n k = plus (sum_n_m a n m) (sum_n_m a (S m) k).\nProof.\n intros Hnm Hmk.\n apply iter_nat_Chasles.\n by apply plus_zero_l.\n by apply plus_assoc.\n by [].\n by [].\nQed.\n\nLemma sum_n_n (a : nat -> G) (n : nat) :\n sum_n_m a n n = a n.\nProof.\n apply iter_nat_point.\n by apply plus_zero_r.\nQed.\n\nLemma sum_O (a : nat -> G) : sum_n a 0 = a O.\nProof.\n by apply sum_n_n.\nQed.\n\nLemma sum_n_Sm (a : nat -> G) (n m : nat) :\n (n <= S m)%nat -> sum_n_m a n (S m) = plus (sum_n_m a n m) (a (S m)).\nProof.\n intros Hnmk.\n rewrite (sum_n_m_Chasles _ _ m).\n by rewrite sum_n_n.\n by [].\n by apply le_n_Sn.\nQed.\n\nLemma sum_Sn_m (a : nat -> G) (n m : nat) :\n (n <= m)%nat -> sum_n_m a n m = plus (a n) (sum_n_m a (S n) m).\nProof.\n intros Hnmk.\n rewrite (sum_n_m_Chasles _ _ n).\n by rewrite sum_n_n.\n by apply le_n_Sn.\n by [].\nQed.\n\nLemma sum_n_m_S (a : nat -> G) (n m : nat) :\n sum_n_m (fun n => a (S n)) n m = sum_n_m a (S n) (S m).\nProof.\n apply iter_nat_S.\nQed.\n\nLemma sum_Sn (a : nat -> G) (n : nat) :\n sum_n a (S n) = plus (sum_n a n) (a (S n)).\nProof.\n apply sum_n_Sm.\n by apply le_O_n.\nQed.\n\nLemma sum_n_m_zero (a : nat -> G) (n m : nat) :\n (m < n)%nat -> sum_n_m a n m = zero.\nProof.\n intros Hnm.\n rewrite /sum_n_m.\n elim: n m a Hnm => [ | n IH] m a Hnm.\n by apply lt_n_O in Hnm.\n case: m Hnm => [|m] Hnm //.\n rewrite -iter_nat_S.\n apply IH.\n by apply lt_S_n.\nQed.\n\nLemma sum_n_m_const_zero (n m : nat) :\n sum_n_m (fun _ => zero) n m = zero.\nProof.\n rewrite /sum_n_m /iter_nat.\n elim: (seq.iota n (S m - n)) => //= h t ->.\n by apply plus_zero_l.\nQed.\n\nLemma sum_n_m_ext_loc (a b : nat -> G) (n m : nat) :\n (forall k, (n <= k <= m)%nat -> a k = b k) ->\n sum_n_m a n m = sum_n_m b n m.\nProof.\n intros.\n by apply iter_nat_ext_loc.\nQed.\nLemma sum_n_m_ext (a b : nat -> G) n m :\n (forall n, a n = b n) ->\n sum_n_m a n m = sum_n_m b n m.\nProof.\n intros H.\n by apply sum_n_m_ext_loc.\nQed.\n\nLemma sum_n_ext_loc :\n forall (a b : nat -> G) N,\n (forall n, (n <= N)%nat -> a n = b n) ->\n sum_n a N = sum_n b N.\nProof.\n intros a b N H.\n apply sum_n_m_ext_loc => k [ _ Hk].\n by apply H.\nQed.\n\nLemma sum_n_ext :\n forall (a b : nat -> G) N,\n (forall n, a n = b n) ->\n sum_n a N = sum_n b N.\nProof.\n intros a b N H.\n by apply sum_n_ext_loc.\nQed.\n\nLemma sum_n_m_plus :\n forall (u v : nat -> G) (n m : nat),\n sum_n_m (fun k => plus (u k) (v k)) n m = plus (sum_n_m u n m) (sum_n_m v n m).\nProof.\n intros u v n m.\n case: (le_dec n m) => Hnm.\n elim: m n u v Hnm => [ | m IH] ;\n case => [ | n] u v Hnm.\n by rewrite !sum_n_n.\n by apply le_Sn_O in Hnm.\n rewrite !sum_n_Sm ; try by apply le_O_n.\n rewrite IH.\n rewrite -2!plus_assoc.\n apply f_equal.\n rewrite plus_comm -plus_assoc.\n apply f_equal, plus_comm.\n by apply le_O_n.\n rewrite /sum_n_m -!iter_nat_S -!/(sum_n_m _ n m).\n apply IH.\n by apply le_S_n.\n apply not_le in Hnm.\n rewrite !sum_n_m_zero //.\n by rewrite plus_zero_l.\nQed.\n\nLemma sum_n_plus :\n forall (u v : nat -> G) (n : nat),\n sum_n (fun k => plus (u k) (v k)) n = plus (sum_n u n) (sum_n v n).\nProof.\n intros u v n.\n apply sum_n_m_plus.\nQed.\n\nLemma sum_n_switch :\n forall (u : nat -> nat -> G) (m n : nat),\n sum_n (fun i => sum_n (u i) n) m = sum_n (fun j => sum_n (fun i => u i j) m) n.\nProof.\n intros u.\n rewrite /sum_n.\n induction m ; simpl ; intros n.\n rewrite sum_n_n.\n apply iter_nat_ext_loc => k Hk.\n rewrite sum_n_n.\n by [].\n rewrite !sum_n_Sm.\n rewrite IHm ; clear IHm.\n rewrite -sum_n_m_plus.\n apply sum_n_m_ext_loc => k Hk.\n rewrite sum_n_Sm //.\n by apply le_O_n.\n by apply le_O_n.\nQed.\n\nLemma sum_n_m_sum_n (a:nat -> G) (n m : nat) :\n (n <= m)%nat -> sum_n_m a (S n) m = minus (sum_n a m) (sum_n a n).\nProof.\n intros Hnm.\n apply plus_reg_l with (sum_n a n).\n rewrite (plus_comm _ (minus _ _)) /minus -plus_assoc plus_opp_l plus_zero_r.\n rewrite /sum_n /sum_n_m.\n apply sym_eq, sum_n_m_Chasles.\n by apply le_O_n.\n by [].\nQed.\n\nEnd Sums.\n\n(** ** Noncommutative rings *)\n\nModule Ring.\n\nRecord mixin_of (K : AbelianGroup) := Mixin {\n mult : K -> K -> K ;\n one : K ;\n ax1 : forall x y z, mult x (mult y z) = mult (mult x y) z ;\n ax2 : forall x, mult x one = x ;\n ax3 : forall x, mult one x = x ;\n ax4 : forall x y z, mult (plus x y) z = plus (mult x z) (mult y z) ;\n ax5 : forall x y z, mult x (plus y z) = plus (mult x y) (mult x z)\n}.\n\nSection ClassDef.\n\nRecord class_of (K : Type) := Class {\n base : AbelianGroup.class_of K ;\n mixin : mixin_of (AbelianGroup.Pack _ base K)\n}.\nLocal Coercion base : class_of >-> AbelianGroup.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition AbelianGroup := AbelianGroup.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> AbelianGroup.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion AbelianGroup : type >-> AbelianGroup.type.\nCanonical AbelianGroup.\nNotation Ring := type.\n\nEnd Exports.\n\nEnd Ring.\n\nExport Ring.Exports.\n\n(** Arithmetic operations *)\n\nSection Ring1.\n\nContext {K : Ring}.\n\nDefinition mult : K -> K -> K := Ring.mult _ (Ring.class K).\nDefinition one : K := Ring.one _ (Ring.class K).\n\nLemma mult_assoc :\n forall x y z : K,\n mult x (mult y z) = mult (mult x y) z.\nProof.\napply Ring.ax1.\nQed.\n\nLemma mult_one_r :\n forall x : K,\n mult x one = x.\nProof.\napply Ring.ax2.\nQed.\n\nLemma mult_one_l :\n forall x : K,\n mult one x = x.\nProof.\napply Ring.ax3.\nQed.\n\nLemma mult_distr_r :\n forall x y z : K,\n mult (plus x y) z = plus (mult x z) (mult y z).\nProof.\napply Ring.ax4.\nQed.\n\nLemma mult_distr_l :\n forall x y z : K,\n mult x (plus y z) = plus (mult x y) (mult x z).\nProof.\napply Ring.ax5.\nQed.\n\nLemma mult_zero_r :\n forall x : K,\n mult x zero = zero.\nProof.\nintros x.\napply plus_reg_r with (mult x zero).\nrewrite <- mult_distr_l.\nrewrite plus_zero_r.\nnow rewrite plus_zero_l.\nQed.\n\nLemma mult_zero_l :\n forall x : K,\n mult zero x = zero.\nProof.\nintros x.\napply plus_reg_r with (mult zero x).\nrewrite <- mult_distr_r.\nrewrite plus_zero_r.\nnow rewrite plus_zero_l.\nQed.\n\nLemma opp_mult_r :\n forall x y : K,\n opp (mult x y) = mult x (opp y).\nProof.\nintros x y.\napply plus_reg_l with (mult x y).\nrewrite plus_opp_r -mult_distr_l.\nnow rewrite plus_opp_r mult_zero_r.\nQed.\n\nLemma opp_mult_l :\n forall x y : K,\n opp (mult x y) = mult (opp x) y.\nProof.\nintros x y.\napply plus_reg_l with (mult x y).\nrewrite plus_opp_r -mult_distr_r.\nnow rewrite plus_opp_r mult_zero_l.\nQed.\n\nLemma opp_mult_m1 :\n forall x : K,\n opp x = mult (opp one) x.\nProof.\n intros x.\n rewrite -opp_mult_l opp_mult_r.\n by rewrite mult_one_l.\nQed.\n\nLemma sum_n_m_mult_r :\n forall (a : K) (u : nat -> K) (n m : nat),\n sum_n_m (fun k => mult (u k) a) n m = mult (sum_n_m u n m) a.\nProof.\n intros a u n m.\n case: (le_dec n m) => Hnm.\n elim: m n u Hnm => [ | m IH] n u Hnm.\n apply le_n_O_eq in Hnm.\n by rewrite -Hnm !sum_n_n.\n destruct n.\n rewrite !sum_n_Sm ; try by apply le_O_n.\n rewrite IH.\n by apply sym_eq, mult_distr_r.\n by apply le_O_n.\n rewrite -!sum_n_m_S.\n apply IH.\n by apply le_S_n.\n apply not_le in Hnm.\n rewrite !sum_n_m_zero //.\n by rewrite mult_zero_l.\nQed.\n\nLemma sum_n_m_mult_l :\n forall (a : K) (u : nat -> K) (n m : nat),\n sum_n_m (fun k => mult a (u k)) n m = mult a (sum_n_m u n m).\nProof.\n intros a u n m.\n case: (le_dec n m) => Hnm.\n elim: m n u Hnm => [ | m IH] n u Hnm.\n apply le_n_O_eq in Hnm.\n by rewrite -Hnm !sum_n_n.\n destruct n.\n rewrite !sum_n_Sm ; try by apply le_O_n.\n rewrite IH.\n by apply sym_eq, mult_distr_l.\n by apply le_O_n.\n rewrite -!sum_n_m_S.\n apply IH.\n by apply le_S_n.\n apply not_le in Hnm.\n rewrite !sum_n_m_zero //.\n by rewrite mult_zero_r.\nQed.\n\nLemma sum_n_mult_r :\n forall (a : K) (u : nat -> K) (n : nat),\n sum_n (fun k => mult (u k) a) n = mult (sum_n u n) a.\nProof.\n intros ; by apply sum_n_m_mult_r.\nQed.\n\nLemma sum_n_mult_l :\n forall (a : K) (u : nat -> K) (n : nat),\n sum_n (fun k => mult a (u k)) n = mult a (sum_n u n).\nProof.\n intros ; by apply sum_n_m_mult_l.\nQed.\n\n(** pow_n *)\n\nFixpoint pow_n (x : K) (N : nat) {struct N} : K :=\n match N with\n | 0%nat => one\n | S i => mult x (pow_n x i)\n end.\n\nLemma pow_n_plus :\n forall (x : K) (n m : nat), pow_n x (n+m) = mult (pow_n x n) (pow_n x m).\nProof.\n intros x.\n elim => /= [ | n IH] m.\n by rewrite mult_one_l.\n by rewrite IH mult_assoc.\nQed.\n\nLemma pow_n_comm_1 :\n forall (x : K) (n : nat), mult (pow_n x n) x = mult x (pow_n x n).\nProof.\n intros x n.\n elim: n => /= [ | n IH].\n by rewrite mult_one_l mult_one_r.\n by rewrite -(mult_assoc _ (pow_n x n)) IH.\nQed.\n\nLemma pow_n_comm :\n forall (x : K) n m, mult (pow_n x n) (pow_n x m) = mult (pow_n x m) (pow_n x n).\nProof.\n intros x n m.\n rewrite -2!pow_n_plus.\n by apply f_equal, Plus.plus_comm.\nQed.\n\nEnd Ring1.\n\n(** ** Rings with absolute value *)\n\nModule AbsRing.\n\nRecord mixin_of (K : Ring) := Mixin {\n abs : K -> R ;\n ax1 : abs zero = 0 ;\n ax2 : abs (opp one) = 1 ;\n ax3 : forall x y : K, abs (plus x y) <= abs x + abs y ;\n ax4 : forall x y : K, abs (mult x y) <= abs x * abs y ;\n ax5 : forall x : K, abs x = 0 -> x = zero\n}.\n\nSection ClassDef.\n\nRecord class_of (K : Type) := Class {\n base : Ring.class_of K ;\n mixin : mixin_of (Ring.Pack _ base K)\n}.\nLocal Coercion base : class_of >-> Ring.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition AbelianGroup := AbelianGroup.Pack cT xclass xT.\nDefinition Ring := Ring.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> Ring.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion AbelianGroup : type >-> AbelianGroup.type.\nCanonical AbelianGroup.\nCoercion Ring : type >-> Ring.type.\nCanonical Ring.\nNotation AbsRing := type.\n\nEnd Exports.\n\nEnd AbsRing.\n\nExport AbsRing.Exports.\n\n(** Usual properties *)\n\nSection AbsRing1.\n\nContext {K : AbsRing}.\n\nDefinition abs : K -> R := AbsRing.abs _ (AbsRing.class K).\n\nLemma abs_zero :\n abs zero = 0.\nProof.\napply AbsRing.ax1.\nQed.\n\nLemma abs_opp_one :\n abs (opp one) = 1.\nProof.\napply AbsRing.ax2.\nQed.\n\nLemma abs_triangle :\n forall x y : K,\n abs (plus x y) <= abs x + abs y.\nProof.\napply: AbsRing.ax3.\nQed.\n\nLemma abs_mult :\n forall x y : K,\n abs (mult x y) <= abs x * abs y.\nProof.\napply AbsRing.ax4.\nQed.\n\nLemma abs_eq_zero :\n forall x : K,\n abs x = 0 -> x = zero.\nProof.\napply AbsRing.ax5.\nQed.\n\nLemma abs_opp :\n forall x, abs (opp x) = abs x.\nProof.\nintros x.\napply Rle_antisym.\n- rewrite opp_mult_m1.\n rewrite -(Rmult_1_l (abs x)) -abs_opp_one.\n apply abs_mult.\n- rewrite -{1}[x]opp_opp.\n rewrite opp_mult_m1.\n rewrite -(Rmult_1_l (abs (opp x))) -abs_opp_one.\n apply abs_mult.\nQed.\n\nLemma abs_minus :\n forall x y : K, abs (minus x y) = abs (minus y x).\nProof.\nintros x y.\nby rewrite /minus -abs_opp opp_plus opp_opp plus_comm.\nQed.\n\nLemma abs_one :\n abs one = 1.\nProof.\nrewrite -abs_opp.\nexact abs_opp_one.\nQed.\n\nLemma abs_ge_0 :\n forall x, 0 <= abs x.\nProof.\n intros x.\n apply Rmult_le_reg_l with 2.\n by apply Rlt_0_2.\n rewrite Rmult_0_r -abs_zero -(plus_opp_l x).\n apply Rle_trans with (1 := abs_triangle _ _).\n rewrite abs_opp.\n apply Req_le ; ring.\nQed.\n\nLemma abs_gt_0 :\n forall x : K,\n x <> zero -> 0 < abs x.\nProof.\nintros x Hx.\napply Rnot_le_lt.\ncontradict Hx.\napply abs_eq_zero.\napply Rle_antisym with (1 := Hx).\napply abs_ge_0.\nQed.\n\nLemma abs_minus_gt_0 :\n forall x y : K,\n x <> y -> 0 < abs (minus x y).\nProof.\nintros x y Hxy.\napply abs_gt_0.\ncontradict Hxy.\napply plus_reg_r with (opp y).\nnow rewrite plus_opp_r.\nQed.\n\nLemma abs_pow_n :\n forall (x : K) n,\n abs (pow_n x n) <= (abs x)^n.\nProof.\ninduction n.\napply Req_le, abs_one.\nsimpl.\napply: Rle_trans (abs_mult _ _) _.\napply Rmult_le_compat_l with (2 := IHn).\napply abs_ge_0.\nQed.\n\nEnd AbsRing1.\n\nModule TopologicalSpace.\n\nRecord mixin_of (M : Type) := Mixin {\n is_open : (M -> Prop) -> Prop;\n ax1 : is_open (fun _ => True);\n ax2 : is_open (fun _ => False);\n ax3 : forall {A: Type} (Us: A -> (M -> Prop)),\n (forall a, is_open (Us a)) -> is_open (fun m => exists a, Us a m);\n ax4 : forall (U1 U2: M -> Prop), is_open U1 -> is_open U2 -> is_open (fun m => U1 m \\/ U2 m)\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nEnd TopologicalSpace.\n\n(** * Uniform spaces defined using balls *)\n\nModule UniformSpace.\n\nRecord mixin_of (M : Type) := Mixin {\n point_of : M ;\n ball : M -> R -> M -> Prop ;\n ax1 : forall x (e : posreal), ball x e x ;\n ax2 : forall x y e, ball x e y -> ball y e x ;\n ax3 : forall x y z e1 e2, ball x e1 y -> ball y e2 z -> ball x (e1 + e2) z\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nSection ClassDef.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\nDefinition class (cT : type) := let: Pack _ c _ := cT return class_of cT in c.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion sort : type >-> Sortclass.\nNotation UniformSpace := type.\n\nEnd Exports.\n\nEnd UniformSpace.\n\nExport UniformSpace.Exports.\n\nSection UniformSpace1.\n\nContext {M : UniformSpace}.\n\nDefinition point_of := UniformSpace.point_of _ (UniformSpace.class M).\n\nDefinition ball := UniformSpace.ball _ (UniformSpace.class M).\n\nLemma ball_center :\n forall (x : M) (e : posreal),\n ball x e x.\nProof.\napply UniformSpace.ax1.\nQed.\n\nLemma ball_sym :\n forall (x y : M) (e : R),\n ball x e y -> ball y e x.\nProof.\napply UniformSpace.ax2.\nQed.\n\nLemma ball_triangle :\n forall (x y z : M) (e1 e2 : R),\n ball x e1 y -> ball y e2 z -> ball x (e1 + e2) z.\nProof.\napply UniformSpace.ax3.\nQed.\n\nLemma ball_le :\n forall (x : M) (e1 e2 : R), e1 <= e2 ->\n forall (y : M), ball x e1 y -> ball x e2 y.\nProof.\nintros x e1 e2 H y H1.\ndestruct H.\nassert (e2 - e1 > 0).\nby apply Rgt_minus.\nassert (ball y {| pos := (e2-e1); cond_pos := (H0) |} y).\napply ball_center.\nreplace e2 with (e1 + (e2 - e1)).\napply ball_triangle with y ; assumption.\nby apply Rplus_minus.\nby rewrite <- H.\nQed.\n\nDefinition close (x y : M) : Prop := forall eps : posreal, ball x eps y.\n\nLemma close_refl (x : M) : close x x.\nProof.\nintros eps.\napply ball_center.\nQed.\n\nLemma close_sym (x y : M) : close x y -> close y x.\nProof.\nintros H eps.\nnow apply ball_sym.\nQed.\n\nLemma close_trans (x y z : M) : close x y -> close y z -> close x z.\nProof.\nintros H1 H2 eps.\nrewrite (double_var eps) -[eps / 2]/(pos (pos_div_2 eps)).\nnow eapply ball_triangle.\nQed.\n\nEnd UniformSpace1.\n\n(** ** Specific uniform spaces *)\n\n(** Rings with absolute value *)\n\nSection AbsRing_UniformSpace.\n\nVariable K : AbsRing.\n\nDefinition AbsRing_ball (x : K) (eps : R) (y : K) := abs (minus y x) < eps.\n\nLemma AbsRing_ball_center :\n forall (x : K) (e : posreal),\n AbsRing_ball x e x.\nProof.\n intros x e.\n rewrite /AbsRing_ball /minus plus_opp_r abs_zero.\n apply cond_pos.\nQed.\n\nLemma AbsRing_ball_sym :\n forall (x y : K) (e : R),\n AbsRing_ball x e y -> AbsRing_ball y e x.\nProof.\n intros x y e.\n by rewrite /AbsRing_ball abs_minus.\nQed.\n\nLemma AbsRing_ball_triangle :\n forall (x y z : K) (e1 e2 : R),\n AbsRing_ball x e1 y -> AbsRing_ball y e2 z ->\n AbsRing_ball x (e1 + e2) z.\nProof.\nintros x y z e1 e2 H1 H2.\nunfold AbsRing_ball.\nreplace (minus z x) with (plus (minus y x) (minus z y)).\napply: Rle_lt_trans (abs_triangle _ _) _.\nnow apply Rplus_lt_compat.\nrewrite plus_comm /minus plus_assoc.\napply (f_equal (fun y => plus y _)).\nrewrite <- plus_assoc.\nnow rewrite plus_opp_l plus_zero_r.\nQed.\n\nDefinition AbsRing_UniformSpace_mixin :=\n UniformSpace.Mixin _ zero _ AbsRing_ball_center AbsRing_ball_sym AbsRing_ball_triangle.\n\nCanonical AbsRing_UniformSpace :=\n UniformSpace.Pack K AbsRing_UniformSpace_mixin K.\n\nEnd AbsRing_UniformSpace.\n\n(** Functional metric spaces *)\n\nSection fct_UniformSpace.\n\nVariable (T : Type) (U : UniformSpace).\n\nDefinition fct_ball (x : T -> U) (eps : R) (y : T -> U) :=\n forall t : T, ball (x t) eps (y t).\n\nLemma fct_ball_center :\n forall (x : T -> U) (e : posreal),\n fct_ball x e x.\nProof.\n intros x e t.\n exact: ball_center.\nQed.\n\nLemma fct_ball_sym :\n forall (x y : T -> U) (e : R),\n fct_ball x e y -> fct_ball y e x.\nProof.\n intros x y e H t.\n exact: ball_sym.\nQed.\n\nLemma fct_ball_triangle :\n forall (x y z : T -> U) (e1 e2 : R),\n fct_ball x e1 y -> fct_ball y e2 z -> fct_ball x (e1 + e2) z.\nProof.\n intros x y z e1 e2 H1 H2 t.\n now apply ball_triangle with (y t).\nQed.\n\n\nDefinition fct_UniformSpace_mixin :=\n UniformSpace.Mixin _ (fun _ => point_of) _ fct_ball_center fct_ball_sym fct_ball_triangle.\n\nCanonical fct_UniformSpace :=\n UniformSpace.Pack (T -> U) fct_UniformSpace_mixin (T -> U).\n\nEnd fct_UniformSpace.\n\n(** ** Local predicates *)\n(** locally_dist *)\n\nDefinition locally_dist {T : Type} (d : T -> R) (P : T -> Prop) :=\n exists delta : posreal, forall y, d y < delta -> P y.\n\nGlobal Instance locally_dist_filter :\n forall T (d : T -> R), Filter (locally_dist d).\nProof.\nintros T d.\nconstructor.\n- now exists (mkposreal _ Rlt_0_1).\n- intros P Q [dP HP] [dQ HQ].\n exists (mkposreal _ (Rmin_stable_in_posreal dP dQ)).\n simpl.\n intros y Hy.\n split.\n apply HP.\n apply Rlt_le_trans with (1 := Hy).\n apply Rmin_l.\n apply HQ.\n apply Rlt_le_trans with (1 := Hy).\n apply Rmin_r.\n- intros P Q H [dP HP].\n exists dP.\n intros y Hy.\n apply H.\n now apply HP.\nQed.\n\n(** locally *)\n\nSection Locally.\n\nContext {T : UniformSpace}.\n\nDefinition locally (x : T) (P : T -> Prop) :=\n exists eps : posreal, forall y, ball x eps y -> P y.\n\nGlobal Instance locally_filter :\n forall x : T, ProperFilter (locally x).\nProof.\nintros x.\nconstructor ; [idtac|constructor].\n- intros P [eps H].\n exists x.\n apply H.\n apply ball_center.\n- now exists (mkposreal _ Rlt_0_1).\n- intros P Q [dP HP] [dQ HQ].\n exists (mkposreal _ (Rmin_stable_in_posreal dP dQ)).\n simpl.\n intros y Hy.\n split.\n apply HP.\n apply ball_le with (2 := Hy).\n apply Rmin_l.\n apply HQ.\n apply ball_le with (2 := Hy).\n apply Rmin_r.\n- intros P Q H [dP HP].\n exists dP.\n intros y Hy.\n apply H.\n now apply HP.\nQed.\n\nLemma locally_locally :\n forall (x : T) (P : T -> Prop),\n locally x P -> locally x (fun y => locally y P).\nProof.\nintros x P [dp Hp].\nexists (pos_div_2 dp).\nintros y Hy.\nexists (pos_div_2 dp) => /= z Hz.\napply Hp.\nrewrite (double_var dp).\nnow apply ball_triangle with y.\nQed.\n\nLemma locally_singleton :\n forall (x : T) (P : T -> Prop),\n locally x P -> P x.\nProof.\nintros x P [dp H].\napply H.\nby apply ball_center.\nQed.\n\nLemma locally_ball :\n forall (x : T) (eps : posreal), locally x (ball x eps).\nProof.\n intros x eps.\n now exists eps.\nQed.\n\nLemma locally_not' :\n forall (x : T) (P : T -> Prop),\n not (forall eps : posreal, not (forall y, ball x eps y -> not (P y))) ->\n {d : posreal | forall y, ball x d y -> not (P y)}.\nProof.\nintros x P H.\nset (Q := fun z => z <= 1 /\\ forall y, ball x z y -> not (P y)).\ndestruct (completeness Q) as [d [H1 H2]].\n- exists 1.\n now intros y [Hy _].\n- exists 0.\n split.\n apply Rle_0_1.\n intros y Hy Py.\n apply H.\n intros eps He.\n apply He with (2 := Py).\n apply ball_le with (2 := Hy).\n apply Rlt_le, eps.\nassert (Zd : 0 < d).\n apply Rnot_le_lt.\n intros Hd.\n apply H.\n intros eps He.\n apply (Rlt_irrefl (Rmin 1 eps)).\n apply Rle_lt_trans with d.\n apply H1.\n split.\n apply Rmin_l.\n intros y By.\n apply He.\n apply ball_le with (2 := By).\n apply Rmin_r.\n apply Rle_lt_trans with (1 := Hd).\n apply Rmin_case.\n apply Rlt_0_1.\n apply cond_pos.\nexists (mkposreal _ (is_pos_div_2 (mkposreal _ Zd))).\nsimpl.\nintros y Hy HP.\napply (Rlt_not_le _ _ (Rlt_eps2_eps _ Zd)).\napply H2.\nintros z Hz.\napply Rnot_lt_le.\ncontradict HP.\napply Hz.\napply ball_le with (2 := Hy).\nnow apply Rlt_le.\nQed.\n\nLemma locally_not :\n forall (x : T) (P : T -> Prop),\n not (forall eps : posreal, not (forall y, ball x eps y -> not (P y))) ->\n locally x (fun y => not (P y)).\nProof.\nintros x P H.\ndestruct (locally_not' x P H) as [eps He].\nnow exists eps.\nQed.\n\nLemma locally_ex_not :\n forall (x : T) (P : T -> Prop),\n locally x (fun y => not (P y)) ->\n {d : posreal | forall y, ball x d y -> not (P y)}.\nProof.\nintros x P H.\napply locally_not'.\ndestruct H as [eps He].\nintros H.\nnow apply (H eps).\nQed.\n\nLemma locally_ex_dec :\n forall (x : T) (P : T -> Prop),\n (forall x, P x \\/ ~P x) ->\n locally x P ->\n {d : posreal | forall y, ball x d y -> P y}.\nProof.\nintros x P P_dec H.\ndestruct (locally_ex_not x (fun y => not (P y))) as [d Hd].\napply: filter_imp H.\nintros y Py HP.\nnow apply HP.\nexists d.\nintros y Hy.\ndestruct (P_dec y) as [HP|HP].\nexact HP.\nexfalso.\nnow apply (Hd y).\nQed.\n\nDefinition is_filter_lim (F : (T -> Prop) -> Prop) (x : T) :=\n forall P, locally x P -> F P.\n\nLemma is_filter_lim_filter_le :\n forall {F G} (x : T),\n filter_le G F ->\n is_filter_lim F x -> is_filter_lim G x.\nProof.\nintros F G x L Fx P HP.\napply L.\nnow apply Fx.\nQed.\n\nLemma is_filter_lim_close {F} {FF : ProperFilter F} (x y : T) :\n is_filter_lim F x -> is_filter_lim F y -> close x y.\nProof.\n intros Hx Hy eps.\n specialize (Hy _ (locally_ball y (pos_div_2 eps))).\n specialize (Hx _ (locally_ball x (pos_div_2 eps))).\n generalize (filter_and _ _ Hx Hy) => {Hx Hy} H.\n destruct (filter_ex _ H) as [z Hz].\n rewrite (double_var eps).\n apply ball_triangle with z.\n apply Hz.\n apply ball_sym, Hz.\nQed.\n\nLemma is_filter_lim_locally_close (x y : T) :\n is_filter_lim (locally x) y -> close x y.\nProof.\n by apply is_filter_lim_close.\nQed.\n\nEnd Locally.\n\nLemma filterlim_const :\n forall {T} {U : UniformSpace} {F : (T -> Prop) -> Prop} {FF : Filter F},\n forall a : U, filterlim (fun _ => a) F (locally a).\nProof.\nintros T U F FF a P [eps HP].\nunfold filtermap.\napply filter_forall.\nintros _.\napply HP.\napply ball_center.\nQed.\n\nSection Locally_fct.\n\nContext {T : Type} {U : UniformSpace}.\n\nLemma filterlim_locally :\n forall {F} {FF : Filter F} (f : T -> U) y,\n filterlim f F (locally y) <->\n forall eps : posreal, F (fun x => ball y eps (f x)).\nProof.\nintros F FF f y.\nsplit.\n- intros Cf eps.\n apply (Cf (fun x => ball y eps x)).\n now exists eps.\n- intros Cf P [eps He].\n apply: filter_imp (Cf eps).\n intros t.\n apply He.\nQed.\n\nLemma filterlimi_locally :\n forall {F} {FF : Filter F} (f : T -> U -> Prop) y,\n filterlimi f F (locally y) <->\n forall eps : posreal, F (fun x => exists z, f x z /\\ ball y eps z).\nProof.\nintros F FF f y.\nsplit.\n- intros Cf eps.\n apply (Cf (fun x => ball y eps x)).\n now exists eps.\n- intros Cf P [eps He].\n unfold filtermapi.\n apply: filter_imp (Cf eps).\n intros t [z [Hz1 Hz2]].\n exists z.\n apply (conj Hz1).\n now apply He.\nQed.\n\nLemma filterlim_locally_close :\n forall {F} {FF: ProperFilter F} (f : T -> U) l l',\n filterlim f F (locally l) -> filterlim f F (locally l') ->\n close l l'.\nProof.\nintros F FF f l l' Hl Hl' eps.\nassert (locally l (ball l (pos_div_2 eps))).\n by apply locally_ball.\nspecialize (Hl (ball l (pos_div_2 eps)) H).\nassert (locally l' (ball l' (pos_div_2 eps))).\n by apply locally_ball.\nspecialize (Hl' (ball l' (pos_div_2 eps)) H0).\nunfold filtermap in Hl, Hl'.\ngeneralize (filter_and _ _ Hl Hl') => {H H0} H.\napply filter_ex in H.\ncase: H => x H.\nrewrite (double_var eps).\napply ball_triangle with (f x).\nby apply H.\nby apply ball_sym, H.\nQed.\n\nLemma filterlimi_locally_close :\n forall {F} {FF: ProperFilter F} (f : T -> U -> Prop) l l',\n F (fun x => forall y1 y2, f x y1 -> f x y2 -> y1 = y2) ->\n filterlimi f F (locally l) -> filterlimi f F (locally l') ->\n close l l'.\nProof.\nintros F FF f l l' Hf Hl Hl' eps.\nassert (H: locally l (ball l (pos_div_2 eps))).\n by apply locally_ball.\nspecialize (Hl (ball l (pos_div_2 eps)) H).\nassert (H': locally l' (ball l' (pos_div_2 eps))).\n by apply locally_ball.\nspecialize (Hl' (ball l' (pos_div_2 eps)) H').\nunfold filtermapi in Hl, Hl'.\ngeneralize (filter_and _ _ Hf (filter_and _ _ Hl Hl')) => {H H' Hl Hl' Hf} H.\napply filter_ex in H.\ndestruct H as [x [Hf [[y [H1 H1']] [y' [H2 H2']]]]].\nrewrite (double_var eps).\napply ball_triangle with y.\nexact H1'.\napply ball_sym.\nrewrite (Hf _ _ H1 H2).\nexact H2'.\nQed.\n\nEnd Locally_fct.\n\nLemma is_filter_lim_filtermap {T: UniformSpace} {U : UniformSpace} :\nforall F x (f : T -> U),\n filterlim f (locally x) (locally (f x))\n -> is_filter_lim F x\n -> is_filter_lim (filtermap f F) (f x).\nProof.\n intros F x f Cf Fx P HP.\n apply Cf in HP.\n now apply Fx.\nQed.\n\n(** locally' *)\n\nDefinition locally' {T : UniformSpace} (x : T) :=\n within (fun y => y <> x) (locally x).\n\nGlobal Instance locally'_filter :\n forall {T : UniformSpace} (x : T), Filter (locally' x).\nProof.\nintros T x.\napply within_filter.\napply locally_filter.\nQed.\n\n(** closely *)\n\nSection closely.\n\nContext {T : UniformSpace}.\n\nDefinition closely (P : T * T -> Prop) :=\n exists eps : posreal, forall u v : T, ball u eps v -> P (u, v).\n\nGlobal Instance closely_filter :\n ProperFilter closely.\nProof.\nsplit.\n{ intros P [eps He].\n exists (point_of, point_of).\n apply He.\n apply ball_center. }\nsplit.\n- now exists (mkposreal _ Rlt_0_1).\n- intros P Q [eP HP] [eQ HQ].\n exists (mkposreal _ (Rmin_stable_in_posreal eP eQ)).\n intros u v H.\n split.\n apply HP.\n apply ball_le with (2 := H).\n apply Rmin_l.\n apply HQ.\n apply ball_le with (2 := H).\n apply Rmin_r.\n- intros P Q H [eps HP].\n exists eps.\n intros u v H'.\n now apply H, HP.\nQed.\n\nEnd closely.\n\nLemma filterlim_closely {T} {U : UniformSpace} {F : (T -> Prop) -> Prop} {FF : Filter F} (f : T -> U) :\n filterlim (fun x => (f (fst x), f (snd x))) (filter_prod F F) closely <->\n (forall eps : posreal, exists P, F P /\\ forall u v : T, P u -> P v -> ball (f u) eps (f v)).\nProof.\napply filterlim_prod.\nQed.\n\n(** Pointed filter *)\n\nSection at_point.\n\nContext {T : UniformSpace}.\n\nDefinition at_point (a : T) (P : T -> Prop) : Prop := P a.\n\nGlobal Instance at_point_filter (a : T) :\n ProperFilter (at_point a).\nProof.\nsplit.\n- intros P Pa.\n now exists a.\n- split ; try easy.\n intros P Q PQ Ha.\n now apply PQ.\nQed.\n\nEnd at_point.\n\n(** ** Open sets in uniform spaces *)\n\nSection Open.\n\nContext {T : UniformSpace}.\n\nDefinition open (D : T -> Prop) :=\n forall x, D x -> locally x D.\n\nLemma locally_open :\n forall (D E : T -> Prop),\n open D ->\n (forall x : T, D x -> E x) ->\n forall x : T, D x ->\n locally x E.\nProof.\nintros D E OD H x Dx.\napply filter_imp with (1 := H).\nnow apply OD.\nQed.\n\nLemma open_ext :\n forall D E : T -> Prop,\n (forall x, D x <-> E x) ->\n open D -> open E.\nProof.\nintros D E H OD x Ex.\ngeneralize (OD x (proj2 (H x) Ex)).\napply filter_imp.\nintros y.\napply H.\nQed.\n\nLemma open_and :\n forall D E : T -> Prop,\n open D -> open E ->\n open (fun x => D x /\\ E x).\nProof.\nintros D E OD OE x [Dx Ex].\napply filter_and.\nnow apply OD.\nnow apply OE.\nQed.\n\nLemma open_exists :\n forall I (D : I -> (T -> Prop)),\n (forall i, open (D i)) ->\n open (fun x => exists i, D i x).\nProof.\nintros I D OD x (i&Dx).\ngeneralize (OD i x Dx).\napply filter_imp.\nintros y Dy.\neauto.\nQed.\n\nLemma open_or :\n forall D E : T -> Prop,\n open D -> open E ->\n open (fun x => D x \\/ E x).\nProof.\nintros D E OD OE x [Dx|Ex].\ngeneralize (OD x Dx).\napply filter_imp.\nintros y Dy.\nnow left.\ngeneralize (OE x Ex).\napply filter_imp.\nintros y Ey.\nnow right.\nQed.\n\nLemma open_true :\n open (fun x : T => True).\nProof.\nintros x _.\napply filter_true.\nQed.\n\nLemma open_false :\n open (fun x : T => False).\nProof.\nnow intros x Hx.\nQed.\n\nEnd Open.\n\nLemma open_comp :\n forall {T U : UniformSpace} (f : T -> U) (D : U -> Prop),\n (forall x, D (f x) -> filterlim f (locally x) (locally (f x))) ->\n open D -> open (fun x : T => D (f x)).\nProof.\nintros T U f D Cf OD x Dfx.\napply Cf.\nexact Dfx.\nnow apply OD.\nQed.\n\n(** ** Closed sets in uniform spaces *)\n\nSection Closed.\n\nContext {T : UniformSpace}.\n\nDefinition closed (D : T -> Prop) :=\n forall x, not (locally x (fun x : T => not (D x))) -> D x.\n\nLemma open_not :\n forall D : T -> Prop,\n closed D -> open (fun x => not (D x)).\nProof.\nintros D CD x Dx.\napply locally_not.\nintros H.\napply Dx, CD.\nintros [eps He].\nnow apply (H eps).\nQed.\n\nLemma closed_not :\n forall D : T -> Prop,\n open D -> closed (fun x => not (D x)).\nProof.\nintros D OD x Lx Dx.\napply Lx.\napply: filter_imp (OD _ Dx).\nintros t Dt nDt.\nnow apply nDt.\nQed.\n\nLemma closed_ext :\n forall D E : T -> Prop,\n (forall x, D x <-> E x) ->\n closed D -> closed E.\nProof.\nintros D E DE CD x Hx.\napply DE, CD.\ncontradict Hx.\napply: filter_imp Hx.\nmove => {x} x Dx Ex.\nnow apply Dx, DE.\nQed.\n\nLemma closed_and :\n forall D E : T -> Prop,\n closed D -> closed E ->\n closed (fun x => D x /\\ E x).\nProof.\nintros D E CD CE x Hx.\nsplit.\napply CD.\ncontradict Hx.\napply: filter_imp Hx.\nmove => {x} x nDx [Dx _].\nnow apply nDx.\napply CE.\ncontradict Hx.\napply: filter_imp Hx.\nmove => {x} x nEx [_ Ex].\nnow apply nEx.\nQed.\n\n(*\nLemma closed_or :\n forall D E : T -> Prop,\n closed D -> closed E ->\n closed (fun x => D x \\/ E x).\nProof.\nintros D E CD CE x Hx.\ngeneralize (open_and _ _ CD CE).\napply open_ext.\nclear ; intuition.\nQed.\n*)\n\nLemma closed_true :\n closed (fun x : T => True).\nProof.\nnow intros _ _.\nQed.\n\nLemma closed_false :\n closed (fun x : T => False).\nProof.\nintros x Hx.\napply Hx.\nnow apply filter_forall.\nQed.\n\nEnd Closed.\n\nLemma closed_comp :\n forall {T U : UniformSpace} (f : T -> U) (D : U -> Prop),\n (forall x, filterlim f (locally x) (locally (f x))) ->\n closed D -> closed (fun x : T => D (f x)).\nProof.\nintros T U f D Cf CD x Dfx.\napply CD.\ncontradict Dfx.\nexact: Cf Dfx.\nQed.\n\nLemma closed_filterlim_loc :\n forall {T} {U : UniformSpace} {F} {FF : ProperFilter' F} (f : T -> U) (D : U -> Prop),\n forall y, filterlim f F (locally y) ->\n F (fun x => D (f x)) ->\n closed D -> D y.\nProof.\nintros T U F FF f D y Ffy Df CD.\napply CD.\nintros LD.\napply filter_not_empty.\nspecialize (Ffy _ LD).\nunfold filtermap in Ffy.\napply: filter_imp (filter_and _ _ Df Ffy).\nintros x Dfx.\nnow apply Dfx.\nQed.\n\nLemma closed_filterlim :\n forall {T} {U : UniformSpace} {F} {FF : ProperFilter' F} (f : T -> U) (D : U -> Prop),\n forall y, filterlim f F (locally y) ->\n (forall x, D (f x)) ->\n closed D -> D y.\nProof.\nintros T U F FF f D y Ffy Df.\napply: closed_filterlim_loc Ffy _.\nnow apply filter_forall.\nQed.\n\n(** ** Complete uniform spaces *)\n\nDefinition cauchy {T : UniformSpace} (F : (T -> Prop) -> Prop) :=\n forall eps : posreal, exists x, F (ball x eps).\n\nModule CompleteSpace.\n\nRecord mixin_of (T : UniformSpace) := Mixin {\n lim : ((T -> Prop) -> Prop) -> T ;\n ax1 : forall F, ProperFilter F -> cauchy F -> forall eps : posreal, F (ball (lim F) eps) ;\n ax2 : forall F1 F2, filter_le F1 F2 -> filter_le F2 F1 -> close (lim F1) (lim F2)\n}.\n\nSection ClassDef.\n\nRecord class_of (T : Type) := Class {\n base : UniformSpace.class_of T ;\n mixin : mixin_of (UniformSpace.Pack _ base T)\n}.\nLocal Coercion base : class_of >-> UniformSpace.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition UniformSpace := UniformSpace.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> UniformSpace.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion UniformSpace : type >-> UniformSpace.type.\nCanonical UniformSpace.\nNotation CompleteSpace := type.\n\nEnd Exports.\n\nEnd CompleteSpace.\n\nExport CompleteSpace.Exports.\n\nSection CompleteSpace1.\n\nContext {T : CompleteSpace}.\n\nDefinition lim : ((T -> Prop) -> Prop) -> T := CompleteSpace.lim _ (CompleteSpace.class T).\n\nLemma complete_cauchy :\n forall F : (T -> Prop) -> Prop,\n ProperFilter F -> cauchy F ->\n forall eps : posreal,\n F (ball (lim F) eps).\nProof.\napply CompleteSpace.ax1.\nQed.\n\nLemma close_lim :\n forall F1 F2 : (T -> Prop) -> Prop,\n filter_le F1 F2 -> filter_le F2 F1 ->\n close (lim F1) (lim F2).\nProof.\napply CompleteSpace.ax2.\nQed.\n\nDefinition iota (P : T -> Prop) := lim (fun A => (forall x, P x -> A x)).\n\nLemma iota_correct_weak :\n forall P : T -> Prop,\n (forall x y, P x -> P y -> close x y) ->\n forall x, P x -> close (iota P) x.\nProof.\nintros P HP x Hx eps.\nset (F := fun A : T -> Prop => forall t : T, P t -> A t).\nassert (forall eps : posreal, F (ball (lim F) eps)) as HF.\napply complete_cauchy.\nconstructor.\nintros Q FQ.\nexists x.\nnow apply FQ.\nconstructor.\nnow intro x0.\nintros A B HA HB x0 Hx0.\nsplit.\nnow apply HA.\nnow apply HB.\nintros A B HAB HA x0 Hx0.\napply HAB ; now apply HA.\nintro e.\nexists x.\nintros y Hy.\nnow apply HP.\nassert (F (ball (lim F) eps)) as Heps.\napply HF.\nclear HF.\nnow apply Heps.\nQed.\n\nLemma close_iota :\n forall P Q : T -> Prop,\n (forall x, P x <-> Q x) ->\n close (iota P) (iota Q).\nProof.\nintros P Q H.\napply close_lim ; intros R HR x Hx ; apply HR, H, Hx.\nQed.\n\nEnd CompleteSpace1.\n\nLemma cauchy_distance' :\n forall {T : UniformSpace} {F} {FF : ProperFilter F},\n cauchy F <-> filter_le (filter_prod F F) (@closely T).\nProof.\nintros T F FF.\nsplit.\n- intros H P [eps HP].\n case: (H (pos_div_2 eps)) => {H} x Hx.\n split with (1 := Hx) (2 := Hx).\n move => u v Hu Hv.\n apply HP.\n rewrite (double_var eps).\n apply ball_triangle with x.\n by apply ball_sym.\n exact Hv.\n- intros H eps.\n destruct (H (fun '(u,v) => ball u eps v)) as [P Q HP HQ H'].\n now exists eps.\n destruct (filter_ex P HP) as [x Hx].\n exists x.\n move: (fun v => H' x v Hx) => {H H'} H.\n now apply filter_imp with (1 := H).\nQed.\n\nLemma cauchy_distance :\n forall {T : UniformSpace} {F} {FF : ProperFilter F},\n cauchy F <->\n (forall eps : posreal, exists P, F P /\\ forall u v : T, P u -> P v -> ball u eps v).\nProof.\nintros T F FF.\nsplit.\n- intros H eps.\n case: (H (pos_div_2 eps)) => {H} x Hx.\n exists (ball x (pos_div_2 eps)).\n split.\n by [].\n move => u v Hu Hv.\n rewrite (double_var eps).\n apply ball_triangle with x.\n by apply ball_sym.\n exact Hv.\n- intros H eps.\n case: (H eps) => {H} P [HP H].\n destruct (filter_ex P HP) as [x Hx].\n exists x.\n move: (fun v => H x v Hx) => {H} H.\n apply filter_imp with (1 := H).\n by [].\nQed.\n\nSection fct_CompleteSpace.\n\nContext {T : Type} {U : CompleteSpace}.\n\nLemma filterlim_locally_closely :\n forall {F} {FF : ProperFilter F} (f : T -> U),\n filterlim (fun x => (f (fst x), f (snd x))) (filter_prod F F) closely <->\n exists y, filterlim f F (locally y).\nProof.\nintros F FF f.\nsplit.\n- intros H.\n exists (lim (filtermap f F)).\n intros P [eps HP].\n refine (_ (complete_cauchy (filtermap f F) _ _ eps)).\n + now apply filter_imp.\n + apply cauchy_distance'.\n apply filter_le_trans with (2 := H).\n apply prod_filtermap_le.\n- intros [y Hy] P [eps HP].\n split with (fun x => ball y (pos_div_2 eps) (f x)) (fun x => ball y (pos_div_2 eps) (f x)).\n apply Hy, locally_ball.\n apply Hy, locally_ball.\n intros u v Hu Hv.\n apply HP.\n rewrite (double_var eps).\n apply ball_triangle with (2 := Hv).\n now apply ball_sym.\nQed.\n\nLemma filterlim_locally_cauchy :\n forall {F} {FF : ProperFilter F} (f : T -> U),\n (forall eps : posreal, exists P, F P /\\ forall u v : T, P u -> P v -> ball (f u) eps (f v)) <->\n exists y, filterlim f F (locally y).\nProof.\nintros F FF f.\napply iff_trans with (2 := filterlim_locally_closely f).\napply iff_sym, filterlim_closely.\nQed.\n\nLemma filterlimi_locally_cauchy :\n forall {F} {FF : ProperFilter F} (f : T -> U -> Prop),\n F (fun x => (exists y, f x y) /\\\n (forall y1 y2, f x y1 -> f x y2 -> y1 = y2)) ->\n ((forall eps : posreal, exists P, F P /\\\n forall u v : T, P u -> P v -> forall u' v': U, f u u' -> f v v' -> ball u' eps v') <->\n exists y, filterlimi f F (locally y)).\nProof.\nintros F FF f Hf.\nassert (FF': ProperFilter (filtermapi f F)).\n apply filtermapi_proper_filter.\n exact: filter_imp Hf.\n exact FF.\nsplit.\n- intros H.\n exists (lim (filtermapi f F)).\n intros P [eps HP].\n refine (_ (complete_cauchy (filtermapi f F) _ _ eps)).\n + now apply filter_imp.\n + clear eps P HP.\n intros eps.\n case: (H eps) => {H} [P [FP H]].\n assert (FfP := filter_and _ _ Hf FP).\n destruct (filter_ex _ FfP) as [x [[[fx Hfx] _] Px]].\n exists fx.\n unfold filtermapi.\n apply: filter_imp FfP.\n intros x' [[[fx' Hfx'] _] Px'].\n exists fx'.\n apply (conj Hfx').\n exact: H Hfx Hfx'.\n- intros [y Hy] eps.\n exists (fun x => forall fx, f x fx -> ball y (pos_div_2 eps) fx).\n split.\n assert (Hb: locally y (ball y (pos_div_2 eps))).\n now exists (pos_div_2 eps).\n assert (H := filter_and _ _ Hf (Hy _ Hb)).\n apply: filter_imp H.\n intros x [[_ H] [fx2 [Hfx2 H']]] fx Hfx.\n now rewrite <- (H fx2).\n intros u v Hu Hv fu fv Hfu Hfv.\n rewrite (double_var eps).\n apply ball_triangle with y.\n apply ball_sym.\n now apply Hu.\n now apply Hv.\nQed.\n\nDefinition lim_fct (F : ((T -> U) -> Prop) -> Prop) (t : T) :=\n lim (fun P => F (fun g => P (g t))).\n\nLemma complete_cauchy_fct :\n forall (F : ((T -> U) -> Prop) -> Prop),\n ProperFilter F ->\n (forall eps : posreal, exists f : T -> U, F (ball f eps)) ->\n forall eps : posreal, F (ball (lim_fct F) eps).\nProof.\n move => F FF HFc.\n\n set Fr := fun (t : T) (P : U -> Prop) => F (fun g => P (g t)).\n have FFr : forall t, ProperFilter (Fr t).\n case: FF => HF FF t.\n split.\n - move => P Hp.\n case: (HF _ Hp) => f Hf.\n by exists (f t).\n - split.\n + by apply FF.\n + move => P P' Hp Hp'.\n by apply FF.\n + move => P P' Hpp'.\n apply FF.\n move => f ; by apply Hpp'.\n assert (HFrc : forall t, forall eps : posreal, exists x : U, Fr t (ball x eps)).\n move => t eps.\n case: (HFc eps) => f Hf.\n exists (f t).\n move: Hf ; apply FF => g.\n by [].\n assert (forall t (eps : posreal), (Fr t) (fun x => ball (lim_fct F t) eps x)).\n move => t.\n apply complete_cauchy.\n apply FFr.\n exact (HFrc t).\n\n move => eps.\n\n generalize (proj1 cauchy_distance HFc) => {HFc} HFc.\n\n case: (HFc (pos_div_2 eps)) => {HFc} P ; simpl ; case => HP H0.\n apply filter_imp with (2 := HP).\n move => g Hg t.\n move: (fun h => H0 g h Hg) => {H0} H0.\n move: (H t (pos_div_2 eps)) ; simpl => {H} H.\n unfold Fr in H ; generalize (filter_and _ _ H HP) => {H} H.\n apply filter_ex in H ; case: H => h H.\n rewrite (double_var eps).\n apply ball_triangle with (h t).\n by apply H.\n apply ball_sym, H0.\n by apply H.\nQed.\n\nLemma close_lim_fct :\n forall F1 F2 : ((T -> U) -> Prop) -> Prop,\n filter_le F1 F2 -> filter_le F2 F1 ->\n close (lim_fct F1) (lim_fct F2).\nProof.\nintros F1 F2 H12 H21 eps t.\napply close_lim => P.\napply H12.\napply H21.\nQed.\n\nDefinition fct_CompleteSpace_mixin :=\n CompleteSpace.Mixin _ lim_fct complete_cauchy_fct close_lim_fct.\n\nCanonical fct_CompleteSpace :=\n CompleteSpace.Pack (T -> U) (CompleteSpace.Class _ _ fct_CompleteSpace_mixin) (T -> U).\n\nEnd fct_CompleteSpace.\n\n(** ** Limit switching *)\n\nSection Filterlim_switch.\n\nContext {T1 T2 : Type}.\n\nLemma filterlim_switch_1 {U : UniformSpace}\n F1 (FF1 : ProperFilter F1) F2 (FF2 : Filter F2) (f : T1 -> T2 -> U) g h (l : U) :\n filterlim f F1 (locally g) ->\n (forall x, filterlim (f x) F2 (locally (h x))) ->\n filterlim h F1 (locally l) -> filterlim g F2 (locally l).\nProof.\n intros Hfg Hfh Hhl P.\n case: FF1 => HF1 FF1.\n apply filterlim_locally.\n move => eps.\n\n have FF := (filter_prod_filter _ _ F1 F2 FF1 FF2).\n\n assert (filter_prod F1 F2 (fun x => ball (g (snd x)) (eps / 2 / 2) (f (fst x) (snd x)))).\n apply Filter_prod with (fun x : T1 => ball g (eps / 2 / 2) (f x)) (fun _ => True).\n move: (proj1 (@filterlim_locally _ _ F1 FF1 f g) Hfg (pos_div_2 (pos_div_2 eps))) => {Hfg} /= Hfg.\n by [].\n by apply FF2.\n simpl ; intros.\n apply H.\n move: H => {Hfg} Hfg.\n\n assert (filter_prod F1 F2 (fun x : T1 * T2 => ball l (eps / 2) (h (fst x)))).\n apply Filter_prod with (fun x : T1 => ball l (eps / 2) (h x)) (fun _ => True).\n move: (proj1 (@filterlim_locally _ _ F1 FF1 h l) Hhl (pos_div_2 eps)) => {Hhl} /= Hhl.\n by [].\n by apply FF2.\n by [].\n move: H => {Hhl} Hhl.\n\n case: (@filter_and _ _ FF _ _ Hhl Hfg) => {Hhl Hfg} /= ; intros.\n\n move: (fun x => proj1 (@filterlim_locally _ _ F2 FF2 (f x) (h x)) (Hfh x) (pos_div_2 (pos_div_2 eps))) => {Hfh} /= Hfh.\n case: (HF1 Q f0) => x Hx.\n move: (@filter_and _ _ FF2 _ _ (Hfh x) g0) => {Hfh}.\n apply filter_imp => y Hy.\n rewrite (double_var eps).\n apply ball_triangle with (h x).\n apply (p x y).\n by [].\n by apply Hy.\n rewrite (double_var (eps / 2)).\n apply ball_triangle with (f x y).\n by apply Hy.\n apply ball_sym, p.\n by [].\n by apply Hy.\nQed.\n\nLemma filterlim_switch_2 {U : CompleteSpace}\n F1 (FF1 : ProperFilter F1) F2 (FF2 : ProperFilter F2) (f : T1 -> T2 -> U) g h :\n filterlim f F1 (locally g) ->\n (forall x, filterlim (f x) F2 (locally (h x))) ->\n exists l : U, filterlim h F1 (locally l).\nProof.\n move => Hfg Hfh.\n case : (proj1 (filterlim_locally_cauchy h)).\n move => eps.\n generalize (proj2 (filterlim_locally_cauchy f)) => Hf.\n assert (exists y : T2 -> U, filterlim f F1 (locally y)).\n exists g => P Hp.\n apply Hfg.\n case: Hp => d Hp.\n exists d => y Hy.\n apply: Hp.\n by apply Hy.\n\n move: H => {Hfg} Hfg.\n move: (Hf Hfg (pos_div_2 eps)) => {Hf Hfg} /= Hf.\n\n case: FF2 => HF2 FF2.\n generalize (fun x => proj1 (filterlim_locally (f x) (h x)) (Hfh x) (pos_div_2 (pos_div_2 eps)))\n => {Hfh} Hfh.\n\n case: Hf => P [Hp Hf].\n exists P ; split.\n by [].\n move => u v Hu Hv.\n move: (Hfh u) => /= Hu'.\n move: (Hfh v) => /= Hv'.\n move: (@filter_and _ F2 FF2 _ _ Hu' Hv') => {Hu' Hv' Hfh} Hfh.\n case: (HF2 _ Hfh) => {Hfh} y Hy.\n replace (pos eps) with (eps / 2 / 2 + (eps / 2 + eps / 2 / 2)) by field.\n apply ball_triangle with (f u y).\n by apply Hy.\n apply ball_triangle with (f v y).\n by apply Hf.\n now apply ball_sym.\n\n move => l Hl.\n by exists l.\nQed.\n\nLemma filterlim_switch {U : CompleteSpace}\n F1 (FF1 : ProperFilter F1) F2 (FF2 : ProperFilter F2) (f : T1 -> T2 -> U) g h :\n filterlim f F1 (locally g) ->\n (forall x, filterlim (f x) F2 (locally (h x))) ->\n exists l : U, filterlim h F1 (locally l) /\\ filterlim g F2 (locally l).\nProof.\n move => Hfg Hfh.\n destruct (filterlim_switch_2 F1 FF1 F2 FF2 f g h Hfg Hfh) as [l Hhl].\n exists l ; split.\n exact Hhl.\n case: FF2 => HF2 FF2.\n now apply (filterlim_switch_1 F1 FF1 F2 FF2 f g h l).\nQed.\n\nEnd Filterlim_switch.\n\nLemma filterlim_switch_dom {T1 T2 : Type} {U : CompleteSpace}\n F1 (FF1 : ProperFilter F1) F2 (FF2 : Filter F2)\n (dom : T2 -> Prop) (HF2 : forall P, F2 P -> exists x, dom x /\\ P x)\n (f : T1 -> T2 -> U) g h :\n filterlim (fun x (y : {z : T2 | dom z}) => f x (proj1_sig y)) F1 (locally (T := fct_UniformSpace _ _) (fun y : {z : T2 | dom z} => g (proj1_sig y))) ->\n (forall x, filterlim (f x) (within dom F2) (locally (h x))) ->\n exists l : U, filterlim h F1 (locally l) /\\ filterlim g (within dom F2) (locally l).\nProof.\nset (T2' := { y : T2 | dom y }).\nset (f' := fun x (y : T2') => f x (proj1_sig y)).\nset (F2' := fun P : T2' -> Prop => F2 (fun x => forall (H:dom x), P (exist _ x H))).\nset (g' := fun y : T2' => g (proj1_sig y)).\nintros Hfg Hfh.\nrefine (filterlim_switch F1 FF1 F2' _ f' g' h _ _).\nnow apply subset_filter_proper.\nintros H P.\nnow apply Hfg.\nintros x P HP.\nnow apply Hfh.\nQed.\n\n(** * Modules *)\n\nModule ModuleSpace.\n\nRecord mixin_of (K : Ring) (V : AbelianGroup) := Mixin {\n scal : K -> V -> V ;\n ax1 : forall x y u, scal x (scal y u) = scal (mult x y) u ;\n ax2 : forall u, scal one u = u ;\n ax3 : forall x u v, scal x (plus u v) = plus (scal x u) (scal x v) ;\n ax4 : forall x y u, scal (plus x y) u = plus (scal x u) (scal y u)\n}.\n\nSection ClassDef.\n\nVariable K : Ring.\n\nRecord class_of (V : Type) := Class {\n base : AbelianGroup.class_of V ;\n mixin : mixin_of K (AbelianGroup.Pack _ base V)\n}.\nLocal Coercion base : class_of >-> AbelianGroup.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition AbelianGroup := AbelianGroup.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> AbelianGroup.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion AbelianGroup : type >-> AbelianGroup.type.\nCanonical AbelianGroup.\nNotation ModuleSpace := type.\n\nEnd Exports.\n\nEnd ModuleSpace.\n\nExport ModuleSpace.Exports.\n\nSection ModuleSpace1.\n\nContext {K : Ring} {V : ModuleSpace K}.\n\nDefinition scal : K -> V -> V := ModuleSpace.scal _ _ (ModuleSpace.class K V).\n\nLemma scal_assoc :\n forall (x y : K) (u : V),\n scal x (scal y u) = scal (mult x y) u.\nProof.\napply ModuleSpace.ax1.\nQed.\n\nLemma scal_one :\n forall (u : V), scal one u = u.\nProof.\napply ModuleSpace.ax2.\nQed.\n\nLemma scal_distr_l :\n forall (x : K) (u v : V),\n scal x (plus u v) = plus (scal x u) (scal x v).\nProof.\napply ModuleSpace.ax3.\nQed.\n\nLemma scal_distr_r :\n forall (x y : K) (u : V),\n scal (plus x y) u = plus (scal x u) (scal y u).\nProof.\napply ModuleSpace.ax4.\nQed.\n\nLemma scal_zero_r :\n forall x : K,\n scal x zero = zero.\nProof.\nintros x.\napply plus_reg_r with (scal x zero).\nrewrite <- scal_distr_l.\nrewrite plus_zero_r.\nnow rewrite plus_zero_l.\nQed.\n\nLemma scal_zero_l :\n forall u : V,\n scal zero u = zero.\nProof.\nintros u.\napply plus_reg_r with (r := scal zero u).\nrewrite plus_zero_l.\nrewrite <- scal_distr_r.\nnow rewrite plus_zero_r.\nQed.\n\nLemma scal_opp_l :\n forall (x : K) (u : V),\n scal (opp x) u = opp (scal x u).\nProof.\nintros x u.\napply plus_reg_r with (r := (scal x u)).\nrewrite plus_opp_l.\nrewrite <- scal_distr_r.\nrewrite plus_opp_l.\napply scal_zero_l.\nQed.\n\nLemma scal_opp_r :\n forall (x : K) (u : V),\n scal x (opp u) = opp (scal x u).\nProof.\nintros x u.\napply plus_reg_r with (r := (scal x u)).\nrewrite plus_opp_l.\nrewrite <- scal_distr_l.\nrewrite plus_opp_l.\napply scal_zero_r.\nQed.\n\nLemma scal_opp_one :\n forall u : V,\n scal (opp one) u = opp u.\nProof.\nintros u.\nrewrite scal_opp_l.\nnow rewrite scal_one.\nQed.\n\nLemma scal_minus_distr_l (x : K) (u v : V) :\n scal x (minus u v) = minus (scal x u) (scal x v).\nProof.\n by rewrite /minus scal_distr_l scal_opp_r.\nQed.\nLemma scal_minus_distr_r (x y : K) (u : V) :\n scal (minus x y) u = minus (scal x u) (scal y u).\nProof.\n by rewrite /minus scal_distr_r scal_opp_l.\nQed.\n\nLemma sum_n_m_scal_l :\n forall (a : K) (u : nat -> V) (n m : nat),\n sum_n_m (fun k => scal a (u k)) n m = scal a (sum_n_m u n m).\nProof.\n intros a u n m.\n case: (le_dec n m) => Hnm.\n elim: m n u Hnm => [ | m IH] n u Hnm.\n apply le_n_O_eq in Hnm.\n by rewrite -Hnm !sum_n_n.\n destruct n.\n rewrite !sum_n_Sm ; try by apply le_O_n.\n rewrite IH.\n by apply sym_eq, scal_distr_l.\n by apply le_O_n.\n rewrite -!sum_n_m_S.\n apply IH.\n by apply le_S_n.\n apply not_le in Hnm.\n rewrite !sum_n_m_zero //.\n by rewrite scal_zero_r.\nQed.\n\nLemma sum_n_scal_l :\n forall (a : K) (u : nat -> V) (n : nat),\n sum_n (fun k => scal a (u k)) n = scal a (sum_n u n).\nProof.\n intros a u n.\n apply sum_n_m_scal_l.\nQed.\n\nEnd ModuleSpace1.\n\n(** Rings are modules *)\n\nSection Ring_ModuleSpace.\n\nVariable (K : Ring).\n\nDefinition Ring_ModuleSpace_mixin :=\n ModuleSpace.Mixin K _ _ mult_assoc mult_one_l mult_distr_l mult_distr_r.\n\nCanonical Ring_ModuleSpace :=\n ModuleSpace.Pack K K (ModuleSpace.Class _ _ _ Ring_ModuleSpace_mixin) K.\n\nEnd Ring_ModuleSpace.\n\nSection AbsRing_ModuleSpace.\n\nVariable (K : AbsRing).\n\nDefinition AbsRing_ModuleSpace_mixin :=\n ModuleSpace.Mixin K _ _ mult_assoc mult_one_l mult_distr_l mult_distr_r.\n\nCanonical AbsRing_ModuleSpace :=\n ModuleSpace.Pack K K (ModuleSpace.Class _ _ _ AbsRing_ModuleSpace_mixin) K.\n\nEnd AbsRing_ModuleSpace.\n\n(** ** Modules with a norm *)\n\nModule NormedModuleAux.\n\nSection ClassDef.\n\nVariable K : AbsRing.\n\nRecord class_of (T : Type) := Class {\n base : ModuleSpace.class_of K T ;\n mixin : UniformSpace.mixin_of T\n}.\nLocal Coercion base : class_of >-> ModuleSpace.class_of.\nLocal Coercion mixin : class_of >-> UniformSpace.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition AbelianGroup := AbelianGroup.Pack cT xclass xT.\nDefinition ModuleSpace := ModuleSpace.Pack _ cT xclass xT.\nDefinition UniformSpace := UniformSpace.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> ModuleSpace.class_of.\nCoercion mixin : class_of >-> UniformSpace.class_of.\nCoercion sort : type >-> Sortclass.\nCoercion AbelianGroup : type >-> AbelianGroup.type.\nCanonical AbelianGroup.\nCoercion ModuleSpace : type >-> ModuleSpace.type.\nCanonical ModuleSpace.\nCoercion UniformSpace : type >-> UniformSpace.type.\nCanonical UniformSpace.\nNotation NormedModuleAux := type.\n\nEnd Exports.\n\nEnd NormedModuleAux.\n\nExport NormedModuleAux.Exports.\n\nModule NormedModule.\n\nRecord mixin_of (K : AbsRing) (V : NormedModuleAux K) := Mixin {\n norm : V -> R ;\n norm_factor : R ;\n ax1 : forall (x y : V), norm (plus x y) <= norm x + norm y ;\n ax2 : forall (l : K) (x : V), norm (scal l x) <= abs l * norm x ;\n ax3 : forall (x y : V) (eps : R), norm (minus y x) < eps -> ball x eps y ;\n ax4 : forall (x y : V) (eps : posreal), ball x eps y -> norm (minus y x) < norm_factor * eps ;\n ax5 : forall x : V, norm x = 0 -> x = zero\n}.\n\nSection ClassDef.\n\nVariable K : AbsRing.\n\nRecord class_of (T : Type) := Class {\n base : NormedModuleAux.class_of K T ;\n mixin : mixin_of K (NormedModuleAux.Pack K T base T)\n}.\nLocal Coercion base : class_of >-> NormedModuleAux.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition AbelianGroup := AbelianGroup.Pack cT xclass xT.\nDefinition ModuleSpace := ModuleSpace.Pack _ cT xclass xT.\nDefinition UniformSpace := UniformSpace.Pack cT xclass xT.\nDefinition NormedModuleAux := NormedModuleAux.Pack _ cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> NormedModuleAux.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion AbelianGroup : type >-> AbelianGroup.type.\nCanonical AbelianGroup.\nCoercion ModuleSpace : type >-> ModuleSpace.type.\nCanonical ModuleSpace.\nCoercion UniformSpace : type >-> UniformSpace.type.\nCanonical UniformSpace.\nCoercion NormedModuleAux : type >-> NormedModuleAux.type.\nCanonical NormedModuleAux.\nNotation NormedModule := type.\n\nEnd Exports.\n\nEnd NormedModule.\n\nExport NormedModule.Exports.\n\nSection NormedModule1.\n\nContext {K : AbsRing} {V : NormedModule K}.\n\nDefinition norm : V -> R := NormedModule.norm K _ (NormedModule.class K V).\n\nDefinition norm_factor : R := NormedModule.norm_factor K _ (NormedModule.class K V).\n\nLemma norm_triangle :\n forall x y : V,\n norm (plus x y) <= norm x + norm y.\nProof.\napply NormedModule.ax1.\nQed.\n\nLemma norm_scal :\n forall (l : K) (x : V),\n norm (scal l x) <= abs l * norm x.\nProof.\napply NormedModule.ax2.\nQed.\n\nLemma norm_compat1 :\n forall (x y : V) (eps : R),\n norm (minus y x) < eps -> ball x eps y.\nProof.\napply NormedModule.ax3.\nQed.\n\nLemma norm_compat2 :\n forall (x y : V) (eps : posreal), ball x eps y -> norm (minus y x) < norm_factor * eps.\nProof.\napply: NormedModule.ax4.\nQed.\n\nLemma norm_eq_zero :\n forall x : V, norm x = 0 -> x = zero.\nProof.\napply NormedModule.ax5.\nQed.\n\nLemma norm_zero :\n norm zero = 0.\nProof.\napply Rle_antisym.\n- rewrite -(scal_zero_l zero).\n rewrite -(Rmult_0_l (norm zero)).\n rewrite -(@abs_zero K).\n apply norm_scal.\n- apply Rplus_le_reg_r with (norm zero).\n rewrite Rplus_0_l.\n rewrite -{1}[zero]plus_zero_r.\n exact (norm_triangle zero zero).\nQed.\n\nLemma norm_factor_gt_0 :\n 0 < norm_factor.\nProof.\nrewrite <- (Rmult_1_r norm_factor).\nrewrite <- norm_zero.\nrewrite <- (plus_opp_r zero).\napply (norm_compat2 _ _ (mkposreal _ Rlt_0_1)).\napply ball_center.\nQed.\n\nLemma norm_opp :\n forall x : V,\n norm (opp x) = norm x.\nProof.\nintros x.\napply Rle_antisym.\n- rewrite -scal_opp_one.\n rewrite -(Rmult_1_l (norm x)) -(@abs_opp_one K).\n apply norm_scal.\n- rewrite -{1}[x]opp_opp -scal_opp_one.\n rewrite -(Rmult_1_l (norm (opp x))) -(@abs_opp_one K).\n apply norm_scal.\nQed.\n\nLemma norm_ge_0 :\n forall x : V,\n 0 <= norm x.\nProof.\n intros x.\n apply Rmult_le_reg_l with 2.\n by apply Rlt_0_2.\n rewrite Rmult_0_r -norm_zero -(plus_opp_r x).\n apply Rle_trans with (norm x + norm (opp x)).\n apply norm_triangle.\n apply Req_le ; rewrite norm_opp.\n ring.\nQed.\n\nLemma norm_gt_0 :\n forall x : V,\n x <> zero -> 0 < norm x.\nProof.\nintros x Hx.\napply Rnot_le_lt.\ncontradict Hx.\napply norm_eq_zero.\napply Rle_antisym with (1 := Hx).\napply norm_ge_0.\nQed.\n\nLemma norm_minus_gt_0 :\n forall x y : V,\n x <> y -> 0 < norm (minus x y).\nProof.\nintros x y Hxy.\napply norm_gt_0.\ncontradict Hxy.\napply plus_reg_r with (opp y).\nnow rewrite plus_opp_r.\nQed.\n\nLemma norm_triangle_inv :\n forall x y : V,\n Rabs (norm x - norm y) <= norm (minus x y).\nProof.\n intros x y.\n apply Rabs_le_between' ; split.\n rewrite -(norm_opp (minus _ _)).\n apply Rle_minus_l ; eapply Rle_trans.\n 2 : apply norm_triangle.\n apply Req_le, f_equal.\n by rewrite /minus opp_plus plus_assoc plus_opp_r plus_zero_l opp_opp.\n eapply Rle_trans.\n 2 : apply norm_triangle.\n apply Req_le, f_equal.\n by rewrite /minus plus_comm -plus_assoc plus_opp_l plus_zero_r.\nQed.\n\nLemma eq_dec :\n forall x y : V,\n { x = y } + { x <> y }.\nProof.\nintros x y.\ndestruct (Req_EM_T (norm (minus y x)) 0) as [H|H].\n- left.\n apply plus_reg_r with (opp x).\n rewrite plus_opp_r.\n now apply eq_sym, norm_eq_zero.\n- right.\n contradict H.\n rewrite H minus_eq_zero.\n apply norm_zero.\nQed.\n\nLemma eq_close :\n forall x y : V,\n close x y -> x = y.\nProof.\nintros x y H.\napply plus_reg_r with (opp x).\nrewrite plus_opp_r.\napply eq_sym, norm_eq_zero.\napply Rle_antisym.\n2: apply norm_ge_0.\napply prop_eps.\nintros eps He.\nassert (He' : 0 < eps / norm_factor).\n apply Rdiv_lt_0_compat with (1 := He).\n apply norm_factor_gt_0.\nspecialize (H (mkposreal _ He')).\nreplace eps with (norm_factor * (eps / norm_factor)).\napply norm_compat2 with (1 := H).\nfield.\napply Rgt_not_eq, norm_factor_gt_0.\nQed.\n\nDefinition ball_norm (x : V) (eps : R) (y : V) := norm (minus y x) < eps.\n\nDefinition locally_norm (x : V) (P : V -> Prop) :=\n exists eps : posreal, forall y, ball_norm x eps y -> P y.\n\nLemma locally_le_locally_norm :\n forall x, filter_le (locally x) (locally_norm x).\nProof.\nintros x P [eps H].\nassert (He : 0 < / norm_factor * eps).\n apply Rmult_lt_0_compat.\n apply Rinv_0_lt_compat.\n apply norm_factor_gt_0.\n apply cond_pos.\nexists (mkposreal _ He).\nintros y By.\napply H.\nunfold ball_norm.\nrewrite -(Rmult_1_l eps) -(Rinv_r norm_factor).\nrewrite Rmult_assoc.\napply norm_compat2 with (1 := By).\napply Rgt_not_eq.\napply norm_factor_gt_0.\nQed.\n\nLemma locally_norm_le_locally :\n forall x, filter_le (locally_norm x) (locally x).\nProof.\nintros x P [eps H].\nexists eps.\nintros y By.\napply H.\nnow apply norm_compat1.\nQed.\n\nLemma locally_norm_ball_norm :\n forall (x : V) (eps : posreal),\n locally_norm x (ball_norm x eps).\nProof.\nintros x eps.\nnow exists eps.\nQed.\n\nLemma locally_norm_ball :\n forall (x : V) (eps : posreal),\n locally_norm x (ball x eps).\nProof.\nintros x eps.\napply locally_norm_le_locally.\napply locally_ball.\nQed.\n\nLemma locally_ball_norm :\n forall (x : V) (eps : posreal),\n locally x (ball_norm x eps).\nProof.\nintros x eps.\napply locally_le_locally_norm.\napply locally_norm_ball_norm.\nQed.\n\nLemma ball_norm_triangle (x y z : V) (e1 e2 : R) :\n ball_norm x e1 y -> ball_norm y e2 z -> ball_norm x (e1 + e2) z.\nProof.\n intros H1 H2.\n eapply Rle_lt_trans, Rplus_lt_compat.\n 2: by apply H1.\n 2: by apply H2.\n rewrite Rplus_comm.\n eapply Rle_trans, norm_triangle.\n apply Req_le, f_equal.\n rewrite /minus -!plus_assoc.\n apply f_equal.\n by rewrite plus_assoc plus_opp_l plus_zero_l.\nQed.\n\nLemma ball_norm_center (x : V) (e : posreal) :\n ball_norm x e x.\nProof.\n eapply Rle_lt_trans, e.\n rewrite minus_eq_zero norm_zero.\n by apply Req_le.\nQed.\n\nLemma ball_norm_dec : forall (x y : V) (eps : posreal),\n {ball_norm x eps y} + {~ ball_norm x eps y}.\nProof.\n intros x y eps.\n apply Rlt_dec.\nQed.\n\nLemma ball_norm_sym :\n forall (x y : V) (eps : posreal), ball_norm x eps y -> ball_norm y eps x.\nProof.\n intros x y eps Hxy.\n unfold ball_norm.\n rewrite <- norm_opp.\n rewrite opp_minus.\n apply Hxy.\nQed.\n\nLemma ball_norm_le :\n forall (x : V) (e1 e2 : posreal), e1 <= e2 ->\n forall y, ball_norm x e1 y -> ball_norm x e2 y.\nProof.\n intros x e1 e2 He y H1.\n now apply Rlt_le_trans with e1.\nQed.\n\nLemma ball_norm_eq :\n forall x y : V,\n (forall eps : posreal, ball_norm x eps y) -> x = y.\nProof.\nintros x y H.\napply plus_reg_r with (opp x).\nrewrite plus_opp_r.\napply eq_sym, norm_eq_zero.\napply Rle_antisym.\n2: apply norm_ge_0.\napply prop_eps.\nintros eps He.\nexact (H (mkposreal eps He)).\nQed.\n\nLemma is_filter_lim_unique :\n forall {F} {FF : ProperFilter' F} (x y : V),\n is_filter_lim F x -> is_filter_lim F y -> x = y.\nProof.\nintros F FF x y Hx Hy.\napply ball_norm_eq => eps.\nassert (Hx': F (ball_norm x (pos_div_2 eps))).\n apply Hx.\n apply locally_ball_norm.\nassert (Hy': F (ball_norm y (pos_div_2 eps))).\n apply Hy.\n apply locally_ball_norm.\napply Rnot_le_lt.\nintros H.\napply (@filter_not_empty V F FF).\napply: filter_imp (filter_and _ _ Hx' Hy').\nclear -H.\nintros z [Bx By].\nrevert H.\napply Rlt_not_le.\nrewrite (double_var eps).\nchange (eps / 2) with (pos (pos_div_2 eps)).\napply ball_norm_triangle with (1 := Bx).\nnow apply ball_norm_sym.\nQed.\n\nLemma is_filter_lim_locally_unique :\n forall (x y : V),\n is_filter_lim (locally x) y -> x = y.\nProof.\nintros x y H.\napply eq_close.\nnow apply is_filter_lim_locally_close.\nQed.\n\nDefinition closely_norm (P : V * V -> Prop) :=\n exists eps : posreal, forall x y, ball_norm x eps y -> P (x, y).\n\nLemma closely_le_closely_norm :\n filter_le closely closely_norm.\nProof.\nintros P [eps H].\nassert (He : 0 < / norm_factor * eps).\n apply Rmult_lt_0_compat.\n apply Rinv_0_lt_compat.\n apply norm_factor_gt_0.\n apply cond_pos.\nexists (mkposreal _ He).\nintros u v Buv.\napply H.\nunfold ball_norm.\nrewrite -(Rmult_1_l eps) -(Rinv_r norm_factor).\nrewrite Rmult_assoc.\napply norm_compat2 with (1 := Buv).\napply Rgt_not_eq.\napply norm_factor_gt_0.\nQed.\n\nLemma closely_norm_le_closely :\n filter_le closely_norm closely.\nProof.\nintros P [eps H].\nexists eps.\nintros u v Buv.\napply H.\nnow apply norm_compat1.\nQed.\n\nEnd NormedModule1.\n\nSection NormedModule2.\n\nContext {T : Type} {K : AbsRing} {V : NormedModule K}.\n\nLemma filterlim_closely_norm {F : (T -> Prop) -> Prop} {FF : Filter F} (f : T -> V) :\n filterlim (fun x => (f (fst x), f (snd x))) (filter_prod F F) closely_norm <->\n (forall eps : posreal, exists P, F P /\\ forall u v : T, P u -> P v -> ball_norm (f u) eps (f v)).\nProof.\napply filterlim_prod.\nQed.\n\nLemma filterlim_locally_unique :\n forall {F} {FF : ProperFilter' F} (f : T -> V) (x y : V),\n filterlim f F (locally x) -> filterlim f F (locally y) ->\n x = y.\nProof.\nintros F FF f x y.\napply is_filter_lim_unique.\nQed.\n\nLemma filterlimi_locally_unique :\n forall {F} {FF : ProperFilter' F} (f : T -> V -> Prop) (x y : V),\n F (fun x => forall y1 y2, f x y1 -> f x y2 -> y1 = y2) ->\n filterlimi f F (locally x) -> filterlimi f F (locally y) ->\n x = y.\nProof.\nintros F FF f x y Hf Hx Hy.\napply ball_norm_eq => eps.\nspecialize (Hx (ball_norm x (pos_div_2 eps)) (locally_ball_norm _ _)).\nspecialize (Hy (ball_norm y (pos_div_2 eps)) (locally_ball_norm _ _)).\nunfold filtermapi in Hx, Hy.\napply Rnot_le_lt.\nintros H.\napply (@filter_not_empty _ F FF).\napply: filter_imp (filter_and _ _ (filter_and _ _ Hx Hy) Hf).\nclear -H.\nintros z [[[x' [Hx Bx]] [y' [Hy By]]] Hf].\napply: Rlt_not_le H.\nrewrite (double_var eps).\nchange (eps / 2) with (pos (pos_div_2 eps)).\napply ball_norm_triangle with (1 := Bx).\napply ball_norm_sym.\nnow rewrite (Hf _ _ Hx Hy).\nQed.\n\nEnd NormedModule2.\n\n(** Rings with absolute values are normed modules *)\n\nSection AbsRing_NormedModule.\n\nVariable (K : AbsRing).\n\nCanonical AbsRing_NormedModuleAux :=\n NormedModuleAux.Pack K K (NormedModuleAux.Class _ _ (ModuleSpace.class _ (AbsRing_ModuleSpace K)) (UniformSpace.class (AbsRing_UniformSpace K))) K.\n\nLemma AbsRing_norm_compat2 :\n forall (x y : AbsRing_NormedModuleAux) (eps : posreal),\n ball x eps y -> abs (minus y x) < 1 * eps.\nProof.\n intros x y eps H.\n now rewrite Rmult_1_l.\nQed.\n\nDefinition AbsRing_NormedModule_mixin :=\n NormedModule.Mixin K _ abs 1 abs_triangle abs_mult (fun x y e H => H) AbsRing_norm_compat2 abs_eq_zero.\n\nCanonical AbsRing_NormedModule :=\n NormedModule.Pack K _ (NormedModule.Class _ _ _ AbsRing_NormedModule_mixin) K.\n\nEnd AbsRing_NormedModule.\n\n(** Normed vector spaces have some continuous functions *)\n\nSection NVS_continuity.\n\nContext {K : AbsRing} {V : NormedModule K}.\n\nLemma filterlim_plus :\n forall x y : V,\n filterlim (fun z : V * V => plus (fst z) (snd z)) (filter_prod (locally x) (locally y)) (locally (plus x y)).\nProof.\nintros x y.\napply (filterlim_filter_le_1 (F := filter_prod (locally_norm x) (locally_norm y))).\n intros P [Q R LQ LR H].\n exists Q R.\n now apply locally_le_locally_norm.\n now apply locally_le_locally_norm.\n exact H.\napply (filterlim_filter_le_2 (G := locally_norm (plus x y))).\n apply locally_norm_le_locally.\nintros P [eps HP].\nexists (ball_norm x (pos_div_2 eps)) (ball_norm y (pos_div_2 eps)).\nby apply locally_norm_ball_norm.\nby apply locally_norm_ball_norm.\nintros u v Hu Hv.\napply HP.\nrewrite /ball_norm /= (double_var eps).\napply Rle_lt_trans with (2 := Rplus_lt_compat _ _ _ _ Hu Hv).\napply Rle_trans with (2 := norm_triangle _ _).\napply Req_le, f_equal.\nrewrite /minus /= opp_plus -2!plus_assoc.\napply f_equal.\nrewrite 2!plus_assoc.\napply f_equal2.\nby apply plus_comm.\nby [].\nQed.\n\nLemma filterlim_scal (k : K) (x : V) :\n filterlim (fun z => scal (fst z) (snd z)) (filter_prod (locally k) (locally x)) (locally (scal k x)).\nProof.\n apply filterlim_locally => /= eps.\n eapply filter_imp.\n move => /= u Hu.\n rewrite (double_var eps).\n apply ball_triangle with (scal (fst u) x).\n apply norm_compat1.\n rewrite -scal_minus_distr_r.\n eapply Rle_lt_trans.\n apply norm_scal.\n eapply Rle_lt_trans.\n apply Rmult_le_compat_l.\n by apply abs_ge_0.\n apply Rlt_le, Rlt_plus_1.\n apply <- Rlt_div_r.\n 2: apply Rle_lt_0_plus_1, norm_ge_0.\n by eapply (proj1 Hu).\n apply norm_compat1.\n rewrite -scal_minus_distr_l.\n eapply Rle_lt_trans.\n apply norm_scal.\n eapply Rle_lt_trans.\n apply Rmult_le_compat_r.\n by apply norm_ge_0.\n replace (fst u) with (plus k (minus (fst u) k)).\n eapply Rle_trans.\n apply abs_triangle.\n apply Rplus_le_compat_l.\n apply Rlt_le.\n instantiate (1 := 1).\n eapply (proj1 (proj2 Hu)).\n by rewrite plus_comm -plus_assoc plus_opp_l plus_zero_r.\n rewrite Rmult_comm.\n apply <- Rlt_div_r.\n 2: apply Rle_lt_0_plus_1, abs_ge_0.\n by apply (proj2 (proj2 Hu)).\n\n repeat apply filter_and.\n\n assert (Hd : 0 < eps / 2 / (norm x + 1)).\n apply Rdiv_lt_0_compat.\n by apply is_pos_div_2.\n apply Rle_lt_0_plus_1, norm_ge_0.\n eexists.\n apply (locally_ball_norm (V := AbsRing_NormedModule K) _ (mkposreal _ Hd)).\n apply filter_true.\n by [].\n\n eexists.\n apply (locally_ball_norm (V := AbsRing_NormedModule K) _ (mkposreal _ Rlt_0_1)).\n apply filter_true.\n by [].\n\n assert (Hd : 0 < eps / 2 / (abs k + 1)).\n apply Rdiv_lt_0_compat.\n by apply is_pos_div_2.\n apply Rle_lt_0_plus_1, abs_ge_0.\n eexists.\n apply filter_true.\n apply (locally_ball_norm _ (mkposreal _ Hd)).\n by [].\nQed.\nLemma filterlim_scal_r (k : K) (x : V) :\n filterlim (fun z : V => scal k z) (locally x) (locally (scal k x)).\nProof.\n eapply filterlim_comp_2.\n by apply filterlim_const.\n by apply filterlim_id.\n by apply filterlim_scal.\nQed.\nLemma filterlim_scal_l (k : K) (x : V) :\n filterlim (fun z => scal z x) (locally k) (locally (scal k x)).\nProof.\n eapply filterlim_comp_2.\n by apply filterlim_id.\n by apply filterlim_const.\n by apply filterlim_scal.\nQed.\n\nLemma filterlim_opp :\n forall x : V,\n filterlim opp (locally x) (locally (opp x)).\nProof.\nintros x.\nrewrite -scal_opp_one.\napply filterlim_ext with (2 := filterlim_scal_r _ _).\napply: scal_opp_one.\nQed.\n\nEnd NVS_continuity.\n\nLemma filterlim_mult {K : AbsRing} (x y : K) :\n filterlim (fun z => mult (fst z) (snd z)) (filter_prod (locally x) (locally y)) (locally (mult x y)).\nProof.\n by apply @filterlim_scal.\nQed.\n\nLemma filterlim_locally_ball_norm :\n forall {K : AbsRing} {T} {U : NormedModule K} {F : (T -> Prop) -> Prop} {FF : Filter F} (f : T -> U) (y : U),\n filterlim f F (locally y) <-> forall eps : posreal, F (fun x => ball_norm y eps (f x)).\nProof.\nintros K T U F FF f y.\nsplit.\n- intros Cf eps.\n apply (Cf (fun x => ball_norm y eps x)).\n apply locally_le_locally_norm.\n apply locally_norm_ball_norm.\n- intros Cf.\n apply (filterlim_filter_le_2 _ (locally_norm_le_locally y)).\n intros P [eps He].\n apply: filter_imp (Cf eps).\n intros t.\n apply He.\nQed.\n\n(** ** Complete Normed Modules *)\n\nModule CompleteNormedModule.\n\nSection ClassDef.\n\nVariable K : AbsRing.\n\nRecord class_of (T : Type) := Class {\n base : NormedModule.class_of K T ;\n mixin : CompleteSpace.mixin_of (UniformSpace.Pack T base T)\n}.\nLocal Coercion base : class_of >-> NormedModule.class_of.\nDefinition base2 T (cT : class_of T) : CompleteSpace.class_of T :=\n CompleteSpace.Class _ (base T cT) (mixin T cT).\nLocal Coercion base2 : class_of >-> CompleteSpace.class_of.\n\nStructure type := Pack { sort; _ : class_of sort ; _ : Type }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariable cT : type.\n\nDefinition class := let: Pack _ c _ := cT return class_of cT in c.\n\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition AbelianGroup := AbelianGroup.Pack cT xclass xT.\nDefinition ModuleSpace := ModuleSpace.Pack _ cT xclass xT.\nDefinition NormedModuleAux := NormedModuleAux.Pack _ cT xclass xT.\nDefinition NormedModule := NormedModule.Pack _ cT xclass xT.\nDefinition UniformSpace := UniformSpace.Pack cT xclass xT.\nDefinition CompleteSpace := CompleteSpace.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> NormedModule.class_of.\nCoercion mixin : class_of >-> CompleteSpace.mixin_of.\nCoercion base2 : class_of >-> CompleteSpace.class_of.\nCoercion sort : type >-> Sortclass.\nCoercion AbelianGroup : type >-> AbelianGroup.type.\nCanonical AbelianGroup.\nCoercion ModuleSpace : type >-> ModuleSpace.type.\nCanonical ModuleSpace.\nCoercion NormedModuleAux : type >-> NormedModuleAux.type.\nCanonical NormedModuleAux.\nCoercion NormedModule : type >-> NormedModule.type.\nCanonical NormedModule.\nCoercion UniformSpace : type >-> UniformSpace.type.\nCanonical UniformSpace.\nCoercion CompleteSpace : type >-> CompleteSpace.type.\nCanonical CompleteSpace.\nNotation CompleteNormedModule := type.\n\nEnd Exports.\n\nEnd CompleteNormedModule.\n\nExport CompleteNormedModule.Exports.\n\nSection CompleteNormedModule1.\n\nContext {K : AbsRing} {V : CompleteNormedModule K}.\n\nLemma iota_unique :\n forall (P : V -> Prop) (x : V),\n (forall y, P y -> y = x) ->\n P x ->\n iota P = x.\nProof.\nintros P x HP Px.\napply eq_close.\nintros eps.\napply: iota_correct_weak Px eps.\nintros x' y Px' Py eps.\nrewrite (HP _ Py) -(HP _ Px').\napply ball_center.\nQed.\n\nLemma iota_correct :\n forall P : V -> Prop,\n (exists! x : V, P x) ->\n P (iota P).\nProof.\nintros P [x [Px HP]].\nrewrite (iota_unique _ x) ; try exact Px.\nintros y Py.\nnow apply sym_eq, HP.\nQed.\n\nLemma iota_is_filter_lim {F} {FF : ProperFilter' F} (l : V) :\n is_filter_lim F l ->\n iota (is_filter_lim F) = l.\nProof.\nintros Hl.\napply: iota_unique (Hl) => l' Hl'.\nexact: is_filter_lim_unique Hl' Hl.\nQed.\n\nContext {T : Type}.\n\nLemma iota_filterlim_locally {F} {FF : ProperFilter' F} (f : T -> V) l :\n filterlim f F (locally l) ->\n iota (fun x => filterlim f F (locally x)) = l.\nProof.\napply iota_is_filter_lim.\nQed.\n\nLemma iota_filterlimi_locally {F} {FF : ProperFilter' F} (f : T -> V -> Prop) l :\n F (fun x => forall y1 y2, f x y1 -> f x y2 -> y1 = y2) ->\n filterlimi f F (locally l) ->\n iota (fun x => filterlimi f F (locally x)) = l.\nProof.\nintros Hf Hl.\napply: iota_unique (Hl) => l' Hl'.\nexact: filterlimi_locally_unique Hf Hl' Hl.\nQed.\n\nEnd CompleteNormedModule1.\n\n(** * Extended Types *)\n\n(** ** Pairs *)\n\nSection prod_AbelianGroup.\n\nContext {U V : AbelianGroup}.\n\nDefinition prod_plus (x y : U * V) :=\n (plus (fst x) (fst y), plus (snd x) (snd y)).\n\nDefinition prod_opp (x : U * V) :=\n (opp (fst x), opp (snd x)).\n\nDefinition prod_zero : U * V := (zero, zero).\n\nLemma prod_plus_comm :\n forall x y : U * V,\n prod_plus x y = prod_plus y x.\nProof.\nintros x y.\napply (f_equal2 pair) ; apply plus_comm.\nQed.\n\nLemma prod_plus_assoc :\n forall x y z : U * V,\n prod_plus x (prod_plus y z) = prod_plus (prod_plus x y) z.\nProof.\nintros x y z.\napply (f_equal2 pair) ; apply plus_assoc.\nQed.\n\nLemma prod_plus_zero_r :\n forall x : U * V,\n prod_plus x prod_zero = x.\nProof.\nintros [u v].\napply (f_equal2 pair) ; apply plus_zero_r.\nQed.\n\nLemma prod_plus_opp_r :\n forall x : U * V,\n prod_plus x (prod_opp x) = prod_zero.\nProof.\nintros x.\napply (f_equal2 pair) ; apply plus_opp_r.\nQed.\n\nEnd prod_AbelianGroup.\n\nDefinition prod_AbelianGroup_mixin (U V : AbelianGroup) :=\n AbelianGroup.Mixin (U * V) _ _ _ prod_plus_comm prod_plus_assoc prod_plus_zero_r prod_plus_opp_r.\n\nCanonical prod_AbelianGroup (U V : AbelianGroup) :=\n AbelianGroup.Pack (U * V) (prod_AbelianGroup_mixin U V) (U * V).\n\nSection prod_UniformSpace.\n\nContext {U V : UniformSpace}.\n\nDefinition prod_ball (x : U * V) (eps : R) (y : U * V) :=\n ball (fst x) eps (fst y) /\\ ball (snd x) eps (snd y).\n\nLemma prod_ball_center :\n forall (x : U * V) (eps : posreal),\n prod_ball x eps x.\nProof.\nintros x eps.\nsplit ; apply ball_center.\nQed.\n\nLemma prod_ball_sym :\n forall (x y : U * V) (eps : R),\n prod_ball x eps y -> prod_ball y eps x.\nProof.\nintros x y eps [H1 H2].\nsplit ; now apply ball_sym.\nQed.\n\nLemma prod_ball_triangle :\n forall (x y z : U * V) (e1 e2 : R),\n prod_ball x e1 y -> prod_ball y e2 z ->\n prod_ball x (e1 + e2) z.\nProof.\nintros x y z e1 e2 [H1 H2] [H3 H4].\nsplit ; eapply ball_triangle ; eassumption.\nQed.\n\n\nEnd prod_UniformSpace.\n\nDefinition prod_UniformSpace_mixin (U V : UniformSpace) :=\n UniformSpace.Mixin (U * V) (point_of, point_of) _ prod_ball_center prod_ball_sym prod_ball_triangle.\n\nCanonical prod_UniformSpace (U V : UniformSpace) :=\n UniformSpace.Pack (U * V) (prod_UniformSpace_mixin U V) (U * V).\n\nSection prod_ModuleSpace.\n\nContext {K : Ring} {U V : ModuleSpace K}.\n\nDefinition prod_scal (x : K) (u : U * V) :=\n (scal x (fst u), scal x (snd u)).\n\nLemma prod_scal_assoc :\n forall (x y : K) (u : U * V),\n prod_scal x (prod_scal y u) = prod_scal (mult x y) u.\nProof.\nintros x y u.\napply (f_equal2 pair) ; apply scal_assoc.\nQed.\n\nLemma prod_scal_one :\n forall u : U * V,\n prod_scal one u = u.\nProof.\nintros [u v].\napply (f_equal2 pair) ; apply scal_one.\nQed.\n\nLemma prod_scal_distr_l :\n forall (x : K) (u v : U * V),\n prod_scal x (prod_plus u v) = prod_plus (prod_scal x u) (prod_scal x v).\nProof.\nintros x u v.\napply (f_equal2 pair) ; apply scal_distr_l.\nQed.\n\nLemma prod_scal_distr_r :\n forall (x y : K) (u : U * V),\n prod_scal (plus x y) u = prod_plus (prod_scal x u) (prod_scal y u).\nProof.\nintros x y u.\napply (f_equal2 pair) ; apply scal_distr_r.\nQed.\n\nEnd prod_ModuleSpace.\n\nDefinition prod_ModuleSpace_mixin (K : Ring) (U V : ModuleSpace K) :=\n ModuleSpace.Mixin K _ _ (@prod_scal_assoc K U V) prod_scal_one prod_scal_distr_l prod_scal_distr_r.\n\nCanonical prod_ModuleSpace (K : Ring) (U V : ModuleSpace K) :=\n ModuleSpace.Pack K (U * V) (ModuleSpace.Class _ _ _ (prod_ModuleSpace_mixin K U V)) (U * V).\n\nCanonical prod_NormedModuleAux (K : AbsRing) (U V : NormedModuleAux K) :=\n NormedModuleAux.Pack K (U * V) (NormedModuleAux.Class _ _ (ModuleSpace.class K _) (UniformSpace.class (prod_UniformSpace U V))) (U * V).\n\nLemma sqrt_plus_sqr :\n forall x y : R, Rmax (Rabs x) (Rabs y) <= sqrt (x ^ 2 + y ^ 2) <= sqrt 2 * Rmax (Rabs x) (Rabs y).\nProof.\nintros x y.\nsplit.\n- rewrite -!sqrt_Rsqr_abs.\n apply Rmax_case ; apply sqrt_le_1_alt, Rminus_le_0 ;\n rewrite /Rsqr /= ; ring_simplify ; by apply pow2_ge_0.\n- apply Rmax_case_strong ; intros H0 ;\n rewrite -!sqrt_Rsqr_abs ;\n rewrite -?sqrt_mult ;\n try (by apply Rle_0_sqr) ;\n try (by apply Rlt_le, Rlt_0_2) ;\n apply sqrt_le_1_alt ; simpl ; [ rewrite Rplus_comm | ] ;\n rewrite /Rsqr ; apply Rle_minus_r ; ring_simplify ;\n apply Rsqr_le_abs_1 in H0 ; by rewrite /pow !Rmult_1_r.\nQed.\n\nSection prod_NormedModule.\n\nContext {K : AbsRing} {U V : NormedModule K}.\n\nDefinition prod_norm (x : U * V) :=\n sqrt (norm (fst x) ^ 2 + norm (snd x) ^ 2).\n\nLemma prod_norm_triangle :\n forall x y : U * V,\n prod_norm (plus x y) <= prod_norm x + prod_norm y.\nProof.\nintros [xu xv] [yu yv].\nrewrite /prod_norm /= !Rmult_1_r.\napply Rle_trans with (sqrt (Rsqr (norm xu + norm yu) + Rsqr (norm xv + norm yv))).\n- apply sqrt_le_1_alt.\n apply Rplus_le_compat.\n apply Rsqr_le_abs_1.\n rewrite -> 2!Rabs_pos_eq.\n apply: norm_triangle.\n apply Rplus_le_le_0_compat ; apply norm_ge_0.\n apply norm_ge_0.\n apply Rsqr_le_abs_1.\n rewrite -> 2!Rabs_pos_eq.\n apply: norm_triangle.\n apply Rplus_le_le_0_compat ; apply norm_ge_0.\n apply norm_ge_0.\n- apply Rsqr_incr_0_var.\n apply Rminus_le_0.\n unfold Rsqr ; simpl ; ring_simplify.\n rewrite /pow ?Rmult_1_r.\n rewrite ?sqrt_sqrt ; ring_simplify.\n replace (-2 * norm xu * norm yu - 2 * norm xv * norm yv)\n with (-(2 * (norm xu * norm yu + norm xv * norm yv))) by ring.\n rewrite Rmult_assoc -sqrt_mult.\n rewrite Rplus_comm.\n apply -> Rminus_le_0.\n apply Rmult_le_compat_l.\n apply Rlt_le, Rlt_0_2.\n apply Rsqr_incr_0_var.\n apply Rminus_le_0.\n rewrite /Rsqr ?sqrt_sqrt ; ring_simplify.\n replace (norm xu ^ 2 * norm yv ^ 2 - 2 * norm xu * norm xv * norm yu * norm yv + norm xv ^ 2 * norm yu ^ 2)\n with ((norm xu * norm yv - norm xv * norm yu) ^ 2) by ring.\n apply pow2_ge_0.\n repeat apply Rplus_le_le_0_compat ; apply Rmult_le_pos ; apply pow2_ge_0.\n apply sqrt_pos.\n apply Rplus_le_le_0_compat ; apply Rle_0_sqr.\n apply Rplus_le_le_0_compat ; apply Rle_0_sqr.\n replace (norm xu ^ 2 + 2 * norm xu * norm yu + norm yu ^ 2 + norm xv ^ 2 + 2 * norm xv * norm yv + norm yv ^ 2)\n with ((norm xu + norm yu) ^ 2 + (norm xv + norm yv) ^ 2) by ring.\n apply Rplus_le_le_0_compat ; apply pow2_ge_0.\n apply Rplus_le_le_0_compat ; apply pow2_ge_0.\n apply Rplus_le_le_0_compat ; apply pow2_ge_0.\n apply Rplus_le_le_0_compat ; apply sqrt_pos.\nQed.\n\nLemma prod_norm_scal :\n forall (l : K) (x : U * V),\n prod_norm (scal l x) <= abs l * prod_norm x.\nProof.\nintros l [xu xv].\nrewrite /prod_norm /= -(sqrt_Rsqr (abs l)).\n2: apply abs_ge_0.\nrewrite !Rmult_1_r.\nrewrite -sqrt_mult.\n2: apply Rle_0_sqr.\napply sqrt_le_1_alt.\nrewrite Rmult_plus_distr_l.\nunfold Rsqr.\napply Rplus_le_compat.\nreplace (abs l * abs l * (norm xu * norm xu)) with ((abs l * norm xu) * (abs l * norm xu)) by ring.\napply Rmult_le_compat.\napply norm_ge_0.\napply norm_ge_0.\nexact (norm_scal l xu).\nexact (norm_scal l xu).\nreplace (abs l * abs l * (norm xv * norm xv)) with ((abs l * norm xv) * (abs l * norm xv)) by ring.\napply Rmult_le_compat.\napply norm_ge_0.\napply norm_ge_0.\nexact (norm_scal l xv).\nexact (norm_scal l xv).\napply Rplus_le_le_0_compat ; apply Rle_0_sqr.\nQed.\n\nLemma prod_norm_compat1 :\n forall (x y : U * V) (eps : R),\n prod_norm (minus y x) < eps -> ball x eps y.\nProof.\nintros [xu xv] [yu yv] eps H.\ngeneralize (Rle_lt_trans _ _ _ (proj1 (sqrt_plus_sqr _ _)) H).\nrewrite -> !Rabs_pos_eq by apply norm_ge_0.\nintros H'.\nsplit ;\n apply norm_compat1 ;\n apply Rle_lt_trans with (2 := H').\napply Rmax_l.\napply Rmax_r.\nQed.\n\nDefinition prod_norm_factor :=\n sqrt 2 * Rmax (@norm_factor K U) (@norm_factor K V).\n\nLemma prod_norm_compat2 :\n forall (x y : U * V) (eps : posreal),\n ball x eps y ->\n prod_norm (minus y x) < prod_norm_factor * eps.\nProof.\nintros [xu xv] [yu yv] eps [Bu Bv].\napply Rle_lt_trans with (1 := proj2 (sqrt_plus_sqr _ _)).\nsimpl.\nrewrite Rmult_assoc.\napply Rmult_lt_compat_l.\napply sqrt_lt_R0.\napply Rlt_0_2.\nrewrite -> !Rabs_pos_eq by apply norm_ge_0.\nrewrite Rmax_mult.\napply Rmax_case.\napply Rlt_le_trans with (2 := Rmax_l _ _).\nnow apply norm_compat2.\napply Rlt_le_trans with (2 := Rmax_r _ _).\nnow apply norm_compat2.\napply Rlt_le.\napply cond_pos.\nQed.\n\nLemma prod_norm_eq_zero :\n forall x : U * V,\n prod_norm x = 0 -> x = zero.\nProof.\nintros [xu xv] H.\napply sqrt_eq_0 in H.\nrewrite !(pow_Rsqr _ 1) !pow_1 in H.\napply Rplus_sqr_eq_0 in H.\ndestruct H as [H1 H2].\napply norm_eq_zero in H1.\napply norm_eq_zero in H2.\nsimpl in H1, H2.\nnow rewrite H1 H2.\napply Rplus_le_le_0_compat ; apply pow2_ge_0.\nQed.\n\nEnd prod_NormedModule.\n\nDefinition prod_NormedModule_mixin (K : AbsRing) (U V : NormedModule K) :=\n NormedModule.Mixin K _ (@prod_norm K U V) prod_norm_factor prod_norm_triangle\n prod_norm_scal prod_norm_compat1 prod_norm_compat2 prod_norm_eq_zero.\n\nCanonical prod_NormedModule (K : AbsRing) (U V : NormedModule K) :=\n NormedModule.Pack K (U * V) (NormedModule.Class K (U * V) _ (prod_NormedModule_mixin K U V)) (U * V).\n\nLemma norm_prod {K : AbsRing}\n {U : NormedModule K} {V : NormedModule K}\n (x : U) (y : V) :\n Rmax (norm x) (norm y) <= norm (x,y) <= sqrt 2 * Rmax (norm x) (norm y).\nProof.\n rewrite -(Rabs_pos_eq (norm x)).\n rewrite -(Rabs_pos_eq (norm y)).\n apply sqrt_plus_sqr.\n by apply norm_ge_0.\n by apply norm_ge_0.\nQed.\n\n(** ** Iterated Products *)\n\nFixpoint Tn (n : nat) (T : Type) : Type :=\n match n with\n | O => unit\n | S n => prod T (Tn n T)\n end.\n\nNotation \"[ x1 , .. , xn ]\" := (pair x1 .. (pair xn tt) .. ).\n\nFixpoint mk_Tn {T} (n : nat) (u : nat -> T) : Tn n T :=\n match n with\n | O => (tt : Tn O T)\n | S n => (u O, mk_Tn n (fun n => u (S n)))\n end.\nFixpoint coeff_Tn {T} {n : nat} (x0 : T) : (Tn n T) -> nat -> T :=\n match n with\n | O => fun (_ : Tn O T) (_ : nat) => x0\n | S n' => fun (v : Tn (S n') T) (i : nat) => match i with\n | O => fst v\n | S i => coeff_Tn x0 (snd v) i\n end\n end.\nLemma mk_Tn_bij {T} {n : nat} (x0 : T) (v : Tn n T) :\n mk_Tn n (coeff_Tn x0 v) = v.\nProof.\n induction n ; simpl.\n now apply unit_ind.\n rewrite IHn ; by destruct v.\nQed.\nLemma coeff_Tn_bij {T} {n : nat} (x0 : T) (u : nat -> T) :\n forall i, (i < n)%nat -> coeff_Tn x0 (mk_Tn n u) i = u i.\nProof.\n revert u ; induction n => /= u i Hi.\n by apply lt_n_O in Hi.\n destruct i.\n by [].\n now apply (IHn (fun n => u (S n))), lt_S_n.\nQed.\nLemma coeff_Tn_ext {T} {n : nat} (x1 x2 : T) (v1 v2 : Tn n T) :\n v1 = v2 <-> forall i, (i < n)%nat -> coeff_Tn x1 v1 i = coeff_Tn x2 v2 i.\nProof.\n split.\n + move => -> {v1}.\n induction n => i Hi.\n by apply lt_n_O in Hi.\n destruct i ; simpl.\n by [].\n by apply IHn, lt_S_n.\n + induction n => H.\n apply unit_ind ; move: (v1) ; now apply unit_ind.\n apply injective_projections.\n by apply (H O), lt_O_Sn.\n apply IHn => i Hi.\n by apply (H (S i)), lt_n_S.\nQed.\nLemma mk_Tn_ext {T} (n : nat) (u1 u2 : nat -> T) :\n (forall i, (i < n)%nat -> (u1 i) = (u2 i))\n <-> (mk_Tn n u1) = (mk_Tn n u2).\nProof.\n move: u1 u2 ; induction n ; simpl ; split ; intros.\n by [].\n by apply lt_n_O in H0.\n apply f_equal2.\n by apply H, lt_O_Sn.\n apply IHn => i Hi.\n by apply H, lt_n_S.\n destruct i.\n by apply (f_equal (@fst _ _)) in H.\n move: i {H0} (lt_S_n _ _ H0).\n apply IHn.\n by apply (f_equal (@snd _ _)) in H.\nQed.\n\n(*\nGlobal Instance AbelianGroup_Tn {T} :\n AbelianGroup T -> forall n, AbelianGroup (Tn n T) | 10.\nProof.\n intro GT.\n elim => /= [ | n IH].\n - apply Build_AbelianGroup with (fun _ _ => tt) (fun _ => tt) tt ; auto.\n by apply unit_ind.\n - by apply AbelianGroup_prod.\nDefined.\n\nGlobal Instance MetricBall_Tn :\n forall T, MetricBall T -> forall n, MetricBall (Tn n T) | 10.\nProof.\nintros T MT n.\nelim: n => [ | n MTn].\nby apply Build_MetricBall with (fun _ _ _ => True).\nby apply MetricBall_prod.\nDefined.\n\nGlobal Instance VectorSpace_mixin_Tn {T} {K} {FK : Ring K} :\n forall GT : AbelianGroup T,\n VectorSpace_mixin T K GT ->\n forall n, VectorSpace_mixin (Tn n T) K (AbelianGroup_Tn GT n) | 10.\nProof.\n intros GT VV.\n elim => [ | n VVn].\n apply Build_VectorSpace_mixin with (fun _ _ => tt) ; by apply unit_ind.\n by apply VectorSpace_mixin_prod.\nDefined.\n\nGlobal Instance VectorSpace_Tn {T} {K} {FK : Ring K} :\n VectorSpace T K -> forall n, VectorSpace (Tn n T) K | 10.\nProof.\n intros VV n.\n apply Build_VectorSpace with (AbelianGroup_Tn _ n).\n now apply VectorSpace_mixin_Tn, VV.\nDefined.\n\nGlobal Instance NormedVectorSpace_Tn {T} {K} {FK : AbsRing K} :\n NormedVectorSpace T K ->\n forall n, NormedVectorSpace (Tn n T) K | 10.\nProof.\n move => VT.\n elim => [ | n NVTn].\n - econstructor.\n apply Build_NormedVectorSpace_mixin with (fun _ => 0).\n move => _ _.\n rewrite Rplus_0_l ; by apply Rle_refl.\n move => l _ ; rewrite Rmult_0_r ; by apply Rle_refl.\n easy.\n exists (mkposreal _ Rlt_0_1).\n intros x y eps _.\n rewrite Rmult_1_l.\n apply cond_pos.\n - by apply NormedVectorSpace_prod.\nDefined.\n*)\n\n(** *)\n\nFixpoint Fn (n : nat) (T U : Type) : Type :=\n match n with\n | O => U\n | S n => T -> Fn n T U\n end.\n\n(*\nGlobal Instance MetricBall_Fn {T M} (n : nat) :\n MetricBall M -> MetricBall (Fn n T M) | 10.\nProof.\n intros MM.\n elim: n => /= [ | n IHn].\n exact MM.\n exact (MetricBall_fct IHn).\nDefined.\n*)\n\n(** ** Matrices *)\n\nSection Matrices.\n\nContext {T : Type}.\n\nDefinition matrix (m n : nat) := Tn m (Tn n T).\n\nDefinition coeff_mat {m n : nat} (x0 : T) (A : matrix m n) (i j : nat) :=\n coeff_Tn x0 (coeff_Tn (mk_Tn _ (fun _ => x0)) A i) j.\n\nDefinition mk_matrix (m n : nat) (U : nat -> nat -> T) : matrix m n :=\n mk_Tn m (fun i => (mk_Tn n (U i))).\n\nLemma mk_matrix_bij {m n : nat} (x0 : T) (A : matrix m n) :\n mk_matrix m n (coeff_mat x0 A) = A.\nProof.\n unfold mk_matrix, coeff_mat.\n unfold matrix in A.\n rewrite -{2}(mk_Tn_bij (mk_Tn _ (fun _ => x0)) A).\n apply mk_Tn_ext.\n intros i Hi.\n by rewrite mk_Tn_bij.\nQed.\n\nLemma coeff_mat_bij {m n : nat} (x0 : T) (u : nat -> nat -> T) :\n forall i j, (i < m)%nat -> (j < n)%nat -> coeff_mat x0 (mk_matrix m n u) i j = u i j.\nProof.\n intros i j Hi Hj.\n unfold mk_matrix, coeff_mat.\n by rewrite 2?coeff_Tn_bij .\nQed.\n\nLemma coeff_mat_ext_aux {m n : nat} (x1 x2 : T) (v1 v2 : matrix m n) :\n v1 = v2 <-> forall i j, (i < m)%nat -> (j < n)%nat -> (coeff_mat x1 v1 i j) = (coeff_mat x2 v2 i j).\nProof.\n split => Hv.\n + move => i j Hi Hj.\n by repeat apply coeff_Tn_ext.\n + unfold matrix in v1, v2.\n rewrite -(mk_matrix_bij x1 v1) -(mk_matrix_bij x2 v2).\n unfold mk_matrix.\n apply mk_Tn_ext => i Hi.\n apply mk_Tn_ext => j Hj.\n by apply Hv.\nQed.\n\nLemma coeff_mat_ext {m n : nat} (x0 : T) (v1 v2 : matrix m n) :\n v1 = v2 <-> forall i j, (coeff_mat x0 v1 i j) = (coeff_mat x0 v2 i j).\nProof.\n split.\n by move => ->.\n intro H.\n now apply (coeff_mat_ext_aux x0 x0 v1 v2).\nQed.\n\nLemma mk_matrix_ext (m n : nat) (u1 u2 : nat -> nat -> T) :\n (forall i j, (i < m)%nat -> (j < n)%nat -> (u1 i j) = (u2 i j))\n <-> (mk_matrix m n u1) = (mk_matrix m n u2).\nProof.\n split => H.\n + apply (mk_Tn_ext m) => i Hi.\n apply (mk_Tn_ext n) => j Hj.\n by apply H.\n + intros i j Hi Hj.\n apply (mk_Tn_ext n).\n apply (mk_Tn_ext m (fun i => mk_Tn n (u1 i)) (fun i => mk_Tn n (u2 i))).\n apply H.\n by [].\n by [].\nQed.\n\nEnd Matrices.\n\nSection MatrixGroup.\n\nContext {G : AbelianGroup} {m n : nat}.\n\nDefinition Mzero := mk_matrix m n (fun i j => @zero G).\n\nDefinition Mplus (A B : @matrix G m n) :=\n mk_matrix m n (fun i j => plus (coeff_mat zero A i j) (coeff_mat zero B i j)).\n\nDefinition Mopp (A : @matrix G m n) :=\n mk_matrix m n (fun i j => opp (coeff_mat zero A i j)).\n\nLemma Mplus_comm :\n forall A B : @matrix G m n,\n Mplus A B = Mplus B A.\nProof.\n intros A B.\n apply mk_matrix_ext => i j Hi Hj.\n by apply plus_comm.\nQed.\n\nLemma Mplus_assoc :\n forall A B C : @matrix G m n,\n Mplus A (Mplus B C) = Mplus (Mplus A B) C.\nProof.\n intros A B C.\n apply mk_matrix_ext => /= i j Hi Hj.\n rewrite ?coeff_mat_bij => //.\n by apply plus_assoc.\nQed.\n\nLemma Mplus_zero_r :\n forall A : @matrix G m n,\n Mplus A Mzero = A.\nProof.\n intros A.\n apply (coeff_mat_ext_aux zero zero) => i j Hi Hj.\n rewrite ?coeff_mat_bij => //=.\n by apply plus_zero_r.\nQed.\n\nLemma Mplus_opp_r :\n forall A : @matrix G m n,\n Mplus A (Mopp A) = Mzero.\nProof.\n intros A.\n apply (coeff_mat_ext_aux zero zero) => i j Hi Hj.\n rewrite ?coeff_mat_bij => //=.\n by apply plus_opp_r.\nQed.\n\nDefinition matrix_AbelianGroup_mixin :=\n AbelianGroup.Mixin _ _ _ _ Mplus_comm Mplus_assoc Mplus_zero_r Mplus_opp_r.\n\nCanonical matrix_AbelianGroup :=\n AbelianGroup.Pack _ matrix_AbelianGroup_mixin (@matrix G m n).\n\nEnd MatrixGroup.\n\nSection MatrixRing.\n\nContext {T : Ring}.\n\nFixpoint Mone_seq i j : T :=\n match i,j with\n | O, O => one\n | O, S _ | S _, O => zero\n | S i, S j => Mone_seq i j end.\n\nDefinition Mone {n} : matrix n n :=\n mk_matrix n n Mone_seq.\n\nLemma Mone_seq_diag :\n forall i j : nat, i = j -> Mone_seq i j = @one T.\nProof.\n move => i j <- {j}.\n by induction i.\nQed.\nLemma Mone_seq_not_diag :\n forall i j : nat, i <> j -> Mone_seq i j = @zero T.\nProof.\n elim => //= [ | i IHi] j Hij ;\n destruct j => //=.\n apply IHi.\n contradict Hij.\n by rewrite Hij.\nQed.\n\nDefinition Mmult {n m k} (A : @matrix T n m) (B : @matrix T m k) :=\n mk_matrix n k (fun i j => sum_n (fun l => mult (coeff_mat zero A i l) (coeff_mat zero B l j)) (pred m)).\n\nLemma Mmult_assoc {n m k l} :\n forall (A : matrix n m) (B : matrix m k) (C : matrix k l),\n Mmult A (Mmult B C) = Mmult (Mmult A B) C.\nProof.\n intros A B C.\n apply mk_matrix_ext => n' l' Hn' Hl'.\n unfold Mmult at 1.\n - transitivity (sum_n (fun l0 : nat => mult (coeff_mat zero A n' l0)\n (sum_n (fun l1 : nat => mult (coeff_mat zero B l0 l1) (coeff_mat zero C l1 l')) (pred k))) (pred m)).\n destruct m ; simpl.\n unfold coeff_mat ; simpl.\n by rewrite 2!mult_zero_l.\n apply sum_n_m_ext_loc ; simpl => m' [ _ Hm'].\n apply f_equal.\n rewrite coeff_mat_bij //.\n by apply le_lt_n_Sm, Hm'.\n - transitivity (sum_n (fun l0 : nat => sum_n\n (fun l1 : nat => mult (coeff_mat zero A n' l0) (mult (coeff_mat zero B l0 l1) (coeff_mat zero C l1 l'))) (pred k)) (pred m)).\n destruct m ; simpl.\n rewrite /sum_n !sum_n_n.\n unfold coeff_mat ; simpl.\n rewrite mult_zero_l.\n rewrite sum_n_m_mult_l.\n by rewrite mult_zero_l.\n apply sum_n_m_ext_loc ; simpl => m' [_ Hm'].\n apply sym_eq, sum_n_m_mult_l.\n rewrite sum_n_switch.\n destruct k ; simpl.\n unfold coeff_mat ; simpl.\n rewrite mult_zero_l.\n rewrite /sum_n sum_n_m_mult_r.\n by rewrite mult_zero_r.\n apply sum_n_m_ext_loc => k' [_ Hk'].\n transitivity (mult (sum_n (fun l1 : nat => mult (coeff_mat zero A n' l1) (coeff_mat zero B l1 k')) (pred m))\n (coeff_mat zero C k' l')).\n rewrite -sum_n_m_mult_r.\n apply sum_n_m_ext_loc => m' [_ Hm'].\n apply mult_assoc.\n apply f_equal2.\n unfold Mmult ; rewrite coeff_mat_bij //.\n by apply le_lt_n_Sm.\n by [].\nQed.\n\nLemma Mmult_one_r {m n} :\n forall x : matrix m n, Mmult x Mone = x.\nProof.\n intros A.\n rewrite -{2}(mk_matrix_bij zero A).\n apply mk_matrix_ext => /= i j Hi Hj.\n destruct n ; simpl.\n by apply lt_n_O in Hj.\n move: (coeff_mat zero A) => {A} A.\n erewrite sum_n_ext_loc ; last first.\n move => /= k Hk.\n rewrite /Mone coeff_mat_bij //.\n by apply le_lt_n_Sm.\n rewrite /sum_n (sum_n_m_Chasles _ _ j) //.\n 2: by apply le_O_n.\n 2: by apply lt_n_Sm_le.\n rewrite (sum_n_m_ext_loc _ (fun _ => zero) (S j)).\n rewrite sum_n_m_const_zero plus_zero_r.\n rewrite -/(sum_n _ _).\n destruct j => //.\n by rewrite sum_O Mone_seq_diag // mult_one_r.\n rewrite sum_Sn.\n rewrite (sum_n_ext_loc _ (fun _ => zero)).\n rewrite /sum_n sum_n_m_const_zero plus_zero_l.\n by rewrite Mone_seq_diag // mult_one_r.\n move => k Hk.\n rewrite Mone_seq_not_diag.\n by apply mult_zero_r.\n by apply MyNat.lt_neq, le_lt_n_Sm.\n move => k [Hk _].\n rewrite Mone_seq_not_diag.\n by apply mult_zero_r.\n by apply sym_not_eq, MyNat.lt_neq.\nQed.\n\nLemma Mmult_one_l {m n} :\n forall x : matrix m n, Mmult Mone x = x.\nProof.\n intros A.\n rewrite -{2}(mk_matrix_bij zero A).\n apply mk_matrix_ext => /= i j Hi Hj.\n destruct m ; simpl.\n by apply lt_n_O in Hi.\n move: (coeff_mat zero A) => {A} A.\n erewrite sum_n_ext_loc ; last first.\n move => /= k Hk.\n rewrite /Mone coeff_mat_bij //.\n by apply le_lt_n_Sm.\n rewrite /sum_n (sum_n_m_Chasles _ _ i) //.\n 2: by apply le_O_n.\n 2: by apply lt_n_Sm_le.\n rewrite (sum_n_m_ext_loc _ (fun _ => zero) (S i)).\n rewrite sum_n_m_const_zero plus_zero_r.\n rewrite -/(sum_n _ _).\n destruct i => //.\n by rewrite sum_O Mone_seq_diag // mult_one_l.\n rewrite sum_Sn.\n rewrite (sum_n_ext_loc _ (fun _ => zero)).\n rewrite /sum_n sum_n_m_const_zero plus_zero_l.\n by rewrite Mone_seq_diag // mult_one_l.\n move => k Hk.\n rewrite Mone_seq_not_diag.\n by apply mult_zero_l.\n by apply sym_not_eq, MyNat.lt_neq, le_lt_n_Sm.\n move => k [Hk _].\n rewrite Mone_seq_not_diag.\n by apply mult_zero_l.\n by apply MyNat.lt_neq.\nQed.\n\nLemma Mmult_distr_r {m n k} :\n forall (A B : @matrix T m n) (C : @matrix T n k),\n Mmult (Mplus A B) C = Mplus (Mmult A C) (Mmult B C).\nProof.\n intros A B C.\n unfold Mmult, plus ; simpl ; unfold Mplus.\n apply mk_matrix_ext => i j Hi Hj.\n rewrite ?coeff_mat_bij => //=.\n rewrite -sum_n_m_plus.\n destruct n ; simpl.\n unfold coeff_mat ; simpl.\n by rewrite ?mult_zero_l plus_zero_l.\n apply sum_n_m_ext_loc => l [_ Hl].\n rewrite ?coeff_mat_bij => //=.\n by apply mult_distr_r.\n by apply le_lt_n_Sm.\nQed.\n\nLemma Mmult_distr_l {m n k} :\n forall (A : @matrix T m n) (B C : @matrix T n k),\n Mmult A (Mplus B C) = Mplus (Mmult A B) (Mmult A C).\nProof.\n intros A B C.\n unfold Mmult, plus ; simpl ; unfold Mplus.\n apply mk_matrix_ext => i j Hi Hj.\n rewrite ?coeff_mat_bij => //=.\n rewrite -sum_n_m_plus.\n destruct n ; simpl.\n unfold coeff_mat ; simpl.\n by rewrite ?mult_zero_l plus_zero_l.\n apply sum_n_m_ext_loc => l [_ Hl].\n rewrite ?coeff_mat_bij => //=.\n by apply mult_distr_l.\n by apply le_lt_n_Sm.\nQed.\n\nDefinition matrix_Ring_mixin {n} :=\n Ring.Mixin _ _ _ (@Mmult_assoc n n n n) Mmult_one_r Mmult_one_l Mmult_distr_r Mmult_distr_l.\n\nCanonical matrix_Ring {n} :=\n Ring.Pack (@matrix T n n) (Ring.Class _ _ matrix_Ring_mixin) (@matrix T n n).\n\nDefinition matrix_ModuleSpace_mixin {m n} :=\n ModuleSpace.Mixin (@matrix_Ring m) (@matrix_AbelianGroup T m n) Mmult\n Mmult_assoc Mmult_one_l Mmult_distr_l Mmult_distr_r.\n\nCanonical matrix_ModuleSpace {m n} :=\n ModuleSpace.Pack _ (@matrix T m n) (ModuleSpace.Class _ _ _ matrix_ModuleSpace_mixin) (@matrix T m n).\n\nEnd MatrixRing.\n\n(** * The topology on natural numbers *)\n\nDefinition eventually (P : nat -> Prop) :=\n exists N : nat, forall n, (N <= n)%nat -> P n.\n\nGlobal Instance eventually_filter : ProperFilter eventually.\nProof.\nconstructor.\n intros P [N H].\n exists N.\n apply H.\n apply le_refl.\nconstructor.\n- now exists 0%nat.\n- intros P Q [NP HP] [NQ HQ].\n exists (max NP NQ).\n intros n Hn.\n split.\n apply HP.\n apply le_trans with (2 := Hn).\n apply Max.le_max_l.\n apply HQ.\n apply le_trans with (2 := Hn).\n apply Max.le_max_r.\n- intros P Q H [NP HP].\n exists NP.\n intros n Hn.\n apply H.\n now apply HP.\nQed.\n\n(** * The topology on real numbers *)\n\nDefinition R_AbelianGroup_mixin :=\n AbelianGroup.Mixin _ _ _ _ Rplus_comm (fun x y z => sym_eq (Rplus_assoc x y z)) Rplus_0_r Rplus_opp_r.\n\nCanonical R_AbelianGroup :=\n AbelianGroup.Pack _ R_AbelianGroup_mixin R.\n\nDefinition R_Ring_mixin :=\n Ring.Mixin _ _ _ (fun x y z => sym_eq (Rmult_assoc x y z)) Rmult_1_r Rmult_1_l Rmult_plus_distr_r Rmult_plus_distr_l.\n\nCanonical R_Ring :=\n Ring.Pack R (Ring.Class _ _ R_Ring_mixin) R.\n\nLemma Rabs_m1 :\n Rabs (-1) = 1.\nProof.\n rewrite Rabs_Ropp.\n exact Rabs_R1.\nQed.\n\nDefinition R_AbsRing_mixin :=\n AbsRing.Mixin _ _ Rabs_R0 Rabs_m1 Rabs_triang (fun x y => Req_le _ _ (Rabs_mult x y)) Rabs_eq_0.\n\nCanonical R_AbsRing :=\n AbsRing.Pack R (AbsRing.Class _ _ R_AbsRing_mixin) R.\n\nDefinition R_UniformSpace_mixin :=\n AbsRing_UniformSpace_mixin R_AbsRing.\n\nCanonical R_UniformSpace :=\n UniformSpace.Pack R R_UniformSpace_mixin R.\n\nDefinition R_complete_lim (F : (R -> Prop) -> Prop) : R :=\n Lub_Rbar (fun x : R => F (ball (x + 1) (mkposreal _ Rlt_0_1))).\n\nLemma R_complete_ax1 :\n forall F : (R -> Prop) -> Prop,\n ProperFilter' F ->\n (forall eps : posreal, exists x : R, F (ball x eps)) ->\n forall eps : posreal, F (ball (R_complete_lim F) eps).\nProof.\nintros F FF HF eps.\nunfold R_complete_lim.\ngeneralize (Lub_Rbar_correct (fun x : R => F (ball (x + 1) (mkposreal _ Rlt_0_1)))).\ngeneralize (Lub_Rbar (fun x : R => F (ball (x + 1) (mkposreal _ Rlt_0_1)))).\nintros [x| |] [Hx1 Hx2].\n-\nset (eps' := pos_div_2 (mkposreal _ (Rmin_case _ _ _ Rlt_R0_R2 (cond_pos eps)))).\ndestruct (HF eps') as [z Hz].\nassert (H1 : z - Rmin 2 eps / 2 + 1 <= x + 1).\n apply Rplus_le_compat_r.\n apply Hx1.\n revert Hz.\n apply filter_imp.\n unfold ball ; simpl ; intros u Bu.\n apply (Rabs_lt_between' u z) in Bu.\n apply Rabs_lt_between'.\n clear -Bu.\n destruct Bu as [Bu1 Bu2].\n assert (H := Rmin_l 2 eps).\n split ; lra.\nassert (H2 : x + 1 <= z + Rmin 2 eps / 2 + 1).\n apply Rplus_le_compat_r.\n apply (Hx2 (Finite _)).\n intros v Hv.\n apply Rbar_not_lt_le => Hlt.\n apply filter_not_empty.\n generalize (filter_and _ _ Hz Hv).\n apply filter_imp.\n unfold ball ; simpl ; intros w [Hw1 Hw2].\n apply (Rabs_lt_between' w z) in Hw1.\n destruct Hw1 as [_ Hw1].\n apply (Rabs_lt_between' w (v + 1)) in Hw2.\n destruct Hw2 as [Hw2 _].\n clear -Hw1 Hw2 Hlt.\n simpl in Hw1, Hw2, Hlt.\n lra.\nrevert Hz.\napply filter_imp.\nunfold ball ; simpl ; intros u Hu.\napply (Rabs_lt_between' u z) in Hu.\napply Rabs_lt_between'.\nassert (H3 := Rmin_l 2 eps).\nassert (H4 := Rmin_r 2 eps).\nclear -H1 H2 Hu H3 H4.\ndestruct Hu.\nsplit ; lra.\n-\n destruct (HF (mkposreal _ Rlt_0_1)) as [y Fy].\n elim (Hx2 (y + 1)).\n intros x Fx.\n apply Rbar_not_lt_le => Hlt.\n apply filter_not_empty.\n generalize (filter_and _ _ Fy Fx).\n apply filter_imp.\n intros z [Hz1 Hz2].\n revert Hlt.\n apply Rbar_le_not_lt.\n apply Rplus_le_reg_r with (-(y - 1)).\n replace (y + 1 + -(y - 1)) with 2 by ring.\n apply Rabs_le_between.\n apply Rlt_le.\n generalize (ball_triangle y z (x + 1) 1 1) => /= H.\n replace (x + -(y - 1)) with ((x + 1) - y) by ring.\n apply H.\n apply Hz1.\n apply ball_sym in Hz2.\n apply Hz2.\n-\n destruct (HF (mkposreal _ Rlt_0_1)) as [y Fy].\n elim (Hx1 (y - 1)).\n now replace (y - 1 + 1) with y by ring.\nQed.\n\nLemma R_complete :\n forall F : (R -> Prop) -> Prop,\n ProperFilter F ->\n (forall eps : posreal, exists x : R, F (ball x eps)) ->\n forall eps : posreal, F (ball (R_complete_lim F) eps).\nProof.\nintros F FF.\napply R_complete_ax1.\nby apply Proper_StrongProper.\nQed.\n\nLemma R_complete_ax2 :\n forall F1 F2 : (R -> Prop) -> Prop,\n filter_le F1 F2 -> filter_le F2 F1 ->\n R_complete_lim F1 = R_complete_lim F2.\nProof.\nintros F1 F2 H12 H21.\nunfold R_complete_lim.\napply f_equal, Lub_Rbar_eqset.\nsplit.\napply H21.\napply H12.\nQed.\n\nLemma R_complete_close :\n forall F1 F2 : (R -> Prop) -> Prop,\n filter_le F1 F2 -> filter_le F2 F1 ->\n close (R_complete_lim F1) (R_complete_lim F2).\nProof.\nintros F1 F2 H12 H21.\nreplace (R_complete_lim F2) with (R_complete_lim F1).\nintros eps.\napply ball_center.\nexact: R_complete_ax2.\nQed.\n\nDefinition R_CompleteSpace_mixin :=\n CompleteSpace.Mixin _ R_complete_lim R_complete R_complete_close.\n\nCanonical R_CompleteSpace :=\n CompleteSpace.Pack R (CompleteSpace.Class _ _ R_CompleteSpace_mixin) R.\n\nDefinition R_ModuleSpace_mixin :=\n AbsRing_ModuleSpace_mixin R_AbsRing.\n\nCanonical R_ModuleSpace :=\n ModuleSpace.Pack _ R (ModuleSpace.Class _ _ _ R_ModuleSpace_mixin) R.\n\nCanonical R_NormedModuleAux :=\n NormedModuleAux.Pack _ R (NormedModuleAux.Class _ _ (ModuleSpace.class _ R_ModuleSpace) (UniformSpace.class R_UniformSpace)) R.\n\nDefinition R_NormedModule_mixin :=\n AbsRing_NormedModule_mixin R_AbsRing.\n\nCanonical R_NormedModule :=\n NormedModule.Pack _ R (NormedModule.Class _ _ _ R_NormedModule_mixin) R.\n\nCanonical R_CompleteNormedModule :=\n CompleteNormedModule.Pack _ R (CompleteNormedModule.Class R_AbsRing _ (NormedModule.class _ R_NormedModule) R_CompleteSpace_mixin) R.\n\nDefinition at_left x := within (fun u : R => Rlt u x) (locally x).\nDefinition at_right x := within (fun u : R => Rlt x u) (locally x).\n\nGlobal Instance at_right_proper_filter : forall (x : R),\n ProperFilter (at_right x).\nProof.\n constructor.\n intros P [d Hd].\n exists (x + d / 2).\n apply Hd.\n apply @norm_compat1 ; rewrite /norm /minus /plus /opp /= /abs /=.\n ring_simplify (x + d / 2 + - x).\n rewrite Rabs_pos_eq.\n apply Rlt_div_l.\n by apply Rlt_0_2.\n apply Rminus_lt_0 ; ring_simplify ; by apply d.\n apply Rlt_le, is_pos_div_2.\n apply Rminus_lt_0 ; ring_simplify ; by apply is_pos_div_2.\n apply within_filter, locally_filter.\nQed.\nGlobal Instance at_left_proper_filter : forall (x : R),\n ProperFilter (at_left x).\nProof.\n constructor.\n intros P [d Hd].\n exists (x - d / 2).\n apply Hd.\n apply @norm_compat1 ; rewrite /norm /minus /plus /opp /= /abs /=.\n ring_simplify (x - d / 2 + - x).\n rewrite Rabs_Ropp Rabs_pos_eq.\n apply Rlt_div_l.\n by apply Rlt_0_2.\n apply Rminus_lt_0 ; ring_simplify ; by apply d.\n apply Rlt_le, is_pos_div_2.\n apply Rminus_lt_0 ; ring_simplify ; by apply is_pos_div_2.\n apply within_filter, locally_filter.\nQed.\n\n(* *)\n\nLemma sum_n_Reals : forall a N, sum_n a N = sum_f_R0 a N.\nProof.\n intros a; induction N; simpl.\n apply sum_n_n.\n by rewrite sum_Sn IHN.\nQed.\nLemma sum_n_m_Reals a n m : (n <= m)%nat -> sum_n_m a n m = sum_f n m a.\nProof.\n induction m => //= Hnm.\n apply le_n_O_eq in Hnm.\n by rewrite -Hnm sum_n_n /=.\n case: (le_dec n m) => H.\n rewrite sum_n_Sm // IHm //.\n rewrite sum_f_n_Sm //.\n replace n with (S m).\n rewrite sum_n_n.\n by rewrite /sum_f minus_diag /=.\n apply le_antisym => //.\n apply not_le in H.\n by apply lt_le_S.\nQed.\n\nLemma sum_n_m_const (n m : nat) (a : R) :\n sum_n_m (fun _ => a) n m = INR (S m - n) * a.\nProof.\n rewrite /sum_n_m /iter_nat (iter_const _ a).\n by rewrite -{2}(seq.size_iota n (S m - n)).\nQed.\nLemma sum_n_const (n : nat) (a : R) :\n sum_n (fun _ => a) n = INR (S n) * a.\nProof.\n by rewrite /sum_n sum_n_m_const -minus_n_O.\nQed.\n\nLemma norm_sum_n_m {K : AbsRing} {V : NormedModule K} (a : nat -> V) (n m : nat) :\n norm (sum_n_m a n m) <= sum_n_m (fun n => norm (a n)) n m.\nProof.\n case: (le_dec n m) => Hnm.\n elim: m n a Hnm => /= [ | m IH] n a Hnm.\n apply le_n_O_eq in Hnm.\n rewrite -Hnm !sum_n_n.\n by apply Rle_refl.\n destruct n.\n rewrite /sum_n !sum_n_Sm ; try by apply le_O_n.\n eapply Rle_trans.\n apply norm_triangle.\n apply Rplus_le_compat_r, IH, le_O_n.\n rewrite -!sum_n_m_S.\n apply IH.\n by apply le_S_n.\n apply not_le in Hnm.\n rewrite !sum_n_m_zero // norm_zero.\n by apply Rle_refl.\nQed.\n\nLemma sum_n_m_le (a b : nat -> R) (n m : nat) :\n (forall k, a k <= b k)\n -> sum_n_m a n m <= sum_n_m b n m.\nProof.\n intros H.\n case: (le_dec n m) => Hnm.\n elim: m n a b Hnm H => /= [ | m IH] n a b Hnm H.\n apply le_n_O_eq in Hnm ; rewrite -Hnm.\n rewrite !sum_n_n ; by apply H.\n destruct n.\n rewrite !sum_n_Sm ; try by apply le_O_n.\n apply Rplus_le_compat.\n apply IH => // ; by apply le_O_n.\n by apply H.\n rewrite -!sum_n_m_S.\n apply IH => //.\n by apply le_S_n.\n apply not_le in Hnm.\n rewrite !sum_n_m_zero //.\n by apply Rle_refl.\nQed.\n\nLemma pow_n_pow :\n forall (x : R) k, pow_n x k = x^k.\nProof.\nintros x; induction k; simpl.\neasy.\nnow rewrite IHk.\nQed.\n\n(** Continuity of norm *)\n\nLemma filterlim_norm {K : AbsRing} {V : NormedModule K} :\n forall (x : V), filterlim norm (locally x) (locally (norm x)).\nProof.\n intros x.\n apply (filterlim_filter_le_1 _ (locally_le_locally_norm x)).\n apply filterlim_locally => eps /=.\n exists eps ; move => /= y Hy.\n apply Rle_lt_trans with (2 := Hy).\n apply norm_triangle_inv.\nQed.\n\nLemma filterlim_norm_zero {U} {K : AbsRing} {V : NormedModule K}\n {F : (U -> Prop) -> Prop} {FF : Filter F} (f : U -> V) :\n filterlim (fun x => norm (f x)) F (locally 0)\n -> filterlim f F (locally (zero (G := V))).\nProof.\n intros Hf.\n apply filterlim_locally_ball_norm => eps.\n generalize (proj1 (filterlim_locally_ball_norm _ _) Hf eps) ;\n unfold ball_norm ; simpl.\n apply filter_imp => /= x.\n rewrite !minus_zero_r {1}/norm /= /abs /= Rabs_pos_eq //.\n by apply norm_ge_0.\nQed.\n\nLemma filterlim_bounded {K : AbsRing} {V : NormedModule K} (a : nat -> V) :\n (exists x, filterlim a eventually (locally x))\n -> {M : R | forall n, norm (a n) <= M}.\nProof.\n intros Ha.\n assert (exists x : R, filterlim (fun n => norm (a n)) eventually (locally x)).\n destruct Ha as [l Hl].\n exists (norm l).\n eapply filterlim_comp.\n by apply Hl.\n by apply filterlim_norm.\n clear Ha.\n\n destruct (LPO_ub_dec (fun n => norm (a n))) as [[M HM]|HM].\n now exists M.\n elimtype False.\n case: H => l Hl.\n assert (H := proj1 (filterlim_locally (F := eventually) _ l) Hl (mkposreal _ Rlt_0_1)).\n clear Hl ; simpl in H ; rewrite /ball /= /AbsRing_ball in H.\n destruct H as [N HN].\n specialize (HM (seq.foldr Rmax (1 + norm l) (seq.map (fun n => norm (a n)) (seq.iota 0 N)))).\n destruct HM as [n Hn].\n revert Hn.\n apply Rle_not_lt.\n elim: N a n HN => /=[ |N IH] a n HN.\n rewrite Rplus_comm.\n apply Rlt_le, Rabs_lt_between'.\n eapply Rle_lt_trans, HN.\n rewrite /abs /=.\n eapply Rle_trans, (norm_triangle_inv (norm (a n)) l).\n apply Req_le, f_equal, f_equal2 => //.\n apply sym_eq, Rabs_pos_eq, norm_ge_0.\n by apply le_O_n.\n case: n => [ | n].\n apply Rmax_l.\n eapply Rle_trans, Rmax_r.\n eapply Rle_trans.\n apply (IH (fun n => a (S n))).\n intros k Hk.\n apply HN.\n by apply le_n_S.\n clear.\n apply Req_le.\n elim: N 0%nat => /=[ |N IH] n0.\n by [].\n apply f_equal.\n apply IH.\nQed.\n\n(** Some open sets of [R] *)\n\nLemma open_lt :\n forall y : R, open (fun u : R => u < y).\nProof.\nintros y x Hxy.\napply Rminus_lt_0 in Hxy.\nexists (mkposreal _ Hxy).\nintros z Bz.\nreplace y with (x + (y - x)) by ring.\napply Rabs_lt_between'.\napply Bz.\nQed.\n\nLemma open_gt :\n forall y : R, open (fun u : R => y < u).\nProof.\nintros y x Hxy.\napply Rminus_lt_0 in Hxy.\nexists (mkposreal _ Hxy).\nintros z Bz.\nreplace y with (x - (x - y)) by ring.\napply Rabs_lt_between'.\napply Bz.\nQed.\n\nLemma open_neq :\n forall y : R, open (fun u : R => u <> y).\nProof.\nintros y.\napply (open_ext (fun u => u < y \\/ y < u)).\nintros u.\nsplit.\napply Rlt_dichotomy_converse.\napply Rdichotomy.\napply open_or.\napply open_lt.\napply open_gt.\nQed.\n\n(** Some closed sets of [R] *)\n\nLemma closed_le :\n forall y : R, closed (fun u : R => u <= y).\nProof.\nintros y.\napply closed_ext with (fun u => not (Rlt y u)).\nintros x.\nsplit.\napply Rnot_lt_le.\napply Rle_not_lt.\napply closed_not.\napply open_gt.\nQed.\n\nLemma closed_ge :\n forall y : R, closed (fun u : R => y <= u).\nProof.\nintros y.\napply closed_ext with (fun u => not (Rlt u y)).\nintros x.\nsplit.\napply Rnot_lt_le.\napply Rle_not_lt.\napply closed_not.\napply open_lt.\nQed.\n\nLemma closed_eq :\n forall y : R, closed (fun u : R => u = y).\nProof.\nintros y.\napply closed_ext with (fun u => not (u <> y)).\nintros x.\ndestruct (Req_dec x y) ; intuition.\napply closed_not.\napply open_neq.\nQed.\n\n(** Local properties in [R] *)\n\nLemma locally_interval (P : R -> Prop) (x : R) (a b : Rbar) :\n Rbar_lt a x -> Rbar_lt x b ->\n (forall (y : R), Rbar_lt a y -> Rbar_lt y b -> P y) ->\n locally x P.\nProof.\n move => Hax Hxb Hp.\n case: (Rbar_lt_locally _ _ _ Hax Hxb) => d Hd.\n exists d => y Hy.\n now apply Hp ; apply Hd.\nQed.\n\n(** * Topology on [R]² *)\n\nDefinition locally_2d (P : R -> R -> Prop) x y :=\n exists delta : posreal, forall u v, Rabs (u - x) < delta -> Rabs (v - y) < delta -> P u v.\n\nLemma locally_2d_locally :\n forall P x y,\n locally_2d P x y <-> locally (x,y) (fun z => P (fst z) (snd z)).\nProof.\nintros P x y.\nsplit ; intros [d H] ; exists d.\n- simpl.\n intros [u v] H'.\n now apply H ; apply H'.\n- intros u v Hu Hv.\n apply (H (u,v)).\n by split.\nQed.\n\nLemma locally_2d_impl_strong :\n forall (P Q : R -> R -> Prop) x y, locally_2d (fun u v => locally_2d P u v -> Q u v) x y ->\n locally_2d P x y -> locally_2d Q x y.\nProof.\nintros P Q x y Li LP.\napply locally_2d_locally in Li.\napply locally_2d_locally in LP.\napply locally_locally in LP.\napply locally_2d_locally.\ngeneralize (filter_and _ _ Li LP).\napply filter_imp.\nintros [u v] [H1 H2].\napply H1.\nnow apply locally_2d_locally.\nQed.\n\nLemma locally_2d_singleton :\n forall (P : R -> R -> Prop) x y, locally_2d P x y -> P x y.\nProof.\nintros P x y LP.\napply locally_2d_locally in LP.\napply locally_singleton with (1 := LP).\nQed.\n\nLemma locally_2d_impl :\n forall (P Q : R -> R -> Prop) x y, locally_2d (fun u v => P u v -> Q u v) x y ->\n locally_2d P x y -> locally_2d Q x y.\nProof.\nintros P Q x y (d,H).\napply locally_2d_impl_strong.\nexists d => u v Hu Hv Hp.\napply H => //.\nnow apply locally_2d_singleton.\nQed.\n\nLemma locally_2d_forall :\n forall (P : R -> R -> Prop) x y, (forall u v, P u v) -> locally_2d P x y.\nProof.\nintros P x y Hp.\nnow exists (mkposreal _ Rlt_0_1) => u v _ _.\nQed.\n\nLemma locally_2d_and :\n forall (P Q : R -> R -> Prop) x y, locally_2d P x y -> locally_2d Q x y ->\n locally_2d (fun u v => P u v /\\ Q u v) x y.\nProof.\nintros P Q x y H.\napply: locally_2d_impl.\napply: locally_2d_impl H.\napply locally_2d_forall.\nnow split.\nQed.\n\nLemma locally_2d_align :\n forall (P Q : R -> R -> Prop) x y,\n ( forall eps : posreal, (forall u v, Rabs (u - x) < eps -> Rabs (v - y) < eps -> P u v) ->\n forall u v, Rabs (u - x) < eps -> Rabs (v - y) < eps -> Q u v ) ->\n locally_2d P x y -> locally_2d Q x y.\nProof.\nintros P Q x y K (d,H).\nexists d => u v Hu Hv.\nnow apply (K d).\nQed.\n\nLemma locally_2d_1d_const_x :\n forall (P : R -> R -> Prop) x y,\n locally_2d P x y ->\n locally y (fun t => P x t).\nProof.\nintros P x y (d,Hd).\nexists d; intros z Hz.\napply Hd.\nrewrite Rminus_eq_0 Rabs_R0; apply cond_pos.\nexact Hz.\nQed.\n\nLemma locally_2d_1d_const_y :\n forall (P : R -> R -> Prop) x y,\n locally_2d P x y ->\n locally x (fun t => P t y).\nProof.\nintros P x y (d,Hd).\nexists d; intros z Hz.\napply Hd.\nexact Hz.\nrewrite Rminus_eq_0 Rabs_R0; apply cond_pos.\nQed.\n\nLemma locally_2d_1d_strong :\n forall (P : R -> R -> Prop) x y,\n locally_2d P x y ->\n locally_2d (fun u v => forall t, 0 <= t <= 1 ->\n locally t (fun z => locally_2d P (x + z * (u - x)) (y + z * (v - y)))) x y.\nProof.\nintros P x y.\napply locally_2d_align => eps HP u v Hu Hv t Ht.\nassert (Zm: 0 <= Rmax (Rabs (u - x)) (Rabs (v - y))).\napply Rmax_case ; apply Rabs_pos.\ndestruct Zm as [Zm|Zm].\n(* *)\nassert (H1: Rmax (Rabs (u - x)) (Rabs (v - y)) < eps).\nnow apply Rmax_case.\nset (d1 := mkposreal _ (Rlt_Rminus _ _ H1)).\nassert (H2: 0 < pos_div_2 d1 / Rmax (Rabs (u - x)) (Rabs (v - y))).\napply Rmult_lt_0_compat.\napply cond_pos.\nnow apply Rinv_0_lt_compat.\nset (d2 := mkposreal _ H2).\nexists d2 => z Hz.\nexists (pos_div_2 d1) => p q Hp Hq.\napply HP.\n(* . *)\nreplace (p - x) with (p - (x + z * (u - x)) + (z - t + t) * (u - x)) by ring.\napply Rle_lt_trans with (1 := Rabs_triang _ _).\nreplace (pos eps) with (pos_div_2 d1 + (eps - pos_div_2 d1)) by ring.\napply Rplus_lt_le_compat with (1 := Hp).\nrewrite Rabs_mult.\napply Rle_trans with ((d2 + 1) * Rmax (Rabs (u - x)) (Rabs (v - y))).\napply Rmult_le_compat.\napply Rabs_pos.\napply Rabs_pos.\napply Rle_trans with (1 := Rabs_triang _ _).\napply Rplus_le_compat.\nnow apply Rlt_le.\nnow rewrite Rabs_pos_eq.\napply Rmax_l.\nrewrite /d2 /d1 /=.\nfield_simplify.\napply Rle_refl.\nnow apply Rgt_not_eq.\n(* . *)\nreplace (q - y) with (q - (y + z * (v - y)) + (z - t + t) * (v - y)) by ring.\napply Rle_lt_trans with (1 := Rabs_triang _ _).\nreplace (pos eps) with (pos_div_2 d1 + (eps - pos_div_2 d1)) by ring.\napply Rplus_lt_le_compat with (1 := Hq).\nrewrite Rabs_mult.\napply Rle_trans with ((d2 + 1) * Rmax (Rabs (u - x)) (Rabs (v - y))).\napply Rmult_le_compat.\napply Rabs_pos.\napply Rabs_pos.\napply Rle_trans with (1 := Rabs_triang _ _).\napply Rplus_le_compat.\nnow apply Rlt_le.\nnow rewrite Rabs_pos_eq.\napply Rmax_r.\nrewrite /d2 /d1 /=.\nfield_simplify.\napply Rle_refl.\nnow apply Rgt_not_eq.\n(* *)\napply filter_forall => z.\nexists eps => p q.\nreplace (u - x) with 0.\nreplace (v - y) with 0.\nrewrite Rmult_0_r 2!Rplus_0_r.\napply HP.\napply sym_eq.\napply Rabs_eq_0.\napply Rle_antisym.\nrewrite Zm.\napply Rmax_r.\napply Rabs_pos.\napply sym_eq.\napply Rabs_eq_0.\napply Rle_antisym.\nrewrite Zm.\napply Rmax_l.\napply Rabs_pos.\nQed.\n\nLemma locally_2d_1d :\n forall (P : R -> R -> Prop) x y,\n locally_2d P x y ->\n locally_2d (fun u v => forall t, 0 <= t <= 1 -> locally_2d P (x + t * (u - x)) (y + t * (v - y))) x y.\nProof.\nintros P x y H.\napply locally_2d_1d_strong in H.\napply: locally_2d_impl H.\napply locally_2d_forall => u v H t Ht.\nspecialize (H t Ht).\napply locally_singleton with (1 := H).\nQed.\n\nLemma locally_2d_ex_dec :\n forall P x y,\n (forall x y, P x y \\/ ~P x y) ->\n locally_2d P x y ->\n {d : posreal | forall u v, Rabs (u-x) < d -> Rabs (v-y) < d -> P u v}.\nProof.\nintros P x y P_dec H.\ndestruct (locally_ex_dec (x, y) (fun z => P (fst z) (snd z))) as [d Hd].\n- now intros [u v].\n- destruct H as [e H].\n exists e.\n intros [u v] Huv.\n apply H.\n apply Huv.\n apply Huv.\nexists d.\nintros u v Hu Hv.\napply (Hd (u, v)).\nsimpl.\nnow split.\nQed.\n\n(** * Some Topology on [Rbar] *)\n\nDefinition R_to_interval (x : R) := (x * Rabs x) / (1 + x * x).\n\nDefinition Rbar_to_interval (a : Rbar) : R :=\n match a with\n | p_infty => 1\n | m_infty => -1\n | Finite a => R_to_interval a\n end.\n\nLemma cross_multiply a b c d :\n ~ (b = 0) ->\n ~ (d = 0) ->\n (a / b) = (c / d) -> a * d = b * c.\nProof.\n intros Hneq0b Hneq0d.\n intros Heq.\n assert (b * d * (a / b) = b * d * (c / d)) as Hcross by (rewrite Heq; eauto).\n field_simplify in Hcross; nra.\nQed.\n\nLemma R_to_interval_inj x y :\n R_to_interval x = R_to_interval y -> x = y.\nProof.\n rewrite /R_to_interval => Heq.\n apply cross_multiply in Heq; try nra.\n destruct (Rle_dec 0 x); destruct (Rle_dec 0 y).\n - rewrite ?Rabs_right in Heq; try nra.\n - rewrite (Rabs_right x) in Heq; try nra.\n rewrite (Rabs_left y) in Heq; try nra.\n - rewrite (Rabs_left x) in Heq; try nra.\n rewrite (Rabs_right y) in Heq; try nra.\n - rewrite (Rabs_left x) in Heq; try nra.\n rewrite (Rabs_left y) in Heq; try nra.\nQed.\n\nLemma R_to_interval_ineq1 (x : R) : 0 <= x -> -1 < x * x / (1 + x * x) < 1.\nProof.\n intros. split.\n * apply (Rlt_le_trans _ 0); first nra.\n apply Rdiv_le_0_compat; try nra.\n * rewrite -Rdiv_lt_1; nra.\nQed.\n\nLemma R_to_interval_range x :\n -1 < R_to_interval x < 1.\nProof.\n rewrite /R_to_interval.\n specialize (R_to_interval_ineq1) => Hle.\n destruct (Rle_dec 0 x).\n - rewrite Rabs_right; try nra. eauto.\n - rewrite Rabs_left; try nra.\n split.\n * destruct (Hle (Ropp x)) as (Ha&Hb); try nra.\n apply Ropp_lt_cancel.\n assert (Ropp x * Ropp x = x * x) as Heq.\n { nra. }\n rewrite Heq in Hb. nra.\n * apply Ropp_lt_cancel.\n apply (Rlt_le_trans _ 0); first nra.\n rewrite -Ropp_div.\n apply Rdiv_le_0_compat; try nra.\nQed.\n\nLemma Rbar_to_interval_inj x y :\n Rbar_to_interval x = Rbar_to_interval y -> x = y.\nProof.\n rewrite /Rbar_to_interval.\n destruct x as [x| |].\n - specialize (R_to_interval_range x). rewrite /R_to_interval.\n destruct y as [y| |]; try nra.\n intros. f_equal. apply R_to_interval_inj; eauto.\n - destruct y as [y| |]; try nra; eauto.\n specialize (R_to_interval_range y); nra; eauto.\n - destruct y as [y| |]; try nra; eauto.\n specialize (R_to_interval_range y); nra; eauto.\nQed.\n\nDefinition Rbar_dist (x y : Rbar) : R :=\n Rabs (Rbar_to_interval x - Rbar_to_interval y).\n\nLemma Rbar_dist_0 x y :\n Rbar_dist x y = 0 -> x = y.\nProof.\n rewrite /Rbar_dist => Heq.\n apply Rbar_to_interval_inj.\n apply Rabs_eq_0 in Heq. nra.\nQed.\n\nLemma Rbar_dist_sym x y :\n Rbar_dist x y = Rbar_dist y x.\nProof. rewrite /Rbar_dist. apply Rabs_minus_sym. Qed.\n\nLemma Rbar_dist_triangle x y z :\n Rbar_dist x z <= Rbar_dist x y + Rbar_dist y z.\nProof.\n rewrite /Rbar_dist.\n eapply Rle_trans; last eapply Rabs_triang.\n right. f_equal. nra.\nQed.\n\nLemma Rbar_dist_same_eq_0 x y :\n x = y -> Rbar_dist x y = 0.\nProof.\n rewrite /Rbar_dist => ->.\n rewrite -Rabs_R0. f_equal. nra.\nQed.\n\nDefinition Rbar_UniformSpace_mixin : UniformSpace.mixin_of Rbar.\n refine {| UniformSpace.point_of := Finite R0;\n UniformSpace.ball := fun x e y => Rbar_dist x y < e |}.\n - abstract (intros x (eps&Hle) => /=; rewrite Rbar_dist_same_eq_0 //).\n - abstract (intros; rewrite Rbar_dist_sym //=).\n - abstract (intros x y z e1 e2; rewrite /Rbar_dist => Hlt1 Hlt2;\n specialize (Rbar_dist_triangle x y z) => Hle; rewrite /Rbar_dist in Hle; nra).\nDefined.\n\nCanonical Rbar_UniformSpace :=\n UniformSpace.Pack Rbar Rbar_UniformSpace_mixin Rbar.\n\nDefinition Rbar_locally' (a : Rbar) (P : R -> Prop) :=\n match a with\n | Finite a => locally' a P\n | p_infty => exists M : R, forall x, M < x -> P x\n | m_infty => exists M : R, forall x, x < M -> P x\n end.\nDefinition Rbar_locally (a : Rbar) (P : R -> Prop) :=\n match a with\n | Finite a => locally a P\n | p_infty => exists M : R, forall x, M < x -> P x\n | m_infty => exists M : R, forall x, x < M -> P x\n end.\n\nGlobal Instance Rbar_locally'_filter :\n forall x, ProperFilter (Rbar_locally' x).\nProof.\nintros [x| |] ; (constructor ; [idtac | constructor]).\n- intros P [eps HP].\n exists (x + eps / 2).\n apply HP.\n rewrite /ball /= /AbsRing_ball /abs /minus /plus /opp /=.\n ring_simplify (x + eps / 2 + - x).\n rewrite Rabs_pos_eq.\n apply Rminus_lt_0.\n replace (eps - eps / 2) with (eps / 2) by field.\n apply is_pos_div_2.\n apply Rlt_le, is_pos_div_2.\n apply Rgt_not_eq, Rminus_lt_0 ; ring_simplify.\n apply is_pos_div_2.\n- now exists (mkposreal _ Rlt_0_1).\n- intros P Q [dP HP] [dQ HQ].\n exists (mkposreal _ (Rmin_stable_in_posreal dP dQ)).\n simpl.\n intros y Hy H.\n split.\n apply HP with (2 := H).\n apply Rlt_le_trans with (1 := Hy).\n apply Rmin_l.\n apply HQ with (2 := H).\n apply Rlt_le_trans with (1 := Hy).\n apply Rmin_r.\n- intros P Q H [dP HP].\n exists dP.\n intros y Hy H'.\n apply H.\n now apply HP.\n- intros P [N HP].\n exists (N + 1).\n apply HP.\n apply Rlt_plus_1.\n- now exists 0.\n- intros P Q [MP HP] [MQ HQ].\n exists (Rmax MP MQ).\n intros y Hy.\n split.\n apply HP.\n apply Rle_lt_trans with (2 := Hy).\n apply Rmax_l.\n apply HQ.\n apply Rle_lt_trans with (2 := Hy).\n apply Rmax_r.\n- intros P Q H [dP HP].\n exists dP.\n intros y Hy.\n apply H.\n now apply HP.\n- intros P [N HP].\n exists (N - 1).\n apply HP.\n apply Rlt_minus_l, Rlt_plus_1.\n- now exists 0.\n- intros P Q [MP HP] [MQ HQ].\n exists (Rmin MP MQ).\n intros y Hy.\n split.\n apply HP.\n apply Rlt_le_trans with (1 := Hy).\n apply Rmin_l.\n apply HQ.\n apply Rlt_le_trans with (1 := Hy).\n apply Rmin_r.\n- intros P Q H [dP HP].\n exists dP.\n intros y Hy.\n apply H.\n now apply HP.\nQed.\n\nGlobal Instance Rbar_locally_filter :\n forall x, ProperFilter (Rbar_locally x).\nProof.\nintros [x| |].\n- apply locally_filter.\n- exact (Rbar_locally'_filter p_infty).\n- exact (Rbar_locally'_filter m_infty).\nQed.\n\n(** Open sets in [Rbar] *)\n\nLemma open_Rbar_lt :\n forall y, open (fun u : R => Rbar_lt u y).\nProof.\nintros [y| |].\n- apply open_lt.\n- apply open_true.\n- apply open_false.\nQed.\n\nLemma open_Rbar_gt :\n forall y, open (fun u : R => Rbar_lt y u).\nProof.\nintros [y| |].\n- apply open_gt.\n- apply open_false.\n- apply open_true.\nQed.\n\nLemma open_Rbar_lt' :\n forall x y, Rbar_lt x y -> Rbar_locally x (fun u => Rbar_lt u y).\nProof.\nintros [x| |] y Hxy.\n- now apply open_Rbar_lt.\n- easy.\n- destruct y as [y| |].\n now exists y.\n now apply filter_forall.\n easy.\nQed.\n\nLemma open_Rbar_gt' :\n forall x y, Rbar_lt y x -> Rbar_locally x (fun u => Rbar_lt y u).\nProof.\nintros [x| |] y Hxy.\n- now apply open_Rbar_gt.\n- destruct y as [y| |].\n now exists y.\n easy.\n now apply filter_forall.\n- now destruct y as [y| |].\nQed.\n\nLemma Rbar_locally'_le :\n forall x, filter_le (Rbar_locally' x) (Rbar_locally x).\nProof.\nintros [x| |] P [eps HP] ; exists eps ; intros ; now apply HP.\nQed.\n\nLemma Rbar_locally'_le_finite :\n forall x : R, filter_le (Rbar_locally' x) (locally x).\nProof.\nintros x P [eps HP] ; exists eps ; intros ; now apply HP.\nQed.\n\n(** * Some limits on real functions *)\n\nDefinition Rbar_loc_seq (x : Rbar) (n : nat) := match x with\n | Finite x => x + / (INR n + 1)\n | p_infty => INR n\n | m_infty => - INR n\n end.\n\nLemma filterlim_Rbar_loc_seq :\n forall x, filterlim (Rbar_loc_seq x) eventually (Rbar_locally' x).\nProof.\n intros x P.\n unfold Rbar_loc_seq.\n case: x => /= [x | | ] [delta Hp].\n(* x \\in R *)\n case: (nfloor_ex (/delta)) => [ | N [_ HN]].\n by apply Rlt_le, Rinv_0_lt_compat, delta.\n exists N => n Hn.\n apply Hp ; simpl.\n rewrite /ball /= /AbsRing_ball /abs /minus /plus /opp /=.\n ring_simplify (x + / (INR n + 1) + - x).\n rewrite Rabs_pos_eq.\n rewrite -(Rinv_involutive delta).\n apply Rinv_lt_contravar.\n apply Rmult_lt_0_compat.\n apply Rinv_0_lt_compat.\n by apply delta.\n exact: INRp1_pos.\n apply Rlt_le_trans with (1 := HN).\n by apply Rplus_le_compat_r, le_INR.\n by apply Rgt_not_eq, delta.\n by apply Rlt_le, RinvN_pos.\n apply Rgt_not_eq, Rminus_lt_0.\n ring_simplify.\n by apply RinvN_pos.\n(* x = p_infty *)\n case: (nfloor_ex (Rmax 0 delta)) => [ | N [_ HN]].\n by apply Rmax_l.\n exists (S N) => n Hn.\n apply Hp.\n apply Rle_lt_trans with (1 := Rmax_r 0 _).\n apply Rlt_le_trans with (1 := HN).\n rewrite -S_INR ; by apply le_INR.\n(* x = m_infty *)\n case: (nfloor_ex (Rmax 0 (-delta))) => [ | N [_ HN]].\n by apply Rmax_l.\n exists (S N) => n Hn.\n apply Hp.\n rewrite -(Ropp_involutive delta).\n apply Ropp_lt_contravar.\n apply Rle_lt_trans with (1 := Rmax_r 0 _).\n apply Rlt_le_trans with (1 := HN).\n rewrite -S_INR ; by apply le_INR.\nQed.\n\nLemma continuity_pt_locally :\n forall f x,\n continuity_pt f x <->\n forall eps : posreal, locally x (fun u => Rabs (f u - f x) < eps).\nProof.\nintros f x.\nsplit.\nintros H eps.\nmove: (H eps (cond_pos eps)) => {H} [d [H1 H2]].\nrewrite /= /R_dist /D_x /no_cond in H2.\nexists (mkposreal d H1) => y H.\ndestruct (Req_dec x y) as [<-|Hxy].\nrewrite /Rminus Rplus_opp_r Rabs_R0.\napply cond_pos.\nby apply H2.\nintros H eps He.\nmove: (H (mkposreal _ He)) => {H} [d H].\nexists d.\nsplit.\napply cond_pos.\nintros h [Zh Hh].\nexact: H.\nQed.\n\nLemma continuity_pt_locally' :\n forall f x,\n continuity_pt f x <->\n forall eps : posreal, locally' x (fun u => Rabs (f u - f x) < eps).\nProof.\nintros f x.\nsplit.\nintros H eps.\nmove: (H eps (cond_pos eps)) => {H} [d [H1 H2]].\nrewrite /= /R_dist /D_x /no_cond in H2.\nexists (mkposreal d H1) => y H H'.\ndestruct (Req_dec x y) as [<-|Hxy].\nrewrite /Rminus Rplus_opp_r Rabs_R0.\napply cond_pos.\nby apply H2.\nintros H eps He.\nmove: (H (mkposreal _ He)) => {H} [d H].\nexists d.\nsplit.\napply cond_pos.\nintros h [Zh Hh].\napply H.\nexact Hh.\napply proj2 in Zh.\nnow contradict Zh.\nQed.\n\nLemma continuity_pt_filterlim :\n forall (f : R -> R) (x : R),\n continuity_pt f x <->\n filterlim f (locally x) (locally (f x)).\nProof.\nintros f x.\neapply iff_trans.\napply continuity_pt_locally.\napply iff_sym.\nexact (filterlim_locally f (f x)).\nQed.\n\nLemma continuity_pt_filterlim' :\n forall f x,\n continuity_pt f x <->\n filterlim f (locally' x) (locally (f x)).\nProof.\nintros f x.\neapply iff_trans.\napply continuity_pt_locally'.\napply iff_sym.\nexact (filterlim_locally f (f x)).\nQed.\n\nLemma locally_pt_comp (P : R -> Prop) (f : R -> R) (x : R) :\n locally (f x) P -> continuity_pt f x ->\n locally x (fun x => P (f x)).\nProof.\nintros Lf Cf.\napply continuity_pt_filterlim in Cf.\nnow apply Cf.\nQed.\n", "meta": {"author": "jtassarotti", "repo": "coquelicot-ext", "sha": "1c11715037fdd4e15de6491bfdb9f923209ddb63", "save_path": "github-repos/coq/jtassarotti-coquelicot-ext", "path": "github-repos/coq/jtassarotti-coquelicot-ext/coquelicot-ext-1c11715037fdd4e15de6491bfdb9f923209ddb63/theories/Hierarchy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11436853221906972, "lm_q1q2_score": 0.05629083465802767}} {"text": "(** This file collects general purpose definitions and theorems on vectors\n(lists of fixed length). It uses the definitions from the standard library, but\nrenames or changes their notations, so that it becomes more consistent with the\nnaming conventions in this development. *)\nFrom stdpp Require Import countable.\nFrom stdpp Require Export fin list.\nFrom stdpp Require Import options.\nOpen Scope vector_scope.\n\n(** The type [vec n] represents lists of consisting of exactly [n] elements.\nWhereas the standard library declares exactly the same notations for vectors as\nused for lists, we use slightly different notations so it becomes easier to use\nlists and vectors together. *)\nNotation vec := Vector.t.\nNotation vnil := Vector.nil.\nArguments vnil {_}.\nNotation vcons := Vector.cons.\nNotation vapp := Vector.append.\nArguments vcons {_} _ {_} _.\n\nInfix \":::\" := vcons (at level 60, right associativity) : vector_scope.\nNotation \"(:::)\" := vcons (only parsing) : vector_scope.\nNotation \"( x :::.)\" := (vcons x) (only parsing) : vector_scope.\nNotation \"(.::: v )\" := (λ x, vcons x v) (only parsing) : vector_scope.\nNotation \"[# ] \" := vnil : vector_scope.\nNotation \"[# x ] \" := (vcons x vnil) : vector_scope.\nNotation \"[# x ; .. ; y ] \" := (vcons x .. (vcons y vnil) ..) : vector_scope.\nInfix \"+++\" := vapp (at level 60, right associativity) : vector_scope.\nNotation \"(+++)\" := vapp (only parsing) : vector_scope.\nNotation \"( v +++.)\" := (vapp v) (only parsing) : vector_scope.\nNotation \"(.+++ w )\" := (λ v, vapp v w) (only parsing) : vector_scope.\n\n(** Similar to [fin], we provide an inversion principle that keeps the length\nfixed. We define a tactic [inv_vec v] to perform case analysis on [v], using\nthis inversion principle. *)\nNotation vec_0_inv := Vector.case0.\nDefinition vec_S_inv {A n} (P : vec A (S n) → Type)\n (Hcons : ∀ x v, P (x ::: v)) v : P v.\nProof.\n revert P Hcons.\n refine match v with [#] => tt | x ::: v => λ P Hcons, Hcons x v end.\nDefined.\n\nInstance vector_lookup_total A : ∀ m, LookupTotal (fin m) A (vec A m) :=\n fix go m i {struct i} := let _ : ∀ m, LookupTotal _ _ _ := @go in\n match i in fin m return vec A m → A with\n | 0%fin => vec_S_inv (λ _, A) (λ x _, x)\n | FS j => vec_S_inv (λ _, A) (λ _ v, v !!! j)\n end.\n\n(** The tactic [vec_double_ind v1 v2] performs double induction on [v1] and [v2]\nprovided that they have the same length. *)\nNotation vec_rect2 := Vector.rect2.\nLtac vec_double_ind v1 v2 :=\n match type of v1 with\n | vec _ ?n =>\n repeat match goal with\n | H' : context [ n ] |- _ => var_neq v1 H'; var_neq v2 H'; revert H'\n end;\n revert n v1 v2;\n match goal with |- ∀ n v1 v2, @?P n v1 v2 => apply (vec_rect2 P) end\n end.\n\nNotation vcons_inj := VectorSpec.cons_inj.\nLemma vcons_inj_1 {A n} x y (v w : vec A n) : x ::: v = y ::: w → x = y.\nProof. apply vcons_inj. Qed.\nLemma vcons_inj_2 {A n} x y (v w : vec A n) : x ::: v = y ::: w → v = w.\nProof. apply vcons_inj. Qed.\n\nLemma vec_eq {A n} (v w : vec A n) : (∀ i, v !!! i = w !!! i) → v = w.\nProof.\n vec_double_ind v w; [done|]. intros n v w IH x y Hi. f_equal.\n - apply (Hi 0%fin).\n - apply IH. intros i. apply (Hi (FS i)).\nQed.\n\nInstance vec_dec {A} {dec : EqDecision A} {n} : EqDecision (vec A n).\nProof.\n refine (vec_rect2\n (λ n (v w : vec A n), { v = w } + { v ≠ w })\n (left _)\n (λ _ _ _ H x y, cast_if_and (dec x y) H));\n f_equal; eauto using vcons_inj_1, vcons_inj_2.\nDefined.\n\nLtac inv_vec v :=\n let T := type of v in\n match eval hnf in T with\n | vec _ ?n =>\n match eval hnf in n with\n | 0 => revert dependent v; match goal with |- ∀ v, @?P v => apply (vec_0_inv P) end\n | S ?n =>\n revert dependent v; match goal with |- ∀ v, @?P v => apply (vec_S_inv P) end;\n (* Try going on recursively. *)\n try (let x := fresh \"x\" in intros x v; inv_vec v; revert x)\n end\n end.\n\n(** The following tactic performs case analysis on all hypotheses of the shape\n[fin 0], [fin (S n)], [vec A 0] and [vec A (S n)] until no further case\nanalyses are possible. *)\nLtac inv_all_vec_fin := block_goal;\n repeat match goal with\n | v : vec _ _ |- _ => inv_vec v; intros\n | i : fin _ |- _ => inv_fin i; intros\n end; unblock_goal.\n\n(** We define a coercion from [vec] to [list] and show that it preserves the\noperations on vectors. We also define a function to go in the other way, but\ndo not define it as a coercion, as it would otherwise introduce ambiguity. *)\nFixpoint vec_to_list {A n} (v : vec A n) : list A :=\n match v with [#] => [] | x ::: v => x :: vec_to_list v end.\nCoercion vec_to_list : vec >-> list.\nNotation list_to_vec := Vector.of_list.\n\nLemma vec_to_list_cons {A n} x (v : vec A n) :\n vec_to_list (x ::: v) = x :: vec_to_list v.\nProof. done. Qed.\nLemma vec_to_list_app {A n m} (v : vec A n) (w : vec A m) :\n vec_to_list (v +++ w) = vec_to_list v ++ vec_to_list w.\nProof. by induction v; f_equal/=. Qed.\nLemma vec_to_list_to_vec {A} (l : list A): vec_to_list (list_to_vec l) = l.\nProof. by induction l; f_equal/=. Qed.\nLemma vec_to_list_length {A n} (v : vec A n) : length (vec_to_list v) = n.\nProof. induction v; simpl; by f_equal. Qed.\nLemma vec_to_list_same_length {A B n} (v : vec A n) (w : vec B n) :\n length v = length w.\nProof. by rewrite !vec_to_list_length. Qed.\nLemma vec_to_list_inj1 {A n m} (v : vec A n) (w : vec A m) :\n vec_to_list v = vec_to_list w → n = m.\nProof.\n revert m w. induction v; intros ? [|???] ?;\n simplify_eq/=; f_equal; eauto.\nQed.\nLemma vec_to_list_inj2 {A n} (v : vec A n) (w : vec A n) :\n vec_to_list v = vec_to_list w → v = w.\nProof.\n revert w. induction v; intros w; inv_vec w; intros;\n simplify_eq/=; f_equal; eauto.\nQed.\nLemma list_to_vec_to_list {A n} (v : vec A n) :\n list_to_vec (vec_to_list v) = eq_rect _ _ v _ (eq_sym (vec_to_list_length v)).\nProof.\n apply vec_to_list_inj2. rewrite vec_to_list_to_vec.\n by destruct (eq_sym (vec_to_list_length v)).\nQed.\n\nLemma vlookup_middle {A n m} (v : vec A n) (w : vec A m) x :\n ∃ i : fin (n + S m), x = (v +++ x ::: w) !!! i.\nProof.\n induction v as [|??? IHv]; simpl; [by eexists 0%fin|].\n destruct IHv as [i ?]. by exists (FS i).\nQed.\nLemma vec_to_list_lookup_middle {A n} (v : vec A n) (l k : list A) x :\n vec_to_list v = l ++ x :: k →\n ∃ i : fin n, l = take i v ∧ x = v !!! i ∧ k = drop (S i) v.\nProof.\n intros H.\n rewrite <-(vec_to_list_to_vec l), <-(vec_to_list_to_vec k) in H.\n rewrite <-vec_to_list_cons, <-vec_to_list_app in H.\n pose proof (vec_to_list_inj1 _ _ H); subst.\n apply vec_to_list_inj2 in H; subst. induction l as [|?? IHl]; simpl.\n - eexists 0%fin. simpl. by rewrite vec_to_list_to_vec.\n - destruct IHl as [i ?]. exists (FS i). simpl. intuition congruence.\nQed.\nLemma vec_to_list_drop_lookup {A n} (v : vec A n) (i : fin n) :\n drop i v = v !!! i :: drop (S i) v.\nProof. induction i as [|?? IHi]; inv_vec v; simpl; intros; [done | by rewrite IHi]. Qed.\nLemma vec_to_list_take_drop_lookup {A n} (v : vec A n) (i : fin n) :\n vec_to_list v = take i v ++ v !!! i :: drop (S i) v.\nProof. rewrite <-(take_drop i v) at 1. by rewrite vec_to_list_drop_lookup. Qed.\n\nLemma vlookup_lookup {A n} (v : vec A n) (i : fin n) x :\n v !!! i = x ↔ (v : list A) !! (i : nat) = Some x.\nProof.\n induction v as [|? ? v IH]; inv_fin i.\n - simpl; split; congruence.\n - done.\nQed.\nLemma vlookup_lookup' {A n} (v : vec A n) (i : nat) x :\n (∃ H : i < n, v !!! nat_to_fin H = x) ↔ (v : list A) !! i = Some x.\nProof.\n split.\n - intros [Hlt ?]. rewrite <-(fin_to_nat_to_fin i n Hlt). by apply vlookup_lookup.\n - intros Hvix. assert (Hlt:=lookup_lt_Some _ _ _ Hvix).\n rewrite vec_to_list_length in Hlt. exists Hlt.\n apply vlookup_lookup. by rewrite fin_to_nat_to_fin.\nQed.\nLemma elem_of_vlookup {A n} (v : vec A n) x :\n x ∈ vec_to_list v ↔ ∃ i, v !!! i = x.\nProof.\n rewrite elem_of_list_lookup. setoid_rewrite <-vlookup_lookup'.\n split; [by intros (?&?&?); eauto|]. intros [i Hx].\n exists i, (fin_to_nat_lt _). by rewrite nat_to_fin_to_nat.\nQed.\n\nLemma Forall_vlookup {A} (P : A → Prop) {n} (v : vec A n) :\n Forall P (vec_to_list v) ↔ ∀ i, P (v !!! i).\nProof. rewrite Forall_forall. setoid_rewrite elem_of_vlookup. naive_solver. Qed.\nLemma Forall_vlookup_1 {A} (P : A → Prop) {n} (v : vec A n) i :\n Forall P (vec_to_list v) → P (v !!! i).\nProof. by rewrite Forall_vlookup. Qed.\nLemma Forall_vlookup_2 {A} (P : A → Prop) {n} (v : vec A n) :\n (∀ i, P (v !!! i)) → Forall P (vec_to_list v).\nProof. by rewrite Forall_vlookup. Qed.\nLemma Exists_vlookup {A} (P : A → Prop) {n} (v : vec A n) :\n Exists P (vec_to_list v) ↔ ∃ i, P (v !!! i).\nProof. rewrite Exists_exists. setoid_rewrite elem_of_vlookup. naive_solver. Qed.\nLemma Forall2_vlookup {A B} (P : A → B → Prop) {n}\n (v1 : vec A n) (v2 : vec B n) :\n Forall2 P (vec_to_list v1) (vec_to_list v2) ↔ ∀ i, P (v1 !!! i) (v2 !!! i).\nProof.\n split.\n - vec_double_ind v1 v2; [intros _ i; inv_fin i |].\n intros n v1 v2 IH a b; simpl. inversion_clear 1.\n intros i. inv_fin i; simpl; auto.\n - vec_double_ind v1 v2; [constructor|].\n intros ??? IH ?? H. constructor.\n + apply (H 0%fin).\n + apply IH, (λ i, H (FS i)).\nQed.\n\n(** Given a function [fin n → A], we can construct a vector. *)\nFixpoint fun_to_vec {A n} {struct n} : (fin n → A) → vec A n :=\n match n with\n | 0 => λ f, [#]\n | S n => λ f, f 0%fin ::: fun_to_vec (f ∘ FS)\n end.\n\nLemma lookup_fun_to_vec {A n} (f : fin n → A) i : fun_to_vec f !!! i = f i.\nProof.\n revert f. induction i as [|n i IH]; intros f; simpl; [done|]. by rewrite IH.\nQed.\n\n(** The function [vmap f v] applies a function [f] element wise to [v]. *)\nNotation vmap := Vector.map.\n\nLemma vlookup_map `(f : A → B) {n} (v : vec A n) i :\n vmap f v !!! i = f (v !!! i).\nProof. by induction v; inv_fin i; eauto. Qed.\nLemma vec_to_list_map `(f : A → B) {n} (v : vec A n) :\n vec_to_list (vmap f v) = f <$> vec_to_list v.\nProof. induction v as [|??? IHv]; simpl; [done|]. by rewrite IHv. Qed.\n\n(** The function [vzip_with f v w] combines the vectors [v] and [w] element\nwise using the function [f]. *)\nNotation vzip_with := Vector.map2.\n\nLemma vlookup_zip_with `(f : A → B → C) {n} (v1 : vec A n) (v2 : vec B n) i :\n vzip_with f v1 v2 !!! i = f (v1 !!! i) (v2 !!! i).\nProof.\n vec_double_ind v1 v2.\n - intros i; inv_fin i.\n - intros n v1 v2 IH a b i.\n inv_fin i; eauto.\nQed.\nLemma vec_to_list_zip_with `(f : A → B → C) {n} (v1 : vec A n) (v2 : vec B n) :\n vec_to_list (vzip_with f v1 v2) =\n zip_with f (vec_to_list v1) (vec_to_list v2).\nProof.\n revert v2. induction v1 as [|??? IHv1]; intros v2; inv_vec v2; intros; simpl; [done|].\n by rewrite IHv1.\nQed.\n\n(** Similar to vlookup, we cannot define [vinsert] as an instance of the\n[Insert] type class, as it has a dependent type. *)\nFixpoint vinsert {A n} (i : fin n) (x : A) : vec A n → vec A n :=\n match i with\n | 0%fin => vec_S_inv _ (λ _ v, x ::: v)\n | FS i => vec_S_inv _ (λ y v, y ::: vinsert i x v)\n end.\n\nLemma vec_to_list_insert {A n} i x (v : vec A n) :\n vec_to_list (vinsert i x v) = insert (fin_to_nat i) x (vec_to_list v).\nProof. induction v as [|??? IHv]; inv_fin i; [done|]. simpl. intros. by rewrite IHv. Qed.\n\nLemma vlookup_insert {A n} i x (v : vec A n) : vinsert i x v !!! i = x.\nProof. by induction i; inv_vec v. Qed.\nLemma vlookup_insert_ne {A n} i j x (v : vec A n) :\n i ≠ j → vinsert i x v !!! j = v !!! j.\nProof.\n induction i as [|?? IHi]; inv_fin j; inv_vec v; simpl; try done.\n intros. apply IHi. congruence.\nQed.\nLemma vlookup_insert_self {A n} i (v : vec A n) : vinsert i (v !!! i) v = v.\nProof. by induction v; inv_fin i; intros; f_equal/=. Qed.\n\nLemma vmap_insert {A B} (f : A → B) (n : nat) i x (v : vec A n) :\n vmap f (vinsert i x v) = vinsert i (f x) (vmap f v).\nProof. induction v; inv_fin i; intros; f_equal/=; auto. Qed.\n\n(** The functions [vtake i v] and [vdrop i v] take the first [i] elements of\na vector [v], respectively remove the first [i] elements of a vector [v]. *)\nFixpoint vtake {A n} (i : fin n) : vec A n → vec A i :=\n match i in fin n return vec A n → vec A i with\n | 0%fin => λ _, [#]\n | FS i => vec_S_inv _ (λ x v, x ::: vtake i v)\n end.\nFixpoint vdrop {A n} (i : fin n) : vec A n → vec A (n - i) :=\n match i in fin n return vec A n → vec A (n - i) with\n | 0%fin => id\n | FS i => vec_S_inv _ (λ _, vdrop i)\n end.\n\nLemma vec_to_list_take {A n} i (v : vec A n) :\n vec_to_list (vtake i v) = take (fin_to_nat i) (vec_to_list v).\nProof. induction i; inv_vec v; intros; f_equal/=; auto. Qed.\nLemma vec_to_list_drop {A n} i (v : vec A n) :\n vec_to_list (vdrop i v) = drop (fin_to_nat i) (vec_to_list v).\nProof. induction i; inv_vec v; intros; f_equal/=; auto. Qed.\n\n(** The function [vreplicate n x] generates a vector with length [n] of elements\nwith value [x]. *)\nFixpoint vreplicate {A} (n : nat) (x : A) : vec A n :=\n match n with 0 => [#] | S n => x ::: vreplicate n x end.\n\nLemma vec_to_list_replicate {A} n (x : A) :\n vec_to_list (vreplicate n x) = replicate n x.\nProof. induction n; by f_equal/=. Qed.\n\nLemma vlookup_replicate {A} n (x : A) i : vreplicate n x !!! i = x.\nProof. induction i; f_equal/=; auto. Qed.\n\nLemma vmap_replicate {A B} (f : A → B) n (x : A) :\n vmap f (vreplicate n x) = vreplicate n (f x).\nProof. induction n; f_equal/=; auto. Qed.\n\n(** Vectors are inhabited and countable *)\nGlobal Instance vec_0_inhabited T : Inhabited (vec T 0) := populate [#].\nGlobal Instance vec_inhabited `{Inhabited T} n : Inhabited (vec T n) :=\n populate (vreplicate n inhabitant).\n\nInstance vec_countable `{Countable A} n : Countable (vec A n).\nProof.\n apply (inj_countable vec_to_list (λ l,\n guard (n = length l) as H; Some (eq_rect _ _ (list_to_vec l) _ (eq_sym H)))).\n intros v. case_option_guard as Hn.\n - rewrite list_to_vec_to_list.\n rewrite (proof_irrel (eq_sym _) Hn). by destruct Hn.\n - by rewrite vec_to_list_length in Hn.\nQed.\n", "meta": {"author": "SkySkimmer", "repo": "stdpp", "sha": "a40580e6d7e6cd16e60aba6deed496a301804c9f", "save_path": "github-repos/coq/SkySkimmer-stdpp", "path": "github-repos/coq/SkySkimmer-stdpp/stdpp-a40580e6d7e6cd16e60aba6deed496a301804c9f/theories/vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.12252320450794524, "lm_q1q2_score": 0.05600985544394579}} {"text": "(** * Induction: Proof by Induction *)\n\n\n(** The next line imports all of our definitions from the\n previous chapter. *)\n\nRequire Export Basics.\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n into [Basics.vo]. (This is like making a .class file from a .java\n file, or a .o file from a .c file.)\n\n Here are two ways to compile your code:\n\n - CoqIDE:\n\n Open [Basics.v].\n In the \"Compile\" menu, click on \"Compile Buffer\".\n\n - Command line:\n\n Run [coqc Basics.v]\n\n *)\n\n(* ###################################################################### *)\n(** * Naming Cases *)\n\n(** The fact that there is no explicit command for moving from\n one branch of a case analysis to the next can make proof scripts\n rather hard to read. In larger proofs, with nested case analyses,\n it can even become hard to stay oriented when you're sitting with\n Coq and stepping through the proof. (Imagine trying to remember\n that the first five subgoals belong to the inner case analysis and\n the remaining seven cases are what remains of the outer one...)\n Disciplined use of indentation and comments can help, but a better\n way is to use the [Case] tactic. *)\n\n(* [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- you can just skip\n over the definition to the example that follows. It uses some\n facilities of Coq that we have not discussed -- the string\n library (just for the concrete syntax of quoted strings) and the\n [Ltac] command, which allows us to declare custom tactics. Kudos\n to Aaron Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n(** Here's an example of how [Case] is used. Step through the\n following proof and observe how the context changes. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\". (* <----- here *)\n reflexivity.\n Case \"b = false\". (* <---- and here *)\n rewrite <- H.\n reflexivity.\nQed.\n\n(** [Case] does something very straightforward: It simply adds a\n string that we choose (tagged with the identifier \"Case\") to the\n context for the current goal. When subgoals are generated, this\n string is carried over into their contexts. When the last of\n these subgoals is finally proved and the next top-level goal\n becomes active, this string will no longer appear in the context\n and we will be able to see that the case where we introduced it is\n complete. Also, as a sanity check, if we try to execute a new\n [Case] tactic while the string left by the previous one is still\n in the context, we get a nice clear error message.\n\n For nested case analyses (e.g., when we want to use a [destruct]\n to solve a goal that has itself been generated by a [destruct]),\n there is an [SCase] (\"subcase\") tactic. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2) *)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c H. destruct c.\n Case \"c = true\".\n reflexivity.\n Case \"c = false\".\n rewrite <- H. destruct b.\n SCase \"b = true\".\n reflexivity.\n SCase \"b = false\".\n reflexivity. Qed.\n(** [] *)\n\n(** There are no hard and fast rules for how proofs should be\n formatted in Coq -- in particular, where lines should be broken\n and how sections of the proof should be indented to indicate their\n nested structure. However, if the places where multiple subgoals\n are generated are marked with explicit [Case] tactics placed at\n the beginning of lines, then the proof will be readable almost no\n matter what choices are made about other aspects of layout.\n\n This is a good place to mention one other piece of (possibly\n obvious) advice about line lengths. Beginning Coq users sometimes\n tend to the extremes, either writing each tactic on its own line\n or entire proofs on one line. Good style lies somewhere in the\n middle. In particular, one reasonable convention is to limit\n yourself to 80-character lines. Lines longer than this are hard\n to read and can be inconvenient to display and print. Many\n editors have features that help enforce this. *)\n\n(* ###################################################################### *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left using a simple argument. The fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... cannot be proved in the same simple way. Just applying\n [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. We could use [destruct n'] to\n get one step further, but since [n] can be arbitrarily large, if we\n try to keep on like this we'll never be done. *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* so far so good... *)\n Case \"n = S n'\".\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** To prove such facts -- indeed, to prove most interesting\n facts about numbers, lists, and other inductively defined sets --\n we need a more powerful reasoning principle: _induction_.\n\n Recall (from high school) the principle of induction over natural\n numbers: If [P(n)] is some proposition involving a natural number\n [n] and we want to show that P holds for _all_ numbers [n], we can\n reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same but the order is backwards: we\n begin with the goal of proving [P(n)] for all [n] and break it\n down (by applying the [induction] tactic) into two separate\n subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n n')]. Here's how this works for the theorem we are trying to\n prove at the moment: *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. In the first branch, [n] is replaced by [0] and\n the goal becomes [0 + 0 = 0], which follows by simplification. In\n the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n n'] is added to the context (with the name [IHn'], i.e., the\n Induction Hypothesis for [n']). The goal in this case becomes [(S\n n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in\n turn follows from the induction hypothesis. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (basic_induction) *)\n\n(** Prove the following lemmas using induction. You might need\n previously proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. induction n as [| n'].\n Case \"n = 0\".\n rewrite -> plus_0_r. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus) *)\n\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n(** [] *)\n\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics\n [destruct] and [induction].\n\n[induction] adds inductive hypothesis.\n\n*)\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Proofs Within Proofs *)\n\n\n(** In Coq, as in informal mathematics, large proofs are very\n often broken into a sequence of theorems, with later proofs\n referring to earlier theorems. Occasionally, however, a proof\n will need some miscellaneous fact that is too trivial (and of too\n little general interest) to bother giving it its own top-level\n name. In such cases, it is convenient to be able to simply state\n and prove the needed \"sub-theorem\" right at the point where it is\n used. The [assert] tactic allows us to do this. For example, our\n earlier proof of the [mult_0_plus] theorem referred to a previous\n theorem named [plus_O_n]. We can also use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n).\n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (Note that we could also name the assertion with\n [as] just as we did above with [destruct] and [induction], i.e.,\n [assert (0 + n = n) as H]. Also note that we mark the proof of\n this assertion with a [Case], both for readability and so that,\n when using Coq interactively, we can see when we're finished\n proving the assertion by observing when the [\"Proof of assertion\"]\n string disappears from the context.) The second goal is the same\n as the one at the point where we invoke [assert], except that, in\n the context, we have the assumption [H] that [0 + n = n]. That\n is, [assert] generates one subgoal where we must prove the\n asserted fact and a second subgoal where we can use the asserted\n fact to make progress on whatever we were trying to prove in the\n first place. *)\n\n(** Actually, [assert] will turn out to be handy in many sorts of\n situations. For example, suppose we want to prove that [(n + m)\n + (p + q) = (m + n) + (p + q)]. The only difference between the\n two sides of the [=] is that the arguments [m] and [n] to the\n first inner [+] are swapped, so it seems we should be able to\n use the commutativity of addition ([plus_comm]) to rewrite one\n into the other. However, the [rewrite] tactic is a little stupid\n about _where_ it applies the rewrite. There are three uses of\n [+] here, and it turns out that doing [rewrite -> plus_comm]\n will affect only the _outer_ one. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)...\n it seems like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To get [plus_comm] to apply at the point where we want it, we can\n introduce a local lemma stating that [n + m = m + n] (for\n the particular [m] and [n] that we are talking about here), prove\n this lemma using [plus_comm], and then use this lemma to do the\n desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Exercise: 4 stars (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction. *)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one.) You may find that [plus_swap] comes in\n handy. *)\n\nTheorem mult_n_Sm : forall n m : nat,\n n * S m = n + n * m.\nProof.\n intros n m. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_swap. reflexivity. Qed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros m n. induction m as [| m'].\n Case \"m = 0\".\n rewrite -> mult_0_r. reflexivity.\n Case \"m = S m'\".\n rewrite -> mult_n_Sm. rewrite <- IHm'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)\n\n(** Prove the following simple fact: *)\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n assert (H: evenb (S (S n')) = evenb n').\n SCase \"Proof of assertion\".\n reflexivity.\n rewrite -> H. rewrite -> IHn'.\n rewrite -> negb_involutive. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before hacking!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n rewrite -> IHn'. reflexivity. Qed.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n intros b. destruct b.\n Case \"b = true\".\n reflexivity.\n Case \"b = false\".\n reflexivity. Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n intros n m p H. induction p as [| p'].\n Case \"p = 0\".\n simpl. rewrite -> H. reflexivity.\n Case \"p = S p'\".\n simpl. rewrite -> IHp'. reflexivity. Qed.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n rewrite -> mult_0_r. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> plus_0_r. reflexivity. Qed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros b c. destruct b.\n Case \"b = true\".\n destruct c.\n SCase \"c = true\".\n reflexivity.\n SCase \"c = false\".\n reflexivity.\n Case \"b = false\".\n destruct c.\n SCase \"c = true\".\n reflexivity.\n SCase \"c = false\".\n reflexivity. Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros n m p. induction p as [| p'].\n Case \"p = 0\".\n rewrite -> mult_0_r. rewrite -> mult_0_r. rewrite -> mult_0_r.\n reflexivity.\n Case \"p = S p'\".\n assert (H1: forall k, k * S p' = S p' * k).\n intros k. rewrite -> mult_comm. reflexivity.\n rewrite -> H1. rewrite -> H1. rewrite -> H1. simpl.\n assert (H2: forall k : nat, p' * k = k * p').\n intros k. rewrite -> mult_comm. reflexivity.\n rewrite -> H2. rewrite -> H2. rewrite -> H2. rewrite -> IHp'.\n rewrite -> plus_assoc. rewrite -> plus_assoc.\n assert (H3: n + n * p' + m = m + n + n * p').\n rewrite -> plus_comm. rewrite -> plus_assoc. reflexivity.\n rewrite -> H3.\n assert (H4: n + m = m + n).\n rewrite -> plus_comm. reflexivity.\n rewrite -> H4. reflexivity. Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'.\n rewrite -> mult_plus_distr_r. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\n(** Prove the following theorem. Putting [true] on the left-hand side\nof the equality may seem odd, but this is how the theorem is stated in\nthe standard library, so we follow suit. Since rewriting\nworks equally well in either direction, we will have no\nproblem using the theorem no matter which way we state it. *)\n\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n rewrite -> IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to. More precisely,\n [replace (t) with (u)] replaces (all copies of) expression [t] in\n the goal by expression [u], and generates [t = u] as an additional\n subgoal. This is often useful when a plain [rewrite] acts on the wrong\n part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)].\n*)\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc. rewrite -> plus_assoc.\n replace (n + m) with (m + n). reflexivity.\n Case \"Proof of replace\".\n rewrite -> plus_comm. reflexivity. Qed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (binary_commute) *)\n(** Recall the [increment] and [binary-to-unary] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that these functions commute -- that is, incrementing a binary\n number and then converting it to unary yields the same result as\n first converting it to unary and then incrementing.\n\n (Before you start working on this exercise, please copy the\n definitions from your solution to the [binary] exercise here so\n that this file can be graded on its own. If you find yourself\n wanting to change your original definitions to make the property\n easier to prove, feel free to do so.) *)\n\nInductive bin : Type :=\n | Z : bin\n | T : bin -> bin\n | M : bin -> bin.\n\nFixpoint inc (b : bin) : bin :=\n match b with\n | Z => M Z (* 0 -> 1 *)\n | T b' => M b' (* 2n -> 2n + 1 *)\n | M b' => T (inc b') (* 2n + 1 -> 2(n + 1) *)\n end.\n\nFixpoint bin2nat (b : bin) : nat :=\n match b with\n | Z => O\n | T b' => (bin2nat b') * 2\n | M b' => S ((bin2nat b') * 2)\n end.\n\nTheorem inc_bin2nat_comm: forall b,\n bin2nat (inc b) = S (bin2nat b).\nProof.\n intros b. induction b as [| b'| b'].\n Case \"b = Z\".\n reflexivity.\n Case \"b = T b'\".\n reflexivity.\n Case \"b = M b'\".\n simpl. rewrite -> IHb'. reflexivity. Qed.\n(** [] *)\n\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n the previous exercise to complete this one.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n*)\n\nFixpoint nat2bin (n : nat) : bin :=\n match n with\n | O => Z\n | S n' => inc (nat2bin n')\n end.\n\nTheorem nat2bin_inverse: forall (n : nat),\n bin2nat (nat2bin n) = n.\nProof.\n intros. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> inc_bin2nat_comm.\n rewrite -> IHn'. reflexivity. Qed.\n\n(**\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, it is not true!\n Explain what the problem is.\n\n (c) Define a function [normalize] from binary numbers to binary\n numbers such that for any binary number b, converting to a\n natural and then back to binary yields [(normalize b)]. Prove\n it.\n\n Again, feel free to change your earlier definitions if this helps\n here.\n*)\n\nDefinition twice (b : bin) : bin :=\n match b with\n | Z => Z\n | c => T c\n end.\n\nFixpoint normalize (b : bin) : bin :=\n match b with\n | Z => Z\n | T b' => twice (normalize b')\n | M b' => inc (twice (normalize b'))\n end.\n\nTheorem inc_twice: forall b,\n inc (inc (twice b)) = twice (inc b).\nProof.\n intros b. destruct b as [|b' |b' ].\n SCase \"b = Z\". reflexivity.\n SCase \"b = T b'\". reflexivity.\n SCase \"b = M b'\". reflexivity.\nQed.\n\nTheorem double_nat2bin_comm: forall n,\n nat2bin (n * 2) = twice (nat2bin n).\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> inc_twice. reflexivity. Qed.\n\nTheorem bin2nat_inverse : forall b,\n nat2bin (bin2nat b) = normalize b.\nProof.\n intros b. induction b as [| b' | b'].\n Case \"b = Z\".\n reflexivity.\n Case \"b = T b'\".\n simpl. rewrite -> double_nat2bin_comm.\n rewrite -> IHb'. reflexivity.\n Case \"b = M b'\".\n simpl. rewrite -> double_nat2bin_comm.\n rewrite -> IHb'. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Advanced Material *)\n\n(** ** Formal vs. Informal Proof *)\n\n(** \"Informal proofs are algorithms; formal proofs are code.\" *)\n\n(** The question of what, exactly, constitutes a \"proof\" of a\n mathematical claim has challenged philosophers for millenia. A\n rough and ready definition, though, could be this: a proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true.\n That is, a proof is an act of communication.\n\n Now, acts of communication may involve different sorts of readers.\n On one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is a simple mechanical check that\n [P] can be derived from a certain set of formal logical rules, and\n the proof is a recipe that guides the program in performing this\n check. Such recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n thus necessarily _informal_. Here, the criteria for success are\n less clearly specified. A \"good\" proof is one that makes the\n reader believe [P]. But the same proof may be read by many\n different readers, some of whom may be convinced by a particular\n way of phrasing the argument, while others may not be. One reader\n may be particularly pedantic, inexperienced, or just plain\n thick-headed; the only way to convince them will be to make the\n argument in painstaking detail. But another reader, more familiar\n in the area, may find all this detail so overwhelming that they\n lose the overall thread. All they want is to be told the main\n ideas, because it is easier to fill in the details for themselves.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader. In practice, however,\n mathematicians have developed a rich set of conventions and idioms\n for writing about complex mathematical objects that, within a\n certain community, make communication fairly reliable. The\n conventions of this stylized form of communication give a fairly\n clear standard for judging proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can ignore\n the informal ones! Formal proofs are useful in many ways, but\n they are _not_ very efficient ways of communicating ideas between\n human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this as a proof. For a human,\n however, it is difficult to make much sense of it. If you're used\n to Coq you can probably step through the tactics one after the\n other in your mind and imagine the state of the context and goal\n stack at each point, but if the proof were even a little bit more\n complicated this would be next to impossible. Instead, a\n mathematician might write it something like this: *)\n(** - _Theorem_: For any [n], [m] and [p],\n n + (m + p) = (n + m) + p.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n 0 + (m + p) = (0 + m) + p.\n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n n' + (m + p) = (n' + m) + p.\n We must show\n (S n') + (m + p) = ((S n') + m) + p.\n By the definition of [+], this follows from\n S (n' + (m + p)) = S ((n' + m) + p),\n which is immediate from the induction hypothesis. [] *)\n\n(** The overall form of the proof is basically similar. This is\n no accident: Coq has been designed so that its [induction] tactic\n generates the same sub-goals, in the same order, as the bullet\n points that a mathematician would write. But there are\n significant differences of detail: the formal proof is much more\n explicit in some ways (e.g., the use of [reflexivity]) but much\n less explicit in others (in particular, the \"proof state\" at any\n given point in the Coq proof is completely implicit, whereas the\n informal proof reminds the reader several times where things\n stand). *)\n\n(** Here is a formal proof that shows the structure more\n clearly: *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, advanced (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative. *)\n(** - _Theorem_: For any [n] and [m],\n n + m = m + n.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n 0 + m = m + 0.\n This follows from the fact that 0 is a \"neutral element\" for [+]\n on the right and on the left.\n\n - Next, suppose [n = S n'], where\n n' + m = m + n'.\n We must show\n (S n') + m = m + (S n').\n By the definition of [+], this follows from\n S (n' + m) = m + (S n'),\n and from induction hypothesis\n S (m + n') = m + (S n'),\n which immediate from the plus_n_Sm. [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n\n Theorem: [true = beq_nat n n] for any [n].\n\n Proof: By induction on [n].\n\n - First, suppose [n = 0]. We must show\n true = beq_nat 0 0.\n This follows directly from the definition of [beq_nat].\n\n - Next, suppose [n = S n'], where\n true = beq_nat n' n'.\n We must show\n true = beq_nat (S n') (S n').\n By the induction hypothesis, this follows from\n beq_nat n' n' = beq_nat (S n') (S n')\n which is immediate from [beq_nat] definition. [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "tymmym", "repo": "software-foundations", "sha": "940149ef3e1e5ae7640497ba392a4e3667dd0412", "save_path": "github-repos/coq/tymmym-software-foundations", "path": "github-repos/coq/tymmym-software-foundations/software-foundations-940149ef3e1e5ae7640497ba392a4e3667dd0412/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404168757891037, "lm_q2_score": 0.18242552825126704, "lm_q1q2_score": 0.05546496546698942}} {"text": "(** * C2: Teoretyczne podstawy teorii typów [TODO] *)\n\n(* begin hide *)\n(*\nTODO-1: Wkleić tutaj opis podstaw teorii typów z mojej pracy magisterskiej.\nTODO 0: Zdeduplikować dwie pierwsze sekcje, bo obie są o termach.\nTODO 1: Osąd `x : A` możemy czytać jako \"x jest typu A\", zaś konkretnie\nTODO 1: `x : nat` jako \"x jest liczbą naturalną\".\nTODO 2: Zrobić więcej ściąg/zadań z czytania różnych rzeczy.\nTODO 3: powiązanie reguł wprowadzania/eliminacji/obliczania/unikalności\nTODO 3: z równoważnościami, czyli w sumie Harmonia.\nTODO 3: A równoważności to nic innego jak konstrukcje uniwersalne.\nTODO 4: Podkreślić gdzieś mocniej, że reguła indukcji mówi,\nTODO 4: że nie ma nic poza tym, co można zrobić konstruktorami.\nTODO 5: Intuicja dla reguł unikalności: dzida składa się z przeddzidzia\nTODO 5: dzidy, śróddzidzia dzidy i zadzidzia dzidy.\nTODO 6: Wprowadzić pojęcie \"motyw eliminacji\" i częściej używać.\nTODO 7: Podkreślić związki teorii typów z rzeczywistością przez\nTODO 7: podkreślenie kwestii silnej normalizacji.\nTODO 8: Opisać parametryczność tuż po opisaniu funkcji i [Type].\n*)\n(* end hide *)\n\n(** Uwaga: ten rozdział jest póki co posklejany z fragmentów innych\n rozdziałów. Czytając go, weź na to poprawkę. W szczególności zawiera on\n zadania, których nie będziesz w stanie zrobić, bo niezbędny do tego\n materiał jest póki co w kolejnym rozdziale. Możesz więc przeczytać\n część teoretyczną, a zadania pominąć (albo w ogóle pominąć cały ten\n rozdział). *)\n\n(** * Typy i termy *)\n\n(** Czym są termy? Są to twory o naturze syntaktycznej (składniowej),\n reprezentujące funkcje, typy, zdania logiczne, predykaty, relacje\n etc. Polskim słowem o najbliższym znaczeniu jest słowo \"wyrażenie\".\n Zamiast prób definiowania termów, co byłoby problematyczne,\n zobaczmy przykłady:\n - [2] — stałe są termami\n - [P] — zmienne są termami\n - [Prop] — typy są termami\n - [fun x : nat => x + 2] — λ-abstrakcje (funkcje) są termami\n - [f x] — aplikacje funkcji do argumentu są termami\n - [if true then 5 else 2] — konstrukcja if-then-else jest termem *)\n\n(** Nie są to wszystkie występujące w Coqu rodzaje termów — jest\n ich nieco więcej.\n\n Kolejnym fundamentalnym pojęciem jest pojęcie typu. W Coqu\n każdy term ma dokładnie jeden, niezmienny typ. Czym są typy?\n Intuicyjnie można powiedzieć, że typ to rodzaj metki, która\n dostarcza nam informacji dotyczących danego termu.\n\n Dla przykładu,\n stwierdzenie [x : nat] informuje nas, że [x] jest liczbą\n naturalną, dzięki czemu wiemy, że możemy użyć go jako argumentu\n dodawania: term [x + 1] jest poprawnie typowany (ang. well-typed),\n tzn. [x + 1 : nat], a więc możemy skonkludować, że [x + 1] również\n jest liczbą naturalną.\n\n Innym przykładem niech będzie stwierdzenie [f : nat -> nat],\n które mówi nam, że [f] jest funkcją, która bierze liczbę\n naturalną i zwraca liczbę naturalną. Dzięki temu wiemy, że term\n [f 2] jest poprawnie typowany i jest liczbą naturalną,\n tzn. [f 2 : nat], zaś term [f f] nie jest poprawnie typowany,\n a więc próba jego użycia, a nawet napisania byłaby błędem.\n\n Typy są tworami absolutnie kluczowymi. Informują nas, z jakimi\n obiektami mamy do czynienia i co możemy z nimi zrobić, a Coq\n pilnuje ścisłego przestrzegania tych reguł. Dzięki temu\n wykluczona zostaje możliwość popełnienia całej gamy różnych\n błędów, które występują w językach nietypowanych, takich jak\n dodanie liczby do ciągu znaków.\n\n Co więcej, system typów Coqa jest jednym z najsilniejszych,\n jakie dotychczas wymyślono, dzięki czemu umożliwia nam wiele\n rzeczy, których prawie żaden inny język programowania nie potrafi,\n jak np. reprezentowanie skomplikowanych obiektów matematycznych\n i dowodzenie twierdzeń. *)\n\n(** * Typy i termy, kanoniczność i uzasadnienie reguł eliminacji *)\n\n(** Co to są termy? Po polsku: wyrażenia. Są to napisy zbudowane według\n pewnych reguł (które będziemy chcieli poznać), które mogą oznaczać\n przeróżne rzeczy: zdania logiczne i ich dowody, programy i ich\n specyfikacje, obiekty matematyczne takie jak liczby czy funkcje,\n struktury danych takie jak napisy czy listy.\n\n Najważniejszym, co wiemy o każdym termie, jest jego typ. Co to jest typ?\n To taki klasyfikator, który mówi, czego możemy się po termie spodziewać -\n można liczyć za pomocą liczb, ale nie za pomocą wartości logicznych.\n Można dowodzić zdań, ale nie napisów. Można skleić ze sobą dwa napisy,\n ale nie napis i funkcję etc.\n\n Każdy term ma tylko jeden typ, więc każdy typ możemy sobie wyobrazić jako\n wielki worek z termami. Dla przykładu, typ [nat], czyli typ liczb\n naturalnych, to worek, w którym są takie wyrażenia, jak:\n - [42]\n - [2 + 2]\n - [10 * 10]\n - jeżeli słowo \"dupa\" zawiera \"i\", to [123], a w przeciwnym wypadku [765]\n - długość listy [[a, b, c, d, e]]\n\n Najważniejsze termy są nazywane elementami. Dla [nat] są to [0], [1],\n [2], [3], [4], [5] i tak dalej. Elementy wyróżnia to, że są w postaci\n normalnej (zwanej też postacią kanoniczną). Znaczy to intuicyjnie, że\n są one ostatecznymi wynikami obliczeń, np.:\n - obliczenie [42] daje [42]\n - obliczenie [2 + 2] daje [4]\n - obliczenie [10 * 10] daje [100]\n - obliczenie ... daje [765]\n - obliczenie długości listy daje [5]\n\n Czym dokładnie są obliczenia, dowiemy się później. Na razie wystarczy\n nam wiedzieć, że każdy term zamknięty, czyli taki, o którym wiadomo\n wystarczająco dużo, oblicza się do postaci normalnej, np. 5 + 1 oblicza\n się do 6. Jeżeli jednak czegoś nie wiadomo, to term się nie oblicza, np.\n n + 1 nie wiadomo ile wynosi, jeżeli nie wiadomo, co oznacza n.\n\n Podsumowując, każdy element jest termem, a każdy term oblicza się do\n postaci normalnej, czyli do elementu. *)\n\n(** * Typy a zbiory *)\n\n(** Z filozoficznego punktu widzenia należy stanowczo odróżnić\n typy od zbiorów, znanych chociażby z teorii zbiorów ZF,\n która jest najpowszechniej używaną podstawą współczesnej\n matematyki:\n - zbiory są materialne, podczas gdy typy są strukturalne.\n Dla przykładu, zbiory {1, 2} oraz {2, 3} mają przecięcie\n równe {2}, które to przecięcie jest podzbiorem każdego\n z nich. W przypadku typów jest inaczej — dwa różne typy\n są zawsze rozłączne i żaden typ nie jest podtypem innego\n - relacja \"x ∈ A\" jest semantyczna, tzn. jest zdaniem\n logicznym i wymaga dowodu. Relacja \"x : A\" jest syntaktyczna,\n a więc nie jest zdaniem logicznym i nie wymaga dowodu —\n Coq jest w stanie sprawdzić automatycznie (bez pomocy\n użytkownika), czy dany term jest danego typu, a często\n także wywnioskować z kontekstu, jakiego typu jest dany\n term\n - zbiór to kolekcja obiektów, do której można włożyć cokolwiek.\n Nowe zbiory mogą być formowane ze starych w sposób niemal\n dowolny (aksjomaty są dość liberalne). Typ to kolekcja obiektów\n o takiej samej wewnętrznej naturze. Zasady formowania nowych\n typów ze starych są bardzo ścisłe\n - teoria zbiorów mówi, jakie obiekty istnieją (np. aksjomat\n zbioru potęgowego mówi, że dla każdego zbioru istnieje zbiór\n wszystkich jego podzbiorów). Teoria typów mówi, w jaki sposób\n obiekty mogą być konstruowane — różnica być może ciężko\n dostrzegalna dla niewprawionego oka, ale znaczna *)\n\n(** * Uniwersa *)\n\n(** Jeżeli przeczytałeś uważnie sekcję \"Typy i termy\" z rozdziału o logice,\n zauważyłeś zapewne stwierdzenie, że typy są termami. W połączeniu ze\n stwierdzeniem, że każdy term ma swój typ, zrodzić musi się pytanie:\n jakiego typu są typy? Zacznijmy od tego, że żeby uniknąć używania mało\n poetyckiego określenia \"typy typów\", typy typów nazywamy uniwersami.\n Czasami używa się też nazwy \"sort\", bo określenie \"jest sortu\" jest\n znacznie krótsze, niż \"należy do uniwersum\" albo \"żyje w uniwersum\". *)\n\n(** [Prop], jak już wiesz, jest uniwersum zdań logicznych. Jeżeli\n [x : A] oraz [A : Prop] (tzn. [A] jest sortu [Prop]), to typ\n [A] możemy interpretować jako zdanie logiczne, a term [x]\n jako jego dowód. Na przykład [I] jest dowodem zdania [True],\n tzn. [I : True], zaś term [42] nie jest dowodem [True], gdyż\n [42 : nat]. *)\n\nCheck True.\n(* ===> True : Prop *)\n\nCheck I.\n(* ===> I : True *)\n\nCheck 42.\n(* ===> 42 : nat *)\n\n(** O ile jednak każde zdanie logiczne jest typem, nie każdy typ jest\n zdaniem — przykładem niech będą liczby naturalne [nat]. Sortem [nat]\n jest [Set]. Niech nie zmyli cię ta nazwa: [Set] nie ma nic wspólnego\n ze zbiorami znanymi choćby z teorii zbiorów ZF.\n\n [Set] jest uniwersum, w którym żyją specyfikacje. Jeżeli [x : A] oraz\n [A : Set] (tzn. sortem [A] jest [Set]), to [A] możemy interpretować\n jako specyfikację pewnej klasy programów, a term [x] jako program,\n który tę specyfikację spełnia (implementuje). Na przykład [2 + 2]\n jest programem, ktory spełnia specyfikację [nat], tzn. [2 + 2 : nat],\n zaś [fun n : nat => n] nie spełnia specyfikacji [nat], gdyż\n [fun n : nat => n : nat -> nat]. *)\n\nCheck nat.\n(* ===> nat : Set *)\n\nCheck 2 + 2.\n(* ===> 2 + 2 : nat *)\n\nCheck fun n : nat => n.\n(* fun n : nat => n : nat -> nat *)\n\n(** Oczywiście w przypadku typu [nat] mówiene o specyfikacji jest trochę\n na wyrost, gdyż określenie \"specyfikacja\" kojarzy nam się z czymś,\n co określa właściwości, jakie powinien mieć spełniający ją program.\n O takich specyfikacjach dowiemy się więcej w kolejnych rozdziałach.\n Choć każda specyfikacja jest typem, to rzecz jasna nie każdy typ jest\n specyfikacją — niektóre typy są przecież zdaniami.\n\n Jeżeli czytasz uważnie, to pewnie wciąż czujesz niedosyt — wszakże\n uniwersa, jako typy, także są termami. Jakiego zatem typu są uniwersa?\n Przekonajmy się. *)\n\nCheck Prop.\n(* ===> Prop : Type *)\n\nCheck Set.\n(* ===> Set : Type *)\n\n(** [Prop] oraz [Set] są sortu [Type]. To stwierdzenie wciąż jednak pewnie\n nie zaspakaja twojej ciekawości. Pójdźmy więc po nitce do kłębka. *)\n\nCheck Type.\n(* ===> Type : Type *)\n\n(** Zdaje się, że osiągnęliśmy kłębek i że [Type] jest typu [Type].\n Rzeczywistość jest jednak o wiele ciekawsza. Gdyby rzeczywiście\n zachodziło [Type : Type], doszłoby do paradoksu znanego jako\n paradoks Girarda (którego omówienie jednak pominiemy). Prawda\n jest inna. *)\n\n(* Set Printing Universes. *)\n\n(** Uwaga: powyższa komenda zadziała jedynie w konsoli (program coqtop).\n Aby osiągnąć ten sam efekt w CoqIDE, zaznacz opcję\n [View > Display universe levels]. *)\n\nCheck Type.\n(* ===> Type (* Top.7 *) : Type (* (Top.7)+1 *) *)\n\n(** Co oznacza ten dziwny napis? Otóż w Coqu mamy do czynienia nie z\n jednym, ale z wieloma (a nawet nieskończenie wieloma) uniwersami.\n Uniwersa te są numerowane liczbami naturalnymi: najniższe uniwersum\n ma numer 0, a każde kolejne o jeden większy. Wobec tego hierarchia\n uniwersów wygląda tak (użyta notacja nie jest tą, której używa Coq;\n została wymyślona ad hoc):\n - [Set] żyje w uniwersum [Type(0)]\n - [Type(0)] żyje w uniwersum [Type(1)]\n - w ogólności, [Type(i)] żyje w uniwersum [Type(i + 1)] *)\n\n(** Aby uniknąć paradoksu, definicje odnoszące się do typów żyjących\n na różnych poziomach hierarchii muszą same bytować w uniwersum\n na poziomie wyższym niż każdy z tych, do których się odwołują.\n Aby to zapewnić, Coq musi pamiętać, na którym poziomie znajduje\n każde użycie [Type] i odpowiednio dopasowywać poziom hierarchii,\n do którego wrzucone zostaną nowe definicje.\n\n Co więcej, w poprzednim rozdziale dopuściłem się drobnego kłamstewka\n twierdząc, że każdy term ma dokładnie jeden typ. W pewnym sensie nie\n jest tak, gdyż powyższa hierarcha jest _kumulatywna_ — znaczy to, że\n jeśli [A : Type(i)], to także [A : Type(j)] dla i < j. Tak więc każdy\n typ, którego sortem jest [Type], nie tylko nie ma unikalnego typu/sortu,\n ale ma ich nieskończenie wiele.\n\n Brawo! Czytając tę sekcję, dotarłeś do króliczej nory i posiadłeś\n wiedzę tajemną, której prawie na pewno nigdy ani nigdzie nie użyjesz.\n Możemy zatem przejść do meritum. *)\n\n(** * Pięć rodzajów reguł *)\n\n(** Być może jeszcze tego nie zauważyłeś, ale większość logiki konstruktywnej,\n programowania funkcyjnego, a przede wszystkim teorii typów kręci się wokół\n pięciu rodzajów reguł.\n Są to reguły:\n - formowania (ang. formation rules)\n - wprowadzania (ang. introduction rules)\n - eliminacji (ang. elimination rules)\n - obliczania (ang. computation rules)\n - unikalności (ang. uniqueness principles) *)\n\n(** W tym podrozdziale przyjrzymy się wszystkim pięciu typom reguł. Zobaczymy\n jak wyglądają, skąd się biorą i do czego służą. Podrozdział będzie miał\n charakter mocno teoretyczny. *)\n\n(** ** Reguły formowania *)\n\n(** Reguły formowania mówią nam, jak tworzyć typy (termy sortów [Set] i [Type])\n oraz zdania (termy sortu [Prop]). Większość z nich pochodzi z nagłówków\n definicji induktywnych. Reguła dla typu [bool] wygląda tak: *)\n\n(*\n ----------\n bool : Set\n*)\n\n(** Ten mistyczny zapis pochodzi z publikacji dotyczących teorii typów.\n Nad kreską znajdują się przesłanki reguły, a pod kreską znajduje się\n konkluzja reguły.\n\n Regułę tę możemy odczytać: [bool] jest typem sortu [Set]. Postać tej\n reguły wynika wprost z definicji typu [bool]. *)\n\nPrint bool.\n(* ===> Inductive bool : Set := true : bool | false : bool *)\n\n(** Powyższej regule formowania odpowiada tutaj fragment [Inductive bool : Set],\n który stwierdza po prostu, że [bool] jest typem sortu [Set].\n\n Nie zawsze jednak reguły formowania są aż tak proste. Reguła dla produktu\n wygląda tak: *)\n\n(*\n A : Type, B : Type\n ------------------\n prod A B : Type\n*)\n\n(** Reguła formowania dla [prod] głosi: jeżeli [A] jest typem sortu [Type]\n oraz [B] jest typem sortu [Type], to [prod A B] jest typem sortu\n [Type]. Jest ona rzecz jasna konsekwencją definicji produktu. *)\n\nPrint prod.\n(* ===> Inductive prod (A B : Type) : Type :=\n pair : A -> B -> A * B *)\n\n(** Regule odpowiada fragment [Inductive prod (A B : Type) : Type]. To,\n co w regule jest nad kreską ([A : Type] i [B : Type]), tutaj występuje\n przed dwukropkiem, po prostu jako argumentu typu [prod]. Jak widać,\n nagłówek typu induktywnego jest po prostu skompresowaną formą reguły\n formowania.\n\n Należy zauważyć, że nie wszystkie reguły formowania pochodzą z definicji\n induktywnych. Tak wygląda reguła formowania dla funkcji (między typami\n sortu [Type]): *)\n\n(*\n A : Type, B : Type\n ------------------\n A -> B : Type\n*)\n\n(** Reguła nie pochodzi z definicji induktywnej, gdyż typ funkcji [A -> B]\n jest typem wbudowanym i nie jest zdefiniowany indukcyjnie. *)\n\n(** **** Ćwiczenie *)\n\n(** Napisz, bez podglądania, jak wyglądają reguły formowania dla [option],\n [nat] oraz [list]. Następnie zweryfikuj swoje odpowiedzi za pomocą\n komendy [Print]. *)\n\n(* begin hide *)\n\n(* [option]\n\n A : Type\n ---------------\n option A : Type\n*)\n\n(* [nat]\n\n ---------\n nat : Set\n*)\n\n(* [list]\n\n A : Type\n -------------\n list A : Type\n*)\n\n(* end hide *)\n\n(** ** Reguły wprowadzania *)\n\n(** Reguły wprowadzania mówią nam, w jaki sposób formować termy danego\n typu. Większość z nich pochodzi od konstruktorów typów induktywnych.\n Dla typu bool reguły wprowadzania wyglądają tak: *)\n\n(*\n -----------\n true : bool\n\n ------------\n false : bool\n*)\n\n(** Reguły te stwierdzają po prostu, że [true] jest termem typu [bool]\n oraz że [false] jest termem typu [bool]. Wynikają one wprost z\n definicji typu [bool] — każda z nich odpowiada jednemu konstruktorowi.\n\n Wobec powyższego nie powinna zaskoczyć cię reguła wprowadzania dla\n produktu: *)\n\n(*\n A : Type, B : Type, a : A, b : B\n --------------------------------\n pair A B a b : prod A B\n*)\n\n(** Jeżeli jednak zaskoczyła cię obecność w regule [A : Type] i [B : Type],\n przyjrzyj się dokładnie typowi konstruktora [pair]: *)\n\nCheck @pair.\n(* ===> pair : forall A B : Type, A -> B -> A * B *)\n\n(** Widać tutaj jak na dłoni, że [pair] jest funkcją zależną biorącą\n cztery argumenty i zwracają wynik, którego typ jest produktem jej\n dwóch pierwszych argumentów.\n\n Podobnie jak w przypadku reguł formowania, nie wszystkie reguły\n wprowadzania pochodzą od konstruktorów typów induktywnych. W\n przypadku funkcji reguła wygląda mniej więcej tak: *)\n\n(*\n Γ |- A -> B : Type, Γ; x : A |- y : B\n -------------------------------------\n Γ |- fun x => y : A -> B\n*)\n\n(** Pojawiło się tu kilka nowych rzeczy: litera Γ oznacza kontekst,\n zaś zapis Γ |- j, że osąd j zachodzi w kontekście Γ. Zapis Γ; j\n oznacza rozszerzenie kontekstu Γ poprzez dodanie do niego osądu j.\n\n Regułę możemy odczytać tak: jeżeli [A -> B] jest typem sortu [Type]\n w kontekście Γ i [y] jest termem typu [B] w kontekście Γ rozszerzonym\n o osąd [x : T], to [fun x => y] jest termem typu [A -> B] w kontekście\n Γ.\n\n Powyższa reguła nazywana jest \"lambda abstrakcją\" (gdyż zazwyczaj jest\n zapisywana przy użyciu symbolu λ zamiast słowa kluczowego [fun], jak\n w Coqu). Nie przejmuj się, jeżeli jej. Znajomość reguł wprowadzania nie\n jest nam potrzebna, by skutecznie posługiwać się Coqiem.\n\n Należy też dodać, że reguła ta jest nieco uproszczona. Pełniejszy\n opis teoretyczny induktywnego rachunku konstrukcji można znaleźć\n w #manualu#. *)\n\n(** **** Ćwiczenie *)\n\n(** Napisz (bez podglądania) jak wyglądają reguły wprowadzania dla\n [option], [nat] oraz [list]. Następnie zweryfikuj swoje odpowiedzi\n za pomocą komendy [Print]. *)\n\n(* begin hide *)\n\n(* [option]\n\n A : Type\n -----------------\n None A : option A\n\n A : Type, x : A\n -----------------\n Some x : option A\n*)\n\n(* [nat]\n\n -------\n 0 : nat\n\n n : nat\n ---------\n S n : nat\n*)\n\n(* [list]\n\n A : Type\n ------------\n nil A : Type\n\n A : Type, h : A, t : list A\n ---------------------------\n h :: t : list A\n*)\n\n(* end hide *)\n\n(** ** Reguły eliminacji *)\n\n(** Reguły eliminacji są w pewien sposób dualne do reguł wprowadzania.\n Tak jak reguły wprowadzania dla typu [T] służą do konstruowania\n termów typu [T] z innych termów, tak reguły eliminacji dla typu [T]\n mówią nam, jak z termów typu [T] skonstruować termy innych typów.\n\n Zobaczmy, jak wygląda jedna z reguł eliminacji dla typu [bool]. *)\n\n(*\n A : Type, x : A, y : A, b : bool\n --------------------------------\n if b then x else y : A\n*)\n\n(** Reguła ta mówi nam, że jeżeli mamy typ [A] oraz dwie wartości\n [x] i [y] typu [A], a także term [b] typu [bool], to możemy\n skonstruować inną wartość typu [A], mianowicie [if b then x\n else y].\n\n Reguła ta jest dość prosta. W szczególności nie jest ona zależna,\n tzn. obie gałęzie [if]a muszą być tego samego typu. Przyjrzyjmy\n się nieco bardziej ogólnej regule. *)\n\n(*\n P : bool -> Type, x : P true, y : P false, b : bool\n ----------------------------------------------------\n bool_rect P x y b : P b\n*)\n\n(** Reguła ta mówi nam, że jeżeli mamy rodzinę typów [P : bool -> Type]\n oraz termy [x] typu [P true] i [y] typu [P false], a także term [b]\n typu [bool], to możemy skonstruować term [bool_rect P x y b] typu\n [P b].\n\n Spójrzmy na tę regułę z nieco innej strony: *)\n\n(*\n P : bool -> Type, x : P true, y : P false\n ----------------------------------------------------\n bool_rect P x y : forall b : bool, P b\n*)\n\n(** Widzimy, że reguły eliminacji dla typu induktywnego [T] służą do\n konstruowania funkcji, których dziedziną jest [T], a więc mówią\n nam, jak \"wyeliminować\" term typu [T], aby uzyskać term innego typu. \n\n Reguły eliminacji występują w wielu wariantach:\n - zależnym i niezależnym — w zależności od tego, czy służą do definiowania\n funkcji zależnych, czy nie.\n - rekurencyjnym i nierekurencyjnym — te druge służą jedynie do\n przeprowadzania rozumowań przez przypadki oraz definiowania funkcji\n przez dopasowanie do wzorca, ale bez rekurencji. Niektóre typy nie\n mają rekurencyjnych reguł eliminacji.\n - pierwotne i wtórne — dla typu induktywnego [T] Coq generuje regułę\n [T_rect], którą będziemy zwać regułą pierwotną. Jej postać wynika\n wprost z definicji typu [T]. Reguły dla typów nieinduktywnych (np.\n funkcji) również będziemy uważać za pierwotne. Jednak nie wszystkie\n reguły są pierwotne — przekonamy się o tym w przyszłości, tworząc\n własne reguły indukcyjne.\n*)\n\n(** Zgodnie z zaprezentowaną klasyfikacją, pierwsza z naszych reguł jest:\n - niezależna, gdyż obie gałęzie [if]a są tego samego typu. Innymi słowy,\n definiujemy term typu [A], który nie jest zależny\n - nierekurencyjna, gdyż typ [bool] nie jest rekurencyjny i wobec tego\n może posiadać jedynie reguły nierekurencyjne\n - wtórna — regułą pierwotną dla [bool] jest [bool_rect] *)\n\n(** Druga z naszych reguł jest:\n - zależna, gdyż definiujemy term typu zależnego [P b]\n - nierekurencyjna z tych samych powodów, co reguła pierwsza\n - pierwotna — Coq wygenerował ją dla nas automatycznie *)\n\n(** W zależności od kombinacji powyższych cech reguły eliminacji mogą\n występować pod różnymi nazwami:\n - reguły indukcyjne są zależne i rekurencyjne. Służą do definiowania\n funkcji, których przeciwdziedzina jest sortu [Prop], a więc do\n dowodzenia zdań przez indukcję\n - rekursory to rekurencyjne reguły eliminacji, które służą do definiowania\n funkcji, których przeciwdziedzina jest sortu [Set] lub [Type] *)\n\n(** Nie przejmuj się natłokiem nazw ani rozróżnień. Powyższą klasyfikację\n wymyśliłem na poczekaniu i nie ma ona w praktyce żadnego znaczenia.\n\n Zauważmy, że podobnie jak nie wszystkie reguły formowania i wprowadzania\n pochodzą od typów induktywnych, tak i nie wszystkie reguły eliminacji\n od nich pochodzą. Kontrprzykładem niech będzie reguła eliminacji dla\n funkcji (niezależnych): *)\n\n(*\n A : Type, B : Type, f : A -> B, x : A\n -------------------------------------\n f x : B\n*)\n\n(** Reguła ta mówi nam, że jeżeli mamy funkcję [f] typu [A -> B] oraz\n argument [x] typu [A], to aplikacja funkcji [f] do argumentu [x]\n jest typu [B].\n\n Zauważmy też, że mimo iż reguły wprowadzania i eliminacji są w pewien\n sposób dualne, to istnieją między nimi różnice.\n\n Przede wszystkim, poza regułami wbudowanymi, obowiązuje prosta zasada:\n jeden konstruktor typu induktywnego — jedna reguła wprowadzania. Innymi\n słowy, reguły wprowadzania dla typów induktywnych pochodzą bezpośrednio\n od konstruktorów i nie możemy w żaden sposób dodać nowych. Są one w\n pewien sposób pierwotne i nie mamy nad nimi (bezpośredniej) kontroli.\n\n Jeżeli chodzi o reguły eliminacji, to są one, poza niewielką ilością\n reguł pierwotnych, w pewnym sensie wtórne —\n możemy budować je z dopasowania do wzorca i rekursji strukturalnej i\n to właśnie te dwie ostatnie idee są w Coqu ideami pierwotnymi. Jeżeli\n chodzi o kontrolę, to możemy swobodnie dodawać nowe reguły eliminacji\n za pomocą twierdzeń lub definiując je bezpośrednio.\n\n Działanie takie jest, w przypadku nieco bardziej zaawansowanych\n twierdzeń niż dotychczas widzieliśmy, bardzo częste. Ba! Częste\n jest także tworzenie reguł eliminacji dla każdej funkcji z osobna,\n perfekcyjnie dopasowanych do kształtu jej rekursji. Jest to nawet\n bardzo wygodne, gdyż Coq potrafi automatycznie wygenerować dla nas\n takie reguły.\n\n Przykładem niestandardowej reguły może być reguła eliminacji dla\n list działająca \"od tyłu\": *)\n\n(*\n A : Type, P : list A -> Prop,\n H : P [[]],\n H' : forall (h : A) (t : list A), P t -> P (t ++ [[h]])\n -------------------------------------------------------------\n forall l : list A, P l\n*)\n\n(** Póki co wydaje mi się, że udowodnienie słuszności tej reguły będzie dla\n nas za trudne. W przyszłości na pewno napiszę coś więcej na temat reguł\n eliminacji, gdyż ze względu na swój \"otwarty\" charakter są one z punktu\n widzenia praktyki najważniejsze.\n\n Tymczasem na otarcie łez zajmijmy się inną, niestandardową regułą dla\n list. *)\n\n(** **** Ćwiczenie *)\n\n(** Udowodnij, że reguła dla list \"co dwa\" jest słuszna. Zauważ, że komenda\n [Fixpoint] może służyć do podawania definicji rekurencyjnych nie tylko\n \"ręcznie\", ale także za pomocą taktyk.\n\n Wskazówka: użycie hipotezy indukcyjnej [list_ind_2] zbyt wcześnie\n ma podobne skutki co wywołanie rekurencyjne na argumencie, który\n nie jest strukturalnie mniejszy. *)\n\nRequire Import List.\nImport ListNotations.\n\nModule EliminationRules.\n\nFixpoint list_ind_2\n (A : Type) (P : list A -> Prop)\n (H0 : P []) (H1 : forall x : A, P [x])\n (H2 : forall (x y : A) (l : list A), P l -> P (x :: y :: l))\n (l : list A) : P l.\n(* begin hide *)\nProof.\n destruct l as [| x [| y t]]; auto.\n apply H2. apply list_ind_2; auto.\nQed.\n(* end hide *)\n\n(** **** Ćwiczenie *)\n\n(** Napisz funkcję [apply], odpowiadającą regule eliminacji dla funkcji\n (niezależnych). Udowodnij jej specyfikację.\n\n Uwaga: notacja \"$$\" na oznaczenie aplikacji funkcji pochodzi z języka\n Haskell i jest tam bardzo często stosowana, gdyż pozwala zaoszczędzić\n stawiania zbędnych nawiasów. *)\n\n(* begin hide *)\nDefinition apply {A B : Type} (f : A -> B) (x : A) : B := f x.\n(* end hide *)\n\nNotation \"f $ x\" := (apply f x) (at level 5).\n\nLemma apply_spec :\n forall (A B : Type) (f : A -> B) (x : A), f $ x = f x.\n(* begin hide *)\nProof. trivial. Qed.\n(* end hide *)\n\nEnd EliminationRules.\n\n(** ** Reguły obliczania *)\n\n(** Poznawszy reguły wprowadzania i eliminacji możemy zadać sobie pytanie:\n jakie są między nimi związki? Jedną z odpowiedzi na to pytanie dają\n reguły obliczania, które określają, w jaki sposób reguły eliminacji\n działają na obiekty stworzone za pomocą reguł wprowadzania. Zobaczmy\n o co chodzi na przykładzie. *)\n\n(*\n A : Type, B : Type, x : A |- e : B, t : A\n -----------------------------------------\n (fun x : A => e) t ≡ e{x/t}\n*)\n\n(** Powyższa reguła nazywa się \"redukcja beta\". Mówi ona, jaki efekt ma\n aplikacja funkcji zrobionej za pomocą lambda abstrakcji do argumentu,\n przy czym aplikacja jest regułą eliminacji dla funkcji, a lambda\n abstrakcja — regułą wprowadzania.\n\n Możemy odczytać ją tak: jeżeli [A] i [B] są typami, zaś [e] termem\n typu [B], w którym występuje zmienna wolna [x] typu [A], to wyrażenie\n [(fun x : A => e) t] redukuje się (symbol ≡) do [e], w którym w miejsce\n zmiennej [x] podstawiono term [t].\n\n Zauważ, że zarówno symbol ≡ jak i notacja [e{x/t}] są tylko nieformalnymi\n zapisami i nie mają żadnego znaczenia w Coqu.\n\n Nie jest tak, że dla każdego typu jest tylko jedna reguła obliczania.\n Jako, że reguły obliczania pokazują związek między regułami eliminacji\n i wprowadzania, ich ilość można przybliżyć prostym wzorem:\n\n ## reguł obliczania = ## reguł eliminacji * ## reguł wprowadzania,\n\n gdzie ## to nieformalny symbol oznaczający \"ilość\". W Coqowej praktyce\n zazwyczaj oznacza to, że reguł obliczania jest nieskończenie wiele,\n gdyż możemy wymyślić sobie nieskończenie wiele reguł eliminacji.\n Przykładem typu, który ma więcej niż jedną regułę obliczania dla danej\n reguły eliminacji, jest [bool]: *)\n\n(*\n P : bool -> Type, x : P true, y : P false\n -----------------------------------------\n bool_rect P x y true ≡ x\n\n P : bool -> Type, x : P true, y : P false\n -----------------------------------------\n bool_rect P x y false ≡ y\n*)\n\n(** Typ [bool] ma dwie reguły wprowadzania pochodzące od dwóch konstruktorów,\n a zatem ich związki z regułą eliminacji [bool_rect] będą opisywać dwie\n reguły obliczania. Pierwsza z nich mówi, że [bool_rect P x y true]\n redukuje się do [x], a druga, że [bool_rect P x y false] redukuje się do\n [y].\n\n Gdyby zastąpić w nich regułe [bool_rect] przez nieco prostszą regułę, w\n której nie występują typy zależne, to można by powyższe reguły zapisać\n tak: *)\n\n(*\n A : Type, x : A, y : A\n -----------------------------------------\n if true then x else y ≡ x\n\n A : Type, x : A, y : A\n -----------------------------------------\n if false then x else y ≡ y\n*)\n\n(** Wygląda dużo bardziej znajomo, prawda?\n\n Na zakończenie wypadałoby napisać, skąd biorą się reguły obliczania. W\n nieco mniej formalnych pracach teoretycznych na temat teorii typów są\n one zazwyczaj uznawane za byty podstawowe, z których następnie wywodzi\n się reguły obliczania takich konstrukcji, jak np. [match].\n\n W Coqu jest na odwrót. Tak jak reguły eliminacji pochodzą od dopasowania\n do wzorca i rekursji, tak reguły obliczania pochdzą od opisanych już\n wcześniej reguł redukcji (beta, delta, jota i zeta), a także konwersji\n alfa. *)\n\n(** **** Ćwiczenie *)\n\n(** Napisz reguły obliczania dla liczb naturalnych oraz list (dla reguł\n eliminacji [nat_ind] oraz [list_ind]). *)\n\n(* begin hide *)\n\n(* Liczbt naturalne.\n\n P : nat -> Prop, H0 : P 0, HS : forall n : nat, P n -> P (S n)\n --------------------------------------------------------------\n nat_ind P H0 HS 0 ≡ H0\n\n P : nat -> Prop, H0 : P 0, HS : forall n : nat, P n -> P (S n), n : nat\n -----------------------------------------------------------------------\n nat_ind P H0 HS (S n) ≡ HS n (nat_ind P H0 HS n)\n\n Listy.\n\n A : Type, P : list A -> Prop, Hnil : P [],\n Hcons : forall (h : A) (t : list A), P t -> P (h :: t)\n ------------------------------------------------------\n list_ind A P Hnil Hcons [] ≡ Hnil\n\n A : Type, P : list A -> Prop, Hnil : P [],\n Hcons : forall (h : A) (t : list A), P t -> P (h :: t),\n h : A, t : list A\n -------------------------------------------------------\n list_ind A P Hnil Hcons (h :: t) ≡\n Hcons h t (list_ind A P Hnil Hcons t) *)\n\n(* end hide *)\n\n(** ** Reguły unikalności *)\n\n(** Kolejną odpowiedzią na pytanie o związki między regułami wprowadzania\n i eliminacji są reguły unikalności. Są one dualne do reguł obliczania\n i określają, w jaki sposób reguły wprowadzania działają na obiekty\n pochodzące od reguł eliminacji. Przyjrzyjmy się przykładowi. *)\n\n(*\n A : Type, B : Type, f : A -> B\n ------------------------------\n (fun x : A => f x) ≡ f\n*)\n\n(** Powyższa reguła unikalności dla funkcji jest nazywana \"redukcją eta\".\n Stwierdza ona, że funkcja stworzona za pomocą abstrakcji [fun x : A],\n której ciałem jest aplikacja [f x] jest definicyjnie równa funkcji [f].\n Regułą wprowadzania dla funkcji jest oczywiście abstrakcja, a regułą\n eliminacji — aplikacja.\n\n Reguły unikalności różnią się jednak dość mocno od reguł obliczania,\n gdyż zamiast równości definicyjnej ≡ mogą czasem używać standardowej,\n zdaniowej równości Coqa, czyli [=]. Nie do końca pasuje też do nich\n stwierdzenie, że określają działanie reguł wprowadzania na reguły\n eliminacji, gdyż zamiast reguł eliminacji mogą w nich występować\n inne byty, zdefiniowane jednak za pomocą reguł eliminacji. Zobaczmy\n o co chodzi na przykładzie. *)\n\n(*\n A : Type, B : Type, p : A * B\n --------------------------------\n (fst p, snd p) = p\n*)\n\n(** Powyższa reguła głosi, że para, której pierwszym elementem jest pierwszy\n element pary [p], a drugim elementem — drugi element pary [p], jest w\n istocie równa parze [p]. W Coqu możemy ją wyrazić (i udowodnić) tak: *)\n\nLemma prod_uniq :\n forall (A B : Type) (p : A * B),\n (fst p, snd p) = p.\nProof.\n destruct p. cbn. trivial.\nQed.\n\n(** Podsumowując, reguły unikalności występują w dwóch rodzajach:\n - dane nam z góry, niemożliwe do wyrażenia bezpośrednio w Coqu i\n używające równości definicyjnej, jak w przypadku redukcji eta\n dla funkcji\n - możliwe do wyrażenia i udowodnienia w Coqu, używające zwykłej\n równości, jak dla produktów i w ogólności dla typów induktywnych *)\n\n(** **** Ćwiczenie *)\n\n(** Sformułuj reguły unikalności dla funkcji zależnych ([forall]), sum\n zależnych ([sigT]) i [unit] (zapisz je w notacji z poziomą kreską).\n Zdecyduj, gdzie w powyższej klasyfikacji mieszczą się te reguły.\n Jeżeli to możliwe, wyraź je i udowodnij w Coqu. *)\n\n(* begin hide *)\n\n(*\n A : Type, P : A -> Type, f : forall x : A, P x\n ----------------------------------------------\n (fun x : A => f x) ≡ f\n*)\n\n(*\n A : Type, P : A -> Type, p : {x : A & P x}\n ------------------------------------------\n (projT1 p, projT2 p) = p\n*)\n\n(*\n u : unit\n --------\n u = tt\n*)\n\n(** Reguła dla funkcji jest pierwszego typu, zaś reguły dla sum zależnych i\n [unit] są drugiego typu. *)\n\nLemma sigT_uniq :\n forall (A : Type) (P : A -> Type) (p : {x : A & P x}),\n existT P (projT1 p) (projT2 p) = p.\nProof.\n intros. destruct p. cbn. f_equal.\nQed.\n\nLemma unit_uniq :\n forall u : unit, u = tt.\nProof.\n destruct u. trivial.\nQed.\n\n(* end hide *)\n\n(** * Metateoria *)\n\n(* begin hide *)\n(** TODO: Podrozdział \"Metateoria\" zakłada, że omówiono wcześniej pojęcie\n TODO: postaci normalnej i silnej normalizowalności. *)\n(* end hide *)\n\n(** Zbliżamy się powoli do końca rozdziału. Z jednej strony sporo się\n nauczyliśmy, ale z drugiej strony fakt ten może budzić dość spory\n niepkój. No bo niby skąd mamy wiedzieć, że cała ta logika (i teoria\n typów też) to nie są zupełne bzdury?\n\n Pisząc ściślej: skąd np. mamy pewność, że logika konstruktywna nie\n jest sprzeczna, tzn. nie można w niej udowodnić [False]? A jakim\n sposobem ustalić, czy przypadkiem nie zrobiłem cię w konia pisząc,\n że nie da się udowodnić prawa wyłączonego środka?\n\n W niniejszym podrozdziale spróbujemy udzielić krótkiej i zwięzłej\n (a co za tym idzie, bardzo zgrubnej i średnio precyzyjnej) odpowiedzi\n na te pytania. Zacznijmy od paru kluczowych uwag. *)\n\n(** ** Preliminaria *)\n\n(** Najpierw będziemy chcieli udowodnić, że logika konstruktywna jest\n niesprzeczna. Co w tym przypadku oznacza słowo \"udowodnić\"? Aż do\n teraz dowodziliśmy twierdzeń _w Coqu/w logice konstruktywnej_, ale\n teraz będziemy chcieli coś udowodnić _o Coqu/o logice konstruktywnej_.\n\n Ta różnica jest bardzo istotna: jeżeli chcemy udowodnić coś o Coqu,\n to nie możemy zrobić tego w Coqu. Wynika to z jednego z twierdzeń\n Gödla, które w uproszczeniu mówi, że jeżeli dany system logiczny\n potrafi wyrazić arytmetykę liczb naturalnych (no wiesz, dodawanie,\n mnożenie i takie tam), to system ten nie może udowodnić swojej\n własnej niesprzeczności.\n\n Jeżeli przeraża cię powyższy akapit, to... taś taś ptaszku, będzie\n dobrze. Parafrazując: żeby udowodnić, że system logiczny nie jest\n sprzeczny, musimy to zrobić w systemie logicznym, który jest od\n niego silniejszy.\n\n Oczywiście wnikliwy umysł wnet dostrzeże tutaj pewien problem.\n Gdy już udowodnimy w silniejszym systemie, że słabszy system\n jest niesprzeczny, to jak mamy się upewnić, czy nasze twierdzenie\n nie jest przypadkiem gówno warte, np. dlatego, że silniejszy system\n jest sprzeczny?\n\n W tym celu wypadałoby udowodnić również niesprzeczność silniejszego\n systemu. Zgodnie z powyższym rozumowaniem trzeba w tym celu mieć\n jeszcze silniejszy system i on również powinien być niesprzeczny, bo\n inaczej z absolutnej matematycznej pewności nici.\n\n Myślę, że widzisz już, dokąd to wszystko zmierza. Tego typu problem\n w filozofii nazywa się _regressus ad infinitum_, co po naszemu znaczy\n po prostu \"cofanie się w nieskończoność\". Niestety w naszym logicznym\n kontekście nie ma on żadnego rozwiązania.\n\n Trochę terminologii: słabszy system (ten, którego niesprzeczności\n chcemy dowieść), bywa zazwyczaj nazywany \"teorią\" lub \"językiem\", a\n silniejszy (ten, w którym dowodzimy) to \"metateoria\" lub \"metajęzyk\".\n Dla zmylenia przeciwnika określeniem \"metateoria\" określa się także\n zbiór właściwości tego słabszego systemu (a zatem np. niesprzeczność\n logiki konstruktywnej jest jej właściwością metateoretyczną).\n\n Uwaga: nie bój się terminologii i żargonu, one nie gryzą.\n\n W praktyce kiedy poważni matematycy (a raczej informatycy i logicy,\n bo matematycy sensu stricto to straszne miernoty w kwestii logiki)\n chcą udowodnić niesprzeczność jakiegoś systemu formalnego, to po\n prostu nie przejmują się niesprzecznością metateorii, w której\n dowodzą. Zazwyczaj taki dowód i tak nie jest sformalizowany, więc\n zwykłe błędy w rozumowaniu są większym problemem, niż sprzeczność\n metateorii. Praktycznym uzasadnieniem na sensowność takiego\n postępowania może być to, że w ulubionej metateorii dowodzącego od\n dawna nie znaleziono sprzeczności (np. w teorii zbiorów ZFC, której\n używa się w takich przypadkach najcześciej, nie znaleziono jej przez\n 100 lat, więc wydaje się być dość bezpieczna).\n\n Teoretycznie, co z tego wychodzi, to względny dowód niesprzeczności,\n czyli twierdzenie postaci \"jeżeli metateoria jest niesprzeczna, to\n teoria jest niesprzeczna\", które w praktyce traktuje się jako\n absolutny dowód niesprzeczności.\n\n Dobra, wystarczy już tego ględzenia. W naszym przypadku po prostu\n zignorujemy problemy filozoficzne i przyjrzymy się nieformalnemu\n dowodowi na to, że logika konstruktywna jest niesprzeczna. *)\n\n(** ** Niesprzeczność *)\n\n(** Dowód jest banalnie prosty. Załóżmy, że istnieje jakiś dowód fałszu.\n\n Przypomnijmy sobie, że Coq jest językiem silnie normalizowalnym.\n Znaczy to, że wszystkie termy obliczają się do postaci normalnej,\n czyli termu, który jest ostatecznym wynikiem obliczeń i nie może\n zostać \"jeszcze bardziej obliczony\".\n\n Ponieważ zdania są typami, to ich certyfikaty również podlegają\n prawom rządzącym obliczeniami. Jak wyglądają certyfikaty na [False]?\n Cóż, teoretycznie mogą być postaci np. [f x], gdzie [f : P -> False],\n zaś [x : P]. Prawdziwe pytanie brzmi jednak: jak wyglądają postacie\n normalne certyfikatów na [False]?\n\n Przypomnijmy, że dla większości typów (a zatem także dla zdań)\n termy w postaci normalnej to te, które pojawiają się w regułach\n wprowadzania i nie inaczej jest dla [False], a ponieważ [False]\n nie ma reguły wprowadzania, to nie ma żadnego certyfikatu na [False],\n który byłby w postaci normalnej.\n\n Ale zaraz! Zgodnie z początkowym założeniem mamy jakiś ceryfikat na\n [False], a zatem na mocy silnej normalizowalności oblicza się on do\n certyfikatu na [False] w postaci normalnej, a to oznacza sprzeczność.\n Wobec tego początkowe założenie było błędne i nie może istnieć żaden\n certyfikat na [False].\n\n Słowem: nie da się udowodnić fałszu, a zatem logika konstruktywna\n jest niesprzeczna. *)\n\n(** ** Niedowodliwość prawa wyłączonego środka *)\n\n(** Podobnie przebiega dowód na niedowodliwość prawa wyłączonego środka.\n Zacznijmy od założenia _a contrario_, że mamy certyfikat na prawo\n wyłączonego środka, czyli [LEM : forall P : Prop, P \\/ ~ P].\n\n Ponieważ Coq jest silnie normalizowalny, to nasz certyfikat oblicza\n się do certyfikatu w postaci normalnej. Jak wygląda postać normalna\n dla naszego certyfikatu? Postacie normalne certyfikatów na kwantyfikację\n uniwersalną [forall x : P, Q] (a zatem także na implikację [P -> Q])\n są postaci [fun p : P => q], a certyfikatów na dysjunkcję [P \\/ Q] są\n postaci [or_introl p] lub [or_intror q].\n\n Czy powyższe fakty wystarczą, by określić, jak wygląda postać normalna\n certyfikatu na prawo wyłączonego środka? Jeszcze nie. Przecież mamy\n do dyspozycji zdanie [P], więc być może da się wycisnąć z niego trochę\n użytecznych informacji, które pozwolą nam zadecydować, czy pójść w lewo,\n czy w prawo, czyż nie?\n\n Otóż nie - Coqowa teoria typów zabrania wykonywania na typach i zdaniach\n dopasowań do wzorca i wszelkich innych operacji, które pozwalałyby podejmować\n decyzje jedynie na podstawie samego typu. Więcej na ten temat dowiemy się\n pod koniec tego rozdziału, gdy będziemy zajmować się parametrycznością.\n\n Teraz możemy już wywnioskować, że nasz certyfikat na prawo wyłączonego środka\n może mieć jedną z dwóch postaci: [fun P : Prop => or_introl p], gdzie [p : P]\n to certyfikat na [p], lub [fun P : Prop => or_intror np], gdzie [np : ~ P] to\n certyfikat na [~ P]. Rozważmy dwa przypadki.\n\n Jeżeli [LEM] ma pierwszą z tych dwóch postaci, to oznacza to w\n zasadzie, że wszystkie zdania są prawdziwe! No bo patrz: jeżeli\n przyjrzymy się [LEM False], to widzimy, że przyjmuje on postać\n [or_introl p], gdzie [p] jest certyfikatem na [False], ale wiemy\n już, że [False] nie da się udowodnić.\n\n Podobnie gdy [LEM] ma drugą z tych postaci. Wtedy [LEM True] jest\n postaci [or_intror p], gdzie [p] to certyfikat na [True -> False],\n a zatem [p I] to certyfikat na [False], ale znów - fałszu nie da\n się udowodnić!\n\n Ponieważ w obu przypadkach uzyskaliśmy sprzeczność, a [LEM] nie\n może być żadnej innej postaci, konkluzja jest oczywista: początkowe\n założenie było błędne i certyfikat na prawo wyłączonego środka nie\n istnieje. *)\n\n(** ** Konkluzja *)\n\n(** Silna normalizowalność jest jedną z kluczowych metateoretycznych\n właściwości logik i języków programowania. Wynikają z niej nie\n tylko inne metateoretyczne właściwości tradycyjnie uznawane za\n ważniejsze, jak niesprzeczność, ale także bardziej ciekawostkowe,\n jak niedowodliwość prawa wyłączonego środka.\n\n Nie przejmuj się, jeżeli nie do końca rozumiesz (albo wcale nie\n rozumiesz) powyższe wywody (szczególnie preliminaria) lub dowody.\n Ich rozumienie nie jest niezbędne do skutecznego dowodzenia ani\n programowania. Ba! Wydaje mi się, że jest całkiem na odwrót: żeby\n zrozumieć je na intuicyjnym poziomie, potrzeba sporo praktycznego\n doświadczenia w programowaniu i dowodzeniu. Jeżeli go nabędziesz,\n powyższe wywody i dowody nagle staną się łatwe, miłe i przyjemne\n (i puszyste i mięciutkie!). Wróć do nich za jakiś, żeby się o tym\n przekonać. *)\n\n(** * Parametryczność *)\n\n(* begin hide *)\n\n(** TODO: Odkłamać kwestię i wyjaśnić polimorfizmu.\n Najlepiej zrobić to za pomocą podziału na funkcje parametryczne\n (czyli takie, które na wszystkich typach działają tak samo) oraz\n ezoteryczną homoklasyczną magię, która wszystko to psuje. *)\n\n(** Niech [A B : Type]. Zadajmy sobie następujące pytanie: ile jest funkcji\n typu [A -> B]? Żeby ułatwić sobie zadanie, ograniczmy się jedynie do\n typów, które mają skończoną ilość elementów.\n\n Nietrudno przekonać się, że ich ilość to |B|^|A|, gdzie ^ oznacza\n potęgowanie, zaś |T| to ilość elementów typu [T] (ta notacja nie ma\n nic wspólnego z Coqiem — zaadaptowałem ją z teorii zbiorów jedynie\n na potrzeby tego podrozdziału).\n\n Udowodnić ten fakt możesz (choć póki co nie w Coqu) posługując się\n indukcją po ilości elementów typu [A]. Jeżeli [A] jest pusty, to\n jest tylko jedna taka funkcja, o czym przekonałeś się już podczas\n ćwiczeń w podrozdziale o typie [Empty_set]. *)\n\n(** **** Ćwiczenie *)\n\n(** Udowodnij (nieformalnie, na papierze), że w powyższym akapicie nie\n okłamałem cię. *)\n\n(** **** Ćwiczenie *)\n\n(** Zdefiniuj wszystkie możliwe funkcje typu [unit -> unit], [unit -> bool]\n i [bool -> bool]. *)\n\n(** Postawmy sobie teraz trudniejsze pytanie: ile jest funkcji typu\n [forall A : Type, A -> A]? W udzieleniu odpowiedzi pomoże nam\n parametryczność — jedna z właściwości Coqowego polimorfizmu.\n\n Stwierdzenie, że polimorfizm w Coqu jest parametryczny, oznacza, że\n funkcja biorąca typ jako jeden z argumentów działa w taki sam sposób\n niezależnie od tego, jaki typ przekażemy jej jako argument.\n\n Konsekwencją tego jest, że funkcje polimorficzne nie wiedzą (i nie\n mogą wiedzieć), na wartościach jakiego typu operują. Wobec tego\n elementem typu [forall A : Type, A -> A] nie może być funkcja, która\n np. dla typu [nat] stale zwraca [42], a dla innych typów po prostu\n zwraca przekazany jej argument.\n\n Stąd konkludujemy, że typ [forall A : Type, A -> A] ma tylko jeden\n element, a mianowicie polimorficzną funkcję identycznościową. *)\n\nDefinition id' : forall A : Type, A -> A :=\n fun (A : Type) (x : A) => x.\n\n(** **** Ćwiczenie *)\n\n(** Zdefiniuj wszystkie elementy następujących typów lub udowodnij, że\n istnienie choć jednego elementu prowadzi do sprzeczności:\n - [forall A : Type, A -> A -> A]\n - [forall A : Type, A -> A -> A -> A]\n - [forall A B : Type, A -> B]\n - [forall A B : Type, A -> B -> A]\n - [forall A B : Type, A -> B -> B]\n - [forall A B : Type, A -> B -> A * B]\n - [forall A B : Type, A -> B -> sum A B]\n - [forall A B C : Type, A -> B -> C]\n - [forall A : Type, option A -> A]\n - [forall A : Type, list A -> A] *)\n\nLemma no_such_fun :\n (forall A B : Type, A -> B) -> False.\nProof.\n intros. exact (X nat False 42).\nQed.\n\nLemma no_such_fun_2 :\n (forall A B C : Type, A -> B -> C) -> False.\nProof.\n intro H. apply (H True True); trivial.\nQed.\n\nLemma no_such_fun_3 :\n (forall A : Type, option A -> A) -> False.\nProof.\n intro H. apply H. exact None.\nQed.\n\nLemma no_such_fun_4 :\n (forall A : Type, list A -> A) -> False.\nProof.\n intro H. apply H. exact nil.\nQed.\n(* end hide *)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/book/C2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.13117322546005344, "lm_q1q2_score": 0.054423619842815504}} {"text": "(** * Subtyping *)\n\n(* $Date: 2011-05-07 21:28:52 -0400 (Sat, 07 May 2011) $ *)\n\nRequire Export MoreStlc.\n\n(* ###################################################### *)\n(** * Concepts *)\n\n(** We now turn to the study of _subtyping_, perhaps the most\n characteristic feature of the static type systems used by many\n recently designed programming languages. *)\n\n(* ###################################################### *)\n(** ** A Motivating Example *)\n\n(** In the simply typed lamdba-calculus with records, the term\n<<\n (\\r:{y:Nat}. (r.y)+1) {x=10,y=11}\n>>\n is not typable: it involves an application of a function that wants\n a one-field record to an argument that actually provides two\n fields, while the [T_App] rule demands that the domain type of the\n function being applied must match the type of the argument\n precisely. \n\n But this is silly: we're passing the function a _better_ argument\n than it needs! The only thing the body of the function can\n possibly do with its record argument [r] is project the field [y]\n from it: nothing else is allowed by the type. So the presence or\n absence of an extra [x] field should make no difference at all.\n So, intuitively, it seems that this function should be applicable\n to any record value that has at least a [y] field.\n\n Looking at the same thing from another point of view, a record with\n more fields is \"at least as good in any context\" as one with just a\n subset of these fields, in the sense that any value belonging to\n the longer record type can be used _safely_ in any context\n expecting the shorter record type. If the context expects\n something with the shorter type but we actually give it something\n with the longer type, nothing bad will happen (formally, the\n program will not get stuck).\n\n The general principle at work here is called _subtyping_. We say\n that \"[S] is a subtype of [T]\", informally written [S <: T], if a\n value of type [S] can safely be used in any context where a value\n of type [T] is expected. The idea of subtyping applies not only to\n records, but to all of the type constructors in the language --\n functions, pairs, etc. *)\n\n(** ** Subtyping and Object-Oriented Languages *)\n\n(** Subtyping plays a fundamental role in many programming\n languages -- in particular, it is closely related to the notion of\n _subclassing_ in object-oriented languages.\n\n An _object_ (in Java, C[#], etc.) can be thought of as a record,\n some of whose fields are functions (\"methods\") and some of whose\n fields are data values (\"fields\" or \"instance variables\").\n Invoking a method [m] of an object [o] on some arguments [a1..an]\n consists of projecting out the [m] field of [o] and applying it to\n [a1..an].\n\n The type of an object can be given as either a _class_ or an\n _interface_. Both of these provide a description of which methods\n and which data fields the object offers.\n\n Classes and interfaces are related by the _subclass_ and\n _subinterface_ relations. An object belonging to a subclass (or\n subinterface) is required to provide all the methods and fields of\n one belonging to a superclass (or superinterface), plus possibly\n some more.\n\n The fact that an object from a subclass (or sub-interface) can be\n used in place of one from a superclass (or super-interface) provides\n a degree of flexibility that is is extremely handy for organizing\n complex libraries. For example, a graphical user interface\n toolkit like Java's Swing framework might define an abstract\n interface [Component] that collects together the common fields and\n methods of all objects having a graphical representation that can\n be displayed on the screen and that can interact with the user.\n Examples of such object would include the buttons, checkboxes, and\n scrollbars of a typical GUI. A method that relies only on this\n common interface can now be applied to any of these objects.\n\n Of course, real object-oriented languages include many other\n features besides these. Fields can be updated. Fields and\n methods can be declared [private]. Classes also give _code_ that\n is used when constructing objects and implementing their methods,\n and the code in subclasses cooperate with code in superclasses via\n _inheritance_. Classes can have static methods and fields,\n initializers, etc., etc.\n\n To keep things simple here, we won't deal with any of these\n issues -- in fact, we won't even talk any more about objects or\n classes. (There is a lot of discussion in Types and Programming\n Languages, if you are interested.) Instead, we'll study the core\n concepts behind the subclass / subinterface relation in the\n simplified setting of the STLC. *)\n\n(** ** The Subsumption Rule *)\n\n(** Our goal for this chapter is to add subtyping to the simply typed\n lambda-calculus (with products). This involves two steps:\n\n - Defining a binary _subtype relation_ between types.\n\n - Enriching the typing relation to take subtyping into account.\n\n The second step is actually very simple. We add just a single rule\n to the typing relation -- the so-called _rule of subsumption_:\n[[[\n Gamma |- t : S S <: T\n ------------------------- (T_Sub)\n Gamma |- t : T\n]]]\n This rule says, intuitively, that we can \"forget\" some of the\n information that we know about a term. *)\n(** For example, we may know that [t] is a record with two\n fields (e.g., [S = {x:A->A, y:B->B}]], but choose to forget about\n one of the fields ([T = {y:B->B}]) so that we can pass [t] to a\n function that expects just a single-field record. *)\n\n(** ** The Subtype Relation *)\n\n(** The first step -- the definition of the relation [S <: T] -- is\n where all the action is. Let's look at each of the clauses of its\n definition. *)\n\n(** *** Products *)\n\n(** First, product types. We consider one pair to be \"better than\"\n another if each of its components is.\n[[[\n S1 <: T1 S2 <: T2\n -------------------- (S_Prod)\n S1*S2 <: T1*T2\n]]]\n*)\n\n(** *** Arrows *)\n\n(** Suppose we have two functions [f] and [g] with these types:\n<<\n f : C -> {x:A,y:B} \n g : (C->{y:B}) -> D\n>>\n That is, [f] is a function that yields a record of type\n [{x:A,y:B}], and [g] is a higher-order function that expects\n its (function) argument to yield a record of type [{y:B}]. (And\n suppose, even though we haven't yet discussed subtyping for\n records, that [{x:A,y:B}] is a subtype of [{y:B}]) Then the\n application [g f] is safe even though their types do not match up\n precisely, because the only thing [g] can do with [f] is to apply\n it to some argument (of type [C]); the result will actually be a\n two-field record, while [g] will be expecting only a record with a\n single field, but this is safe because the only thing [g] can then\n do is to project out the single field that it knows about, and\n this will certainly be among the two fields that are present.\n\n This example suggests that the subtyping rule for arrow types\n should say that two arrow types are in the subtype relation if\n their results are:\n[[[\n S2 <: T2\n ---------------- (S_Arrow2)\n S1->S2 <: S1->T2\n]]]\n We can generalize this to allow the arguments of the two arrow\n types to be in the subtype relation as well:\n[[[\n T1 <: S1 S2 <: T2\n -------------------- (S_Arrow)\n S1->S2 <: T1->T2\n]]]\n Notice, here, that the argument types are subtypes \"the other way\n round\": in order to conclude that [S1->S2] to be a subtype of\n [T1->T2], it must be the case that [T1] is a subtype of [S1]. The\n arrow constructor is said to be _contravariant_ in its first\n argument and _covariant_ in its second.\n\n The intuition is that, if we have a function [f] of type [S1->S2],\n then we know that [f] accepts elements of type [S1]; clearly, [f]\n will also accept elements of any subtype [T1] of [S1]. The type of\n [f] also tells us that it returns elements of type [S2]; we can\n also view these results belonging to any supertype [T2] of\n [S2]. That is, any function [f] of type [S1->S2] can also be viewed\n as having type [T1->T2]. *)\n\n(** *** Top *)\n\n(** It is natural to give the subtype relation a maximal element -- a\n type that lies above every other type and is inhabited by\n all (well-typed) values. We do this by adding to the language one\n new type constant, called [Top], together with a subtyping rule\n that places it above every other type in the subtype relation:\n[[[\n -------- (S_Top)\n S <: Top\n]]]\n The [Top] type is an analog of the [Object] type in Java and C[#]. *)\n\n(** *** Structural Rules *)\n\n(** To finish off the subtype relation, we add two \"structural rules\"\n that are independent of any particular type constructor: a rule of\n _transitivity_, which says intuitively that, if [S] is better than\n [U] and [U] is better than [T], then [S] is better than [T]...\n[[[\n S <: U U <: T\n ---------------- (S_Trans)\n S <: T\n]]]\n ... and a rule of _reflexivity_, since any type [T] is always just\n as good as itself:\n[[[\n ------ (S_Refl)\n T <: T\n]]]\n*)\n\n(** *** Records *)\n\n(** What about subtyping for record types? \n\n The basic intuition about subtyping for record types is that it is\n always safe to use a \"bigger\" record in place of a \"smaller\" one.\n That is, given a record type, adding extra fields will always\n result in a subtype. If some code is expecting a record with\n fields [x] and [y], it is perfectly safe for it to receive a record\n with fields [x], [y], and [z]; the [z] field will simply be ignored.\n For example,\n<<\n {x:Nat,y:Bool} <: {x:Nat}\n {x:Nat} <: {}\n>>\n This is known as \"width subtyping\" for records.\n\n We can also create a subtype of a record type by replacing the type\n of one of its fields with a subtype. If some code is expecting a\n record with a field [x] of type [T], it will be happy with a record\n having a field [x] of type [S] as long as [S] is a subtype of\n [T]. For example,\n<<\n {a:{x:Nat}} <: {a:{}}\n>>\n This is known as \"depth subtyping\".\n\n Finally, although the fields of a record type are written in a\n particular order, the order does not really matter. For example, \n<<\n {x:Nat,y:Bool} <: {y:Bool,x:Nat}\n>>\n This is known as \"permutation subtyping\".\n\n We could try formalizing these requirements in a single subtyping\n rule for records as follows:\n[[[\n for each jk in j1..jn,\n exists ip in i1..im, such that\n jk=ip and Sp <: Tk\n ---------------------------------- (S_Rcd)\n {i1:S1...im:Sm} <: {j1:T1...jn:Tn}\n]]]\n That is, the record on the left should have all the field labels of\n the one on the right (and possibly more), while the types of the\n common fields should be in the subtype relation. However, This rule\n is rather heavy and hard to read. If we like, we can decompose it\n into three simpler rules, which can be combined using [S_Trans] to\n achieve all the same effects.\n\n First, adding fields to the end of a record type gives a subtype:\n[[[\n n > m\n --------------------------------- (S_RcdWidth)\n {i1:T1...in:Tn} <: {i1:T1...im:Tm} \n]]]\n We can use [S_RcdWidth] to drop later fields of a multi-field\n record while keeping earlier fields, showing for example that\n [{y:B, x:A} <: {y:B}].\n\n Second, we can apply subtyping inside the components of a compound\n record type:\n[[[\n S1 <: T1 ... Sn <: Tn\n ---------------------------------- (S_RcdDepth)\n {i1:S1...in:Sn} <: {i1:T1...in:Tn}\n]]]\n For example, we can use [S_RcdDepth] and [S_RcdWidth] together to\n show that [{y:{z:B}, x:A} <: {y:{}}].\n\n Third, we need to be able to reorder fields. The example we\n originally had in mind was [{x:A,y:B} <: {y:B}]. We\n haven't quite achieved this yet: using just [S_RcdDepth] and\n [S_RcdWidth] we can only drop fields from the _end_ of a record\n type. So we need:\n[[[\n {i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}\n --------------------------------------------------- (S_RcdPerm)\n {i1:S1...in:Sn} <: {i1:T1...in:Tn}\n]]]\n\n Further examples:\n - [{x:A,y:B}] <: [{y:B,x:A}].\n - [{}->{j:A} <: {k:B}->Top]\n - [Top->{k:A,j:B} <: C->{j:B}]\n*)\n\n(** It is worth noting that real languages may choose not to adopt\n all of these subtyping rules. For example, in Java:\n\n - A subclass may not change the argument or result types of a\n method of its superclass (i.e., no depth subtyping or no arrow\n subtyping, depending how you look at it).\n\n - Each class has just one superclass (\"single inheritance\" of\n classes)\n\n - Each class member (field or method) can be assigned a single\n index, adding new indices \"on the right\" as more members are\n added in subclasses (i.e., no permutation for classes)\n\n - A class may implement multiple interfaces -- so-called \"multiple\n inheritance\" of interfaces (i.e., permutation is allowed for\n interfaces). *)\n\n(** *** Records, via Products and Top (optional) *)\n\n(** Exactly how we formalize all this depends on how we are choosing\n to formalize records and their types. If we are treating them as\n part of the core language, then we need to write down subtyping\n rules for them. The file [RecordSub.v] shows how this extension\n works.\n\n On the other hand, if we are treating them as a derived form that\n is desugared in the parser, then we shouldn't need any new rules:\n we should just check that the existing rules for subtyping product\n and [Unit] types give rise to reasonable rules for record\n subtyping via this encoding. To do this, we just need to make one\n small change to the encoding described earlier: instead of using\n [Unit] as the base case in the encoding of tuples and the \"don't\n care\" placeholder in the encoding of records, we use [Top]. So:\n<<\n {a:Nat, b:Nat} ----> {Nat,Nat} i.e. (Nat,(Nat,Top))\n {c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e. (Nat,(Top,(Nat,Top)))\n>>\n The encoding of record values doesn't change at all. It is\n easy (and instructive) to check that the subtyping rules above are\n validated by the encoding. For the rest of this chapter, we'll\n follow this approach. *)\n\n\n(* ###################################################### *)\n(** * Core definitions *)\n\n(** We've already sketched the significant extensions that we'll need\n to make to the STLC: (1) add the subtype relation and (2) extend\n the typing relation with the rule of subsumption. To make\n everything work smoothly, we'll also implement some technical\n improvements to the presentation from the last chapter. The rest\n of the definitions -- in particular, the syntax and operational\n semantics of the language -- are identical to what we saw in the\n last chapter. Let's first do the identical bits. *)\n\n(* ################################### *)\n(** *** Syntax *)\n\n(** Just for the sake of more interesting examples, we'll make one\n more very small extension to the pure STLC: an arbitrary set of\n additional _base types_ like [String], [Person], [Window], etc.\n We won't bother adding any constants belonging to these types or\n any operators on them, but we could easily do so. *)\n\n(** In the rest of the chapter, we formalize just base types,\n booleans, arrow types, [Unit], and [Top], leaving product types as\n an exercise. *)\n\nInductive ty : Type :=\n | ty_Top : ty\n | ty_Bool : ty\n | ty_base : id -> ty\n | ty_arrow : ty -> ty -> ty\n | ty_Unit : ty\n.\n\nTactic Notation \"ty_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"ty_Top\" | Case_aux c \"ty_Bool\" \n | Case_aux c \"ty_base\" | Case_aux c \"ty_arrow\" \n | Case_aux c \"ty_Unit\" | \n ].\n\nInductive tm : Type :=\n | tm_var : id -> tm\n | tm_app : tm -> tm -> tm\n | tm_abs : id -> ty -> tm -> tm\n | tm_true : tm\n | tm_false : tm\n | tm_if : tm -> tm -> tm -> tm\n | tm_unit : tm \n.\n\nTactic Notation \"tm_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"tm_var\" | Case_aux c \"tm_app\" \n | Case_aux c \"tm_abs\" | Case_aux c \"tm_true\" \n | Case_aux c \"tm_false\" | Case_aux c \"tm_if\"\n | Case_aux c \"tm_unit\" \n ].\n\n(* ################################### *)\n(** *** Substitution *)\n\n(** The definition of substitution remains the same as for the\n ordinary STLC. *)\n\nFixpoint subst (s:tm) (x:id) (t:tm) : tm :=\n match t with\n | tm_var y => \n if beq_id x y then s else t\n | tm_abs y T t1 => \n tm_abs y T (if beq_id x y then t1 else (subst s x t1))\n | tm_app t1 t2 => \n tm_app (subst s x t1) (subst s x t2)\n | tm_true => \n tm_true\n | tm_false => \n tm_false\n | tm_if t1 t2 t3 => \n tm_if (subst s x t1) (subst s x t2) (subst s x t3)\n | tm_unit => \n tm_unit \n end.\n\n(* ################################### *)\n(** *** Reduction *)\n\n(** Likewise the definitions of the [value] property and the [step]\n relation. *)\n\nInductive value : tm -> Prop :=\n | v_abs : forall x T t,\n value (tm_abs x T t)\n | t_true : \n value tm_true\n | t_false : \n value tm_false\n | v_unit : \n value tm_unit\n.\n\nHint Constructors value.\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n | ST_AppAbs : forall x T t12 v2,\n value v2 ->\n (tm_app (tm_abs x T t12) v2) ==> (subst v2 x t12)\n | ST_App1 : forall t1 t1' t2,\n t1 ==> t1' ->\n (tm_app t1 t2) ==> (tm_app t1' t2)\n | ST_App2 : forall v1 t2 t2',\n value v1 ->\n t2 ==> t2' ->\n (tm_app v1 t2) ==> (tm_app v1 t2')\n | ST_IfTrue : forall t1 t2,\n (tm_if tm_true t1 t2) ==> t1\n | ST_IfFalse : forall t1 t2,\n (tm_if tm_false t1 t2) ==> t2\n | ST_If : forall t1 t1' t2 t3,\n t1 ==> t1' ->\n (tm_if t1 t2 t3) ==> (tm_if t1' t2 t3)\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"ST_AppAbs\" | Case_aux c \"ST_App1\" \n | Case_aux c \"ST_App2\" | Case_aux c \"ST_IfTrue\" \n | Case_aux c \"ST_IfFalse\" | Case_aux c \"ST_If\" \n ].\n\nHint Constructors step.\n\n(* ###################################################################### *)\n(** * Subtyping *)\n\n(** Now we come to the interesting part. We begin by defining\n the subtyping relation and developing some of its important\n technical properties. *)\n\n(* ################################### *)\n(** ** Definition *)\n\n(** The definition of subtyping is just what we sketched in the\n motivating discussion. *)\n\nInductive subtype : ty -> ty -> Prop :=\n | S_Refl : forall T,\n subtype T T\n | S_Trans : forall S U T,\n subtype S U ->\n subtype U T ->\n subtype S T\n | S_Top : forall S,\n subtype S ty_Top\n | S_Arrow : forall S1 S2 T1 T2,\n subtype T1 S1 ->\n subtype S2 T2 ->\n subtype (ty_arrow S1 S2) (ty_arrow T1 T2)\n.\n\n(** Note that we don't need any special rules for base types: they are\n automatically subtypes of themselves (by [S_Refl]) and [Top] (by\n [S_Top]), and that's all we want. *)\n\nHint Constructors subtype.\n\nTactic Notation \"subtype_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"S_Refl\" | Case_aux c \"S_Trans\"\n | Case_aux c \"S_Top\" | Case_aux c \"S_Arrow\" \n ].\n\n(* ############################################### *)\n(** ** Subtyping Examples and Exercises *)\n\nModule Examples.\n\nNotation x := (Id 0).\nNotation y := (Id 1).\nNotation z := (Id 2).\n\nNotation A := (ty_base (Id 6)).\nNotation B := (ty_base (Id 7)).\nNotation C := (ty_base (Id 8)).\n\nNotation String := (ty_base (Id 9)).\nNotation Float := (ty_base (Id 10)).\nNotation Integer := (ty_base (Id 11)).\n\n(** **** Exercise: 2 stars, optional (subtyping judgements) *)\n\n(** (Do this exercise after you have added product types to the\n language, at least up to this point in the file).\n\n Using the encoding of records into pairs, define pair types\n representing the record types\n[[\n Person := { name : String }\n Student := { name : String ; \n gpa : Float }\n Employee := { name : String ;\n ssn : Integer }\n]]\n*)\nDefinition Person : ty := \n(* FILL IN HERE *) admit.\nDefinition Student : ty := \n(* FILL IN HERE *) admit.\nDefinition Employee : ty := \n(* FILL IN HERE *) admit.\n\nExample sub_student_person :\n subtype Student Person.\nProof. \n(* FILL IN HERE *) Admitted.\n\nExample sub_employee_person :\n subtype Employee Person.\nProof. \n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nExample subtyping_example_0 :\n subtype (ty_arrow C Person) \n (ty_arrow C ty_Top).\n(* C->Person <: C->Top *)\nProof.\n apply S_Arrow.\n apply S_Refl. auto.\nQed.\n\n(** The following facts are mostly easy to prove in Coq. To get\n full benefit from the exercises, make sure you also\n understand how to prove them on paper! *)\n\n(** **** Exercise: 1 star, optional (subtyping_example_1) *)\nExample subtyping_example_1 :\n subtype (ty_arrow ty_Top Student) \n (ty_arrow (ty_arrow C C) Person).\n(* Top->Student <: (C->C)->Person *)\nProof with eauto.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (subtyping_example_2) *)\nExample subtyping_example_2 :\n subtype (ty_arrow ty_Top Person) \n (ty_arrow Person ty_Top).\n(* Top->Person <: Person->Top *)\nProof with eauto.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd Examples.\n\n(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)\n(** Suppose we have types [S], [T], [U], and [V] with [S <: T]\n and [U <: V]. Which of the following subtyping assertions\n are then true? Write _true_ or _false_ after each one. \n (Note that [A], [B], and [C] are base types.)\n\n - [T->S <: T->S]\n\n - [Top->U <: S->Top]\n\n - [(C->C) -> (A*B) <: (C->C) -> (Top*B)]\n\n - [T->T->U <: S->S->V]\n\n - [(T->T)->U <: (S->S)->V]\n\n - [((T->S)->T)->U <: ((S->T)->S)->V]\n\n - [S*V <: T*U]\n\n[]\n*)\n\n(** **** Exercise: 1 star (subtype_instances_tf_2) *)\n(** Which of the following statements are true? Write TRUE or FALSE\n after each one.\n[[\n forall S T,\n S <: T ->\n S->S <: T->T\n\n forall S T,\n S <: A->A ->\n exists T,\n S = T->T /\\ T <: A\n\n forall S T1 T1,\n S <: T1 -> T2 ->\n exists S1 S2,\n S = S1 -> S2 /\\ T1 <: S1 /\\ S2 <: T2 \n\n exists S,\n S <: S->S \n\n exists S,\n S->S <: S \n\n forall S T2 T2,\n S <: T1*T2 ->\n exists S1 S2,\n S = S1*S2 /\\ S1 <: T1 /\\ S2 <: T2 \n]]\n[] *)\n\n(** **** Exercise: 1 star (subtype_concepts_tf) *)\n(** Which of the following statements are true, and which are false?\n - There exists a type that is a supertype of every other type.\n\n - There exists a type that is a subtype of every other type.\n\n - There exists a pair type that is a supertype of every other\n pair type.\n\n - There exists a pair type that is a subtype of every other\n pair type.\n\n - There exists an arrow type that is a supertype of every other\n arrow type.\n\n - There exists an arrow type that is a subtype of every other\n arrow type.\n\n - There is an infinite descending chain of distinct types in the\n subtype relation---that is, an infinite sequence of types\n [S0], [S1], etc., such that all the [Si]'s are different and\n each [S(i+1)] is a subtype of [Si].\n\n - There is an infinite _ascending_ chain of distinct types in\n the subtype relation---that is, an infinite sequence of types\n [S0], [S1], etc., such that all the [Si]'s are different and\n each [S(i+1)] is a supertype of [Si].\n\n[]\n*)\n\n(** **** Exercise: 2 stars (proper_subtypes) *)\n(** Is the following statement true or false? Briefly explain your\n answer.\n[[\n forall T,\n ~(exists n, T = ty_base n) ->\n exists S,\n S <: T /\\ S <> T\n]] \n[]\n*)\n\n(** **** Exercise: 2 stars (small_large_1) *)\n(** \n - What is the _smallest_ type [T] (\"smallest\" in the subtype\n relation) that makes the following assertion true?\n[[\n empty |- (\\p:T*Top. p.fst) ((\\z:A.z), unit) : A->A\n]]\n\n - What is the _largest_ type [T] that makes the same assertion true?\n\n[]\n*)\n\n(** **** Exercise: 2 stars (small_large_2) *)\n(** \n - What is the _smallest_ type [T] that makes the following\n assertion true?\n[[\n empty |- (\\p:(A->A * B->B). p) ((\\z:A.z), (\\z:B.z)) : T\n]]\n\n - What is the _largest_ type [T] that makes the same assertion true?\n\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (small_large_3) *)\n(** \n - What is the _smallest_ type [T] that makes the following\n assertion true?\n[[\n a:A |- (\\p:(A*T). (p.snd) (p.fst)) (a , \\z:A.z) : A\n]]\n\n - What is the _largest_ type [T] that makes the same assertion true?\n\n[]\n*)\n\n(** **** Exercise: 2 stars (small_large_4) *)\n(** \n - What is the _smallest_ type [T] that makes the following\n assertion true?\n[[\n exists S,\n empty |- (\\p:(A*T). (p.snd) (p.fst)) : S\n]]\n\n - What is the _largest_ type [T] that makes the same\n assertion true?\n\n[]\n*)\n\n(** **** Exercise: 2 stars (smallest_1) *)\n(** What is the _smallest_ type [T] that makes the following\n assertion true?\n[[\n exists S, exists t, \n empty |- (\\x:T. x x) t : S\n]] \n[]\n*)\n\n(** **** Exercise: 2 stars (smallest_2) *)\n(** What is the _smallest_ type [T] that makes the following\n assertion true?\n[[\n empty |- (\\x:Top. x) ((\\z:A.z) , (\\z:B.z)) : T\n]] \n[]\n*)\n\n(** **** Exercise: 3 stars, optional (count_supertypes) *)\n(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,\n how many different types [T] are there such that [{x:A, y:C->C} <:\n T]? (We consider two types to be different if they are written\n differently, even if each is a subtype of the other. For example,\n [{x:A,y:B}] and [{y:B,x:A}] are different.)\n\n\n[]\n*)\n\n(* ###################################################################### *)\n(** * Typing *)\n\n(** The only change to the typing relation is the addition of the rule\n of subsumption, [T_Sub]. *)\n\nDefinition context := id -> (option ty).\nDefinition empty : context := (fun _ => None). \nDefinition extend (Gamma : context) (x:id) (T : ty) :=\n fun x' => if beq_id x x' then Some T else Gamma x'.\n\nInductive has_type : context -> tm -> ty -> Prop :=\n (* Same as before *)\n | T_Var : forall Gamma x T,\n Gamma x = Some T ->\n has_type Gamma (tm_var x) T\n | T_Abs : forall Gamma x T11 T12 t12,\n has_type (extend Gamma x T11) t12 T12 -> \n has_type Gamma (tm_abs x T11 t12) (ty_arrow T11 T12)\n | T_App : forall T1 T2 Gamma t1 t2,\n has_type Gamma t1 (ty_arrow T1 T2) -> \n has_type Gamma t2 T1 -> \n has_type Gamma (tm_app t1 t2) T2\n | T_True : forall Gamma,\n has_type Gamma tm_true ty_Bool\n | T_False : forall Gamma,\n has_type Gamma tm_false ty_Bool\n | T_If : forall t1 t2 t3 T Gamma,\n has_type Gamma t1 ty_Bool ->\n has_type Gamma t2 T ->\n has_type Gamma t3 T ->\n has_type Gamma (tm_if t1 t2 t3) T\n | T_Unit : forall Gamma,\n has_type Gamma tm_unit ty_Unit\n (* New rule of subsumption *)\n | T_Sub : forall Gamma t S T,\n has_type Gamma t S ->\n subtype S T ->\n has_type Gamma t T.\n\nHint Constructors has_type.\n\nTactic Notation \"has_type_cases\" tactic(first) ident(c) :=\n first;\n [ Case_aux c \"T_Var\" | Case_aux c \"T_Abs\" \n | Case_aux c \"T_App\" | Case_aux c \"T_True\" \n | Case_aux c \"T_False\" | Case_aux c \"T_If\"\n | Case_aux c \"T_Unit\" \n | Case_aux c \"T_Sub\" ].\n\n(* ############################################### *)\n(** ** Typing examples *)\n\nModule Examples2.\nImport Examples.\n\n(** Do the following exercises after you have added product types to\n the language. For each informal typing judgement, write it as a\n formal statement in Coq and prove it. *)\n\n(** **** Exercise: 1 star, optional (typing_example_0) *)\n(* empty |- ((\\z:A.z), (\\z:B.z)) : (A->A * B->B) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (typing_example_1) *)\n(* empty |- (\\x:(Top * B->B). x.snd) ((\\z:A.z), (\\z:B.z)) : B->B *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (typing_example_2) *)\n(* empty |- (\\z:(C->C)->(Top * B->B). (z (\\x:C.x)).snd)\n (\\z:C->C. ((\\z:A.z), (\\z:B.z)))\n : B->B *)\n(* FILL IN HERE *)\n(** [] *)\n\nEnd Examples2.\n\n(* ###################################################################### *)\n(** * Properties *)\n\n(** The fundamental properties of the system that we want to check are\n the same as always: progress and preservation. Unlike the\n extension of the STLC with references, we don't need to change the\n _statements_ of these properties to take subtyping into account.\n However, their proofs do become a little bit more involved. *)\n\n(* ###################################################################### *)\n(** ** Inversion Lemmas for Subtyping *)\n\n(** Before we look at the properties of the typing relation, we need\n to record a couple of critical structural properties of the subtype\n relation: \n - [Bool] is the only subtype of [Bool]\n - every subtype of an arrow type _is_ an arrow type. *)\n \n(** These are called _inversion lemmas_ because they play the same\n role in later proofs as the built-in [inversion] tactic: given a\n hypothesis that there exists a derivation of some subtyping\n statement [S <: T] and some constraints on the shape of [S] and/or\n [T], each one reasons about what this derivation must look like to\n tell us something further about the shapes of [S] and [T] and the\n existence of subtype relations between their parts. *)\n\n(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)\nLemma sub_inversion_Bool : forall U,\n subtype U ty_Bool ->\n U = ty_Bool.\nProof with auto.\n intros U Hs.\n remember ty_Bool as V.\n (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)\nLemma sub_inversion_arrow : forall U V1 V2,\n subtype U (ty_arrow V1 V2) ->\n exists U1, exists U2, \n U = (ty_arrow U1 U2) /\\ (subtype V1 U1) /\\ (subtype U2 V2).\nProof with eauto.\n intros U V1 V2 Hs.\n remember (ty_arrow V1 V2) as V.\n generalize dependent V2. generalize dependent V1.\n (* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(* ########################################## *)\n(** ** Canonical Forms *)\n\n(** We'll see first that the proof of the progress theorem doesn't\n change too much -- we just need one small refinement. When we're\n considering the case where the term in question is an application\n [t1 t2] where both [t1] and [t2] are values, we need to know that\n [t1] has the _form_ of a lambda-abstraction, so that we can apply\n the [ST_AppAbs] reduction rule. In the ordinary STLC, this is\n obvious: we know that [t1] has a function type [T11->T12], and\n there is only one rule that can be used to give a function type to\n a value -- rule [T_Abs] -- and the form of the conclusion of this\n rule forces [t1] to be an abstraction.\n\n In the STLC with subtyping, this reasoning doesn't quite work\n because there's another rule that can be used to show that a value\n has a function type: subsumption. Fortunately, this possibility\n doesn't change things much: if the last rule used to show [Gamma\n |- t1 : T11->T12] is subsumption, then there is some\n _sub_-derivation whose subject is also [t1], and we can reason by\n induction until we finally bottom out at a use of [T_Abs].\n\n This bit of reasoning is packaged up in the following lemma, which\n tells us the possible \"canonical forms\" (i.e. values) of function\n type. *)\n\n(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)\nLemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,\n has_type Gamma s (ty_arrow T1 T2) ->\n value s ->\n exists x, exists S1, exists s2,\n s = tm_abs x S1 s2.\nProof with eauto.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Similarly, the canonical forms of type [Bool] are the constants\n [true] and [false]. *)\n\nLemma canonical_forms_of_Bool : forall Gamma s,\n has_type Gamma s ty_Bool ->\n value s ->\n (s = tm_true \\/ s = tm_false).\nProof with eauto.\n intros Gamma s Hty Hv.\n remember ty_Bool as T.\n has_type_cases (induction Hty) Case; try solve by inversion...\n Case \"T_Sub\".\n subst. apply sub_inversion_Bool in H. subst...\nQed.\n\n\n(* ########################################## *)\n(** ** Progress *)\n\n(** The proof of progress proceeds like the one for the pure\n STLC, except that in several places we invoke canonical forms\n lemmas... *)\n\n(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-\n t : T] then [t] is a value or [t ==> t'] for some term [t'].\n \n _Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed\n by induction on the typing derivation. \n\n The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are\n immediate because abstractions, [unit], [true], and [false] are\n already values. The [T_Var] case is vacuous because variables\n cannot be typed in the empty context. The remaining cases are\n more interesting:\n\n - If the last step in the typing derivation uses rule [T_App],\n then there are terms [t1] [t2] and types [T1] and [T2] such that\n [t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-\n t2 : T1]. Moreover, by the induction hypothesis, either [t1] is\n a value or it steps, and either [t2] is a value or it steps.\n There are three possibilities to consider:\n\n - Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2] \n by [ST_App1].\n\n - Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].\n Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a\n value.\n\n - Finally, suppose [t1] and [t2] are both values. By Lemma\n [canonical_forms_for_arrow_types], we know that [t1] has the\n form [\\x:S1.s2] for some [x], [S1], and [s2]. But then\n [(\\x:S1.s2) t2 ==> [t2/x]s2] by [ST_AppAbs], since [t2] is a\n value.\n\n - If the final step of the derivation uses rule [T_If], then there\n are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else\n t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and\n [empty |- t3 : T]. Moreover, by the induction hypothesis,\n either [t1] is a value or it steps. \n \n - If [t1] is a value, then by the canonical forms lemma for\n booleans, either [t1 = true] or [t1 = false]. In either\n case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].\n\n - If [t1] can step, then so can [t], by rule [ST_If].\n\n - If the final step of the derivation is by [T_Sub], then there is\n a type [S] such that [S <: T] and [empty |- t : S]. The desired\n result is exactly the induction hypothesis for the typing\n subderivation.\n*)\n\nTheorem progress : forall t T, \n has_type empty t T ->\n value t \\/ exists t', t ==> t'. \nProof with eauto.\n intros t T Ht.\n remember empty as Gamma.\n revert HeqGamma.\n has_type_cases (induction Ht) Case; \n intros HeqGamma; subst...\n Case \"T_Var\".\n inversion H.\n Case \"T_App\".\n right.\n destruct IHHt1; subst...\n SCase \"t1 is a value\".\n destruct IHHt2; subst...\n SSCase \"t2 is a value\".\n destruct (canonical_forms_of_arrow_types empty t1 T1 T2)\n as [x [S1 [t12 Heqt1]]]...\n subst. exists (subst t2 x t12)...\n SSCase \"t2 steps\".\n destruct H0 as [t2' Hstp]. exists (tm_app t1 t2')...\n SCase \"t1 steps\".\n destruct H as [t1' Hstp]. exists (tm_app t1' t2)...\n Case \"T_If\".\n right.\n destruct IHHt1.\n SCase \"t1 is a value\"...\n assert (t1 = tm_true \\/ t1 = tm_false) \n by (eapply canonical_forms_of_Bool; eauto).\n inversion H0; subst...\n destruct H. rename x into t1'. eauto.\n\nQed.\n\n(* ########################################## *)\n(** ** Inversion Lemmas for Typing *)\n\n(** The proof of the preservation theorem also becomes a little more\n complex with the addition of subtyping. The reason is that, as\n with the \"inversion lemmas for subtyping\" above, there are a\n number of facts about the typing relation that are \"obvious from\n the definition\" in the pure STLC (and hence can be obtained\n directly from the [inversion] tactic) but that require real proofs\n in the presence of subtyping because there are multiple ways to\n derive the same [has_type] statement.\n\n The following \"inversion lemma\" tells us that, if we have a\n derivation of some typing statement [Gamma |- \\x:S1.t2 : T] whose\n subject is an abstraction, then there must be some subderivation\n giving a type to the body [t2]. *)\n\n(** _Lemma_: If [Gamma |- \\x:S1.t2 : T], then there is a type [S2]\n such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].\n\n (Notice that the lemma does _not_ say, \"then [T] itself is an arrow\n type\" -- this is tempting, but false!)\n\n _Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as\n described. Proceed by induction on the derivation of [Gamma |-\n \\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those\n rules cannot be used to give a type to a syntactic abstraction.\n\n - If the last step of the derivation is a use of [T_Abs] then\n there is a type [T12] such that [T = S1 -> T12] and [Gamma,\n x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we\n need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].\n\n - If the last step of the derivation is a use of [T_Sub] then\n there is a type [S] such that [S <: T] and [Gamma |- \\x:S1.t2 :\n S]. The IH for the typing subderivation tell us that there is\n some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :\n S2]. Picking type [S2] gives us what we need, since [S1 -> S2\n <: T] then follows by [S_Trans]. *)\n\nLemma typing_inversion_abs : forall Gamma x S1 t2 T,\n has_type Gamma (tm_abs x S1 t2) T ->\n (exists S2, subtype (ty_arrow S1 S2) T\n /\\ has_type (extend Gamma x S1) t2 S2).\nProof with eauto.\n intros Gamma x S1 t2 T H.\n remember (tm_abs x S1 t2) as t.\n has_type_cases (induction H) Case; \n inversion Heqt; subst; intros; try solve by inversion.\n Case \"T_Abs\".\n exists T12...\n Case \"T_Sub\".\n destruct IHhas_type as [S2 [Hsub Hty]]...\n Qed.\n\n(** Similarly... *)\n\nLemma typing_inversion_var : forall Gamma x T,\n has_type Gamma (tm_var x) T ->\n exists S,\n Gamma x = Some S /\\ subtype S T.\nProof with eauto.\n intros Gamma x T Hty.\n remember (tm_var x) as t.\n has_type_cases (induction Hty) Case; intros; \n inversion Heqt; subst; try solve by inversion.\n Case \"T_Var\".\n exists T...\n Case \"T_Sub\".\n destruct IHHty as [U [Hctx HsubU]]... Qed.\n\nLemma typing_inversion_app : forall Gamma t1 t2 T2,\n has_type Gamma (tm_app t1 t2) T2 ->\n exists T1,\n has_type Gamma t1 (ty_arrow T1 T2) /\\\n has_type Gamma t2 T1.\nProof with eauto.\n intros Gamma t1 t2 T2 Hty.\n remember (tm_app t1 t2) as t.\n has_type_cases (induction Hty) Case; intros;\n inversion Heqt; subst; try solve by inversion.\n Case \"T_App\".\n exists T1...\n Case \"T_Sub\".\n destruct IHHty as [U1 [Hty1 Hty2]]...\nQed.\n\nLemma typing_inversion_true : forall Gamma T,\n has_type Gamma tm_true T ->\n subtype ty_Bool T.\nProof with eauto.\n intros Gamma T Htyp. remember tm_true as tu.\n has_type_cases (induction Htyp) Case;\n inversion Heqtu; subst; intros...\nQed.\n\nLemma typing_inversion_false : forall Gamma T,\n has_type Gamma tm_false T ->\n subtype ty_Bool T.\nProof with eauto.\n intros Gamma T Htyp. remember tm_false as tu.\n has_type_cases (induction Htyp) Case;\n inversion Heqtu; subst; intros...\nQed.\n\nLemma typing_inversion_if : forall Gamma t1 t2 t3 T,\n has_type Gamma (tm_if t1 t2 t3) T ->\n has_type Gamma t1 ty_Bool \n /\\ has_type Gamma t2 T\n /\\ has_type Gamma t3 T.\nProof with eauto.\n intros Gamma t1 t2 t3 T Hty.\n remember (tm_if t1 t2 t3) as t.\n has_type_cases (induction Hty) Case; intros;\n inversion Heqt; subst; try solve by inversion.\n Case \"T_If\".\n auto.\n Case \"T_Sub\".\n destruct (IHHty H0) as [H1 [H2 H3]]...\nQed.\n\nLemma typing_inversion_unit : forall Gamma T,\n has_type Gamma tm_unit T ->\n subtype ty_Unit T.\nProof with eauto.\n intros Gamma T Htyp. remember tm_unit as tu.\n has_type_cases (induction Htyp) Case;\n inversion Heqtu; subst; intros...\nQed.\n\n\n(** The inversion lemmas for typing and for subtyping between arrow\n types can be packaged up as a useful \"combination lemma\" telling\n us exactly what we'll actually require below. *)\n\nLemma abs_arrow : forall x S1 s2 T1 T2, \n has_type empty (tm_abs x S1 s2) (ty_arrow T1 T2) ->\n subtype T1 S1 \n /\\ has_type (extend empty x S1) s2 T2.\nProof with eauto.\n intros x S1 s2 T1 T2 Hty.\n apply typing_inversion_abs in Hty.\n destruct Hty as [S2 [Hsub Hty]].\n apply sub_inversion_arrow in Hsub.\n destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].\n inversion Heq; subst... Qed.\n\n(* ########################################## *)\n(** ** Context Invariance *)\n\n(** The context invariance lemma follows the same pattern as in the\n pure STLC. *)\n\nInductive appears_free_in : id -> tm -> Prop :=\n | afi_var : forall x,\n appears_free_in x (tm_var x)\n | afi_app1 : forall x t1 t2,\n appears_free_in x t1 -> appears_free_in x (tm_app t1 t2)\n | afi_app2 : forall x t1 t2,\n appears_free_in x t2 -> appears_free_in x (tm_app t1 t2)\n | afi_abs : forall x y T11 t12,\n y <> x ->\n appears_free_in x t12 ->\n appears_free_in x (tm_abs y T11 t12)\n | afi_if1 : forall x t1 t2 t3,\n appears_free_in x t1 ->\n appears_free_in x (tm_if t1 t2 t3)\n | afi_if2 : forall x t1 t2 t3,\n appears_free_in x t2 ->\n appears_free_in x (tm_if t1 t2 t3)\n | afi_if3 : forall x t1 t2 t3,\n appears_free_in x t3 ->\n appears_free_in x (tm_if t1 t2 t3)\n.\n\nHint Constructors appears_free_in.\n\nLemma context_invariance : forall Gamma Gamma' t S,\n has_type Gamma t S ->\n (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n has_type Gamma' t S.\nProof with eauto.\n intros. generalize dependent Gamma'.\n has_type_cases (induction H) Case; \n intros Gamma' Heqv...\n Case \"T_Var\".\n apply T_Var... rewrite <- Heqv...\n Case \"T_Abs\".\n apply T_Abs... apply IHhas_type. intros x0 Hafi.\n unfold extend. remember (beq_id x x0) as e.\n destruct e...\n Case \"T_App\".\n apply T_App with T1...\n Case \"T_If\".\n apply T_If...\n\nQed.\n\nLemma free_in_context : forall x t T Gamma,\n appears_free_in x t ->\n has_type Gamma t T ->\n exists T', Gamma x = Some T'.\nProof with eauto.\n intros x t T Gamma Hafi Htyp.\n has_type_cases (induction Htyp) Case; \n subst; inversion Hafi; subst...\n Case \"T_Abs\".\n destruct (IHHtyp H4) as [T Hctx]. exists T.\n unfold extend in Hctx. apply not_eq_beq_id_false in H2. \n rewrite H2 in Hctx... Qed.\n\n(* ########################################## *)\n(** ** Substitution *)\n\n(** The _substitution lemma_ is proved along the same lines as for the\n pure STLC. The only significant change is that there are several\n places where, instead of the built-in [inversion] tactic, we use\n the inversion lemmas that we proved above to extract structural\n information from assumptions about the well-typedness of\n subterms. *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (extend Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma (subst v x t) S.\nProof with eauto.\n intros Gamma x U v t S Htypt Htypv.\n generalize dependent S. generalize dependent Gamma.\n tm_cases (induction t) Case; intros; simpl.\n Case \"tm_var\".\n rename i into y.\n destruct (typing_inversion_var _ _ _ Htypt) \n as [T [Hctx Hsub]].\n unfold extend in Hctx.\n remember (beq_id x y) as e. destruct e...\n SCase \"x=y\".\n apply beq_id_eq in Heqe. subst.\n inversion Hctx; subst. clear Hctx.\n apply context_invariance with empty...\n intros x Hcontra.\n destruct (free_in_context _ _ S empty Hcontra) \n as [T' HT']...\n inversion HT'.\n Case \"tm_app\".\n destruct (typing_inversion_app _ _ _ _ Htypt) \n as [T1 [Htypt1 Htypt2]].\n eapply T_App...\n Case \"tm_abs\".\n rename i into y. rename t into T1.\n destruct (typing_inversion_abs _ _ _ _ _ Htypt) \n as [T2 [Hsub Htypt2]].\n apply T_Sub with (ty_arrow T1 T2)... apply T_Abs...\n remember (beq_id x y) as e. destruct e.\n SCase \"x=y\".\n eapply context_invariance...\n apply beq_id_eq in Heqe. subst.\n intros x Hafi. unfold extend.\n destruct (beq_id y x)...\n SCase \"x<>y\".\n apply IHt. eapply context_invariance...\n intros z Hafi. unfold extend.\n remember (beq_id y z) as e0. destruct e0...\n apply beq_id_eq in Heqe0. subst.\n rewrite <- Heqe...\n Case \"tm_true\".\n assert (subtype ty_Bool S) \n by apply (typing_inversion_true _ _ Htypt)...\n Case \"tm_false\".\n assert (subtype ty_Bool S) \n by apply (typing_inversion_false _ _ Htypt)...\n Case \"tm_if\".\n assert (has_type (extend Gamma x U) t1 ty_Bool \n /\\ has_type (extend Gamma x U) t2 S\n /\\ has_type (extend Gamma x U) t3 S) \n by apply (typing_inversion_if _ _ _ _ _ Htypt).\n destruct H as [H1 [H2 H3]].\n apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.\n auto.\n Case \"tm_unit\".\n assert (subtype ty_Unit S) \n by apply (typing_inversion_unit _ _ Htypt)...\nQed.\n\n(* ########################################## *)\n(** ** Preservation *)\n\n(** The proof of preservation now proceeds pretty much as in earlier\n chapters, using the substitution lemma at the appropriate point\n and again using inversion lemmas from above to extract structural\n information from typing assumptions. *)\n\n(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type\n such that [empty |- t : T] and [t ==> t'], then [empty |- t' :\n T].\n\n _Proof_: Let [t] and [T] be given such that [empty |- t : T]. We\n go by induction on the structure of this typing derivation,\n leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and\n [T_False] cases are vacuous because abstractions and constants\n don't step. Case [T_Var] is vacuous as well, since the context is\n empty.\n\n - If the final step of the derivation is by [T_App], then there\n are terms [t1] [t2] and types [T1] [T2] such that [t = t1 t2],\n [T = T2], [empty |- t1 : T1 -> T2] and [empty |- t2 : T1].\n\n By inspection of the definition of the step relation, there are\n three ways [t1 t2] can step. Cases [ST_App1] and [ST_App2]\n follow immediately by the induction hypotheses for the typing\n subderivations and a use of [T_App].\n\n Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =\n \\x:S.t12] for some type [S] and term [t12], and [t' =\n [t2/x]t12].\n \n By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].\n It then follows by the substitution lemma \n ([substitution_preserves_typing]) that [empty |- [t2/x]\n t12 : T2] as desired.\n\n - If the final step of the derivation uses rule [T_If], then\n there are terms [t1], [t2], and [t3] such that [t = if t1 then\n t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :\n T] and [empty |- t3 : T]. Moreover, by the induction\n hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].\n There are three cases to consider, depending on which rule was\n used to show [t ==> t'].\n\n - If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2\n else t3] with [t1 ==> t1']. By the induction hypothesis,\n [empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].\n \n - If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then\n either [t' = t2] or [t' = t3], and [empty |- t' : T]\n follows by assumption.\n\n - If the final step of the derivation is by [T_Sub], then there\n is a type [S] such that [S <: T] and [empty |- t : S]. The\n result is immediate by the induction hypothesis for the typing\n subderivation and an application of [T_Sub]. [] *)\n\nTheorem preservation : forall t t' T,\n has_type empty t T ->\n t ==> t' ->\n has_type empty t' T.\nProof with eauto.\n intros t t' T HT.\n remember empty as Gamma. generalize dependent HeqGamma.\n generalize dependent t'.\n has_type_cases (induction HT) Case; \n intros t' HeqGamma HE; subst; inversion HE; subst...\n Case \"T_App\".\n inversion HE; subst...\n SCase \"ST_AppAbs\".\n destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].\n apply substitution_preserves_typing with T...\nQed.\n\n(* ###################################################### *)\n(** ** Exercises on Typing *)\n\n(** **** Exercise: 2 stars (variations) *)\n(** Each part of this problem suggests a different way of\n changing the definition of the STLC with Unit and\n subtyping. (These changes are not cumulative: each part\n starts from the original language.) In each part, list which\n properties (Progress, Preservation, both, or neither) become\n false. If a property becomes false, give a counterexample.\n - Suppose we add the following typing rule:\n[[[\n Gamma |- t : S1->S2\n S1 <: T1 T1 <: S1 S2 <: T2\n ----------------------------------- (T_Funny1)\n Gamma |- t : T1->T2\n]]]\n\n - Suppose we add the following reduction rule:\n[[[\n ------------------ (ST_Funny21)\n unit ==> (\\x:Top. x)\n]]]\n\n - Suppose we add the following subtyping rule:\n[[[\n -------------- (S_Funny3)\n Unit <: Top->Top\n]]]\n\n - Suppose we add the following subtyping rule:\n[[[\n -------------- (S_Funny4)\n Top->Top <: Unit\n]]]\n\n - Suppose we add the following evaluation rule:\n[[[\n ----------------- (ST_Funny5)\n (unit t) ==> (t unit)\n]]]\n\n - Suppose we add the same evaluation rule _and_ a new typing rule:\n[[[\n ----------------- (ST_Funny5)\n (unit t) ==> (t unit)\n\n ---------------------- (T_Funny6)\n empty |- Unit : Top->Top\n]]]\n\n - Suppose we _change_ the arrow subtyping rule to:\n[[[\n S1 <: T1 S2 <: T2\n ----------------------- (S_Arrow')\n S1->S2 <: T1->T2\n]]]\n\n[]\n*) \n\n(* ###################################################################### *)\n(** * Exercise: Adding Products *)\n\n(** **** Exercise: 4 stars, optional (products) *)\n(** Adding pairs, projections, and product types to the system we have\n defined is a relatively straightforward matter. Carry out this\n extension:\n\n - Add constructors for pairs, first and second projections, and\n product types to the definitions of [ty] and [tm]. (Don't\n forget to add corresponding cases to [ty_cases] and [tm_cases].)\n\n - Extend the well-formedness relation in the obvious way.\n\n - Extend the operational semantics with the same reduction rules\n as in the last chapter.\n\n - Extend the subtyping relation with this rule:\n[[[\n S1 <: T1 S2 <: T2\n --------------------- (Sub_Prod)\n S1 * S2 <: T1 * T2\n]]]\n - Extend the typing relation with the same rules for pairs and\n projections as in the last chapter.\n\n - Extend the proofs of progress, preservation, and all their\n supporting lemmas to deal with the new constructs. (You'll also\n need to add some completely new lemmas.) []\n*)\n\n", "meta": {"author": "Blaisorblade", "repo": "Software-Foundations", "sha": "aeb1b49fd922a346b774b330694fe6c16caf9626", "save_path": "github-repos/coq/Blaisorblade-Software-Foundations", "path": "github-repos/coq/Blaisorblade-Software-Foundations/Software-Foundations-aeb1b49fd922a346b774b330694fe6c16caf9626/Subtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11436852920044105, "lm_q1q2_score": 0.05406011399842997}} {"text": "(** * Library file that should be used for the term projects of introduction\nto functional programming 2015. This file is based on SfLib.v of Software\nFoundations by Benjamin Pierce and others. *)\n\n(** * From the Coq Standard Library *)\n\nRequire Export Bool.\nRequire Export List.\nExport ListNotations.\nRequire Export Arith.\nRequire Export NPeano.\nRequire Export Arith.EqNat. (* Contains [beq_nat], among other things *)\n\n(** * From Basics.v *)\n\nDefinition admit {T: Type} : T. Admitted.\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\n(** * From Logic.v *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n False -> P.\nProof.\n intros P contra.\n inversion contra. Qed.\n\n(** Identifiers *)\n\n(** We define a new inductive datatype [Id] so that we won't confuse\n identifiers and numbers. *)\n\nInductive id : Type :=\n Id : nat -> id.\n\nDefinition beq_id (x x' : id) : bool :=\n match x, x' with\n | Id y, Id y' => beq_nat y y'\n end.\nLemma beq_id_refl : forall x : id,\n true = beq_id x x.\nProof.\n intros x; destruct x as [y]; simpl; apply beq_nat_refl.\nQed.\nLemma beq_id_eq: forall x x' : id,\n true = beq_id x x' -> x = x'.\nProof.\n intros x x' H; destruct x as [y]; destruct x' as [y']; simpl in H.\n apply beq_nat_eq in H. rewrite H. reflexivity.\nQed.", "meta": {"author": "Kasserne", "repo": "FSVproject", "sha": "326ec93628556919f021a2acd4d25d802c64b2e1", "save_path": "github-repos/coq/Kasserne-FSVproject", "path": "github-repos/coq/Kasserne-FSVproject/FSVproject-326ec93628556919f021a2acd4d25d802c64b2e1/project_lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326716, "lm_q2_score": 0.11920292515117026, "lm_q1q2_score": 0.053568918327655195}} {"text": "(** remove printing ~ *)\n(** printing ~ %\\textasciitilde% *)\n(** printing R $R$ *)\n(** printing done %\\texttt{\\emph{done}}% *)\n(** printing congr %\\texttt{\\emph{congr}}% *)\n(** printing of %\\texttt{\\emph{of}}% *)\n(** printing suff %\\texttt{\\emph{suff}}% *)\n(** printing have %\\texttt{\\emph{have}}% *)\n(** printing View %\\texttt{\\emph{View}}% *)\n(** printing From %\\textsf{{From}}% *)\n\n(** \n\n%\\chapter{Views and Boolean Reflection}\n\\label{ch:boolrefl}%\n\n*)\n\n(** \n\nIn %Chapter~\\ref{ch:eqrew}%, we have seen how custom rewriting rules\nand truth tables can be encoded in Coq using its support for indexed\ndatatype families, so they are of great help for constructing the\nproofs by case analysis and rewriting. In this chapter, we will show\nhow the custom rewriting machinery can be taken to the whole new level\nand be used to facilitate the reasoning about _computable_ properties\nand predicates. We will consider a series of insights that lead to the\nidea of the _small-scale reflection_, the heart of the Ssreflect\n%\\index{small-scale reflection|textbf}% %\\index{reflection|see\n{small-scale reflection}}% framework, which blurs the boundaries\nbetween computable predicates defined in the sort [Prop] (see\n%Chapter~\\ref{ch:logic}%) and Coq's recursive functions returning a\nresult of type [bool] (in the spirit of the definitions that we have\nseen in %Chapter~\\ref{ch:funprog}%). That said, in the vast number of\ncases these two are just the sides of the same coin and, hence, should\nbe treated uniformly, serving to facilitate the reasoning in two\ndifferent directions: %\\index{reflection|see {small-scale\nreflection}}%\n\n- expressing quantifications and building the proofs by means of\n _constructive reasoning_ with logical connectives as datatypes\n defined in the sort [Prop];\n\n- employing brute-force computations for quantifier-free goals within\n the Coq framework itself, taken as a programming language, in order\n to reduce the goals to be proved by means of simply _computing_\n them.\n\nWe will elaborate more on the differences between predicates stated by\nmeans of [Prop] and [bool] in %Section~\\ref{sec:propbool}%. The term\n_small-scale reflection_, which gives the name to the whole framework\nof Ssreflect, emphasizes the two complementary ways of building\nproofs: by means of intuitionistic inference (i.e., using the\nconstructors of datatypes defined in [Prop]) and by means of mere\ncomputation (i.e., with [bool]-returning function). These two ways,\ntherefore, serve as each other's \"reflections\" and, moreover, both are\nimplemented within the same system, without the need to appeal to\nCoq's meta-object protocol,%\\footnote{In contrast, reflection\nmechanism in Java, Python or Ruby actually does appeal to the\nmeta-object protocol, e.g., \\index{meta-object protocol} the structure\nof the classes, which lies beyond the formally defined semantics of\nthe language itself and, hence, allows one to modify the program's\nbehaviour at runtime.}% which makes this reflection _small-scale_.\n\nUnfortunately, the proper explanation of the implementation of the\nreflection mechanism between [Prop] and [bool] in Ssreflect strongly\nrelies on the _views_ machinery, so let us begin by describing it\nfirst.\n\n%\\newpage%\n\n* Proving with views in Ssreflect\n%\\label{sec:views}\\index{views|textbf}%\n\n*)\n\nFrom mathcomp\nRequire Import ssreflect ssrnat prime ssrbool eqtype.\n\n(* begin hide *)\nModule BoolReflect.\n(* end hide *)\n\n(** \n\nLet us assume we have the following implication to prove:\n\n*)\n\nLemma imp_trans4 P Q R S: (P -> Q) -> (R -> S) -> (Q -> R) -> P -> S.\nProof.\nmove=>H1 H2 H3.\n\n(** \n[[\n P : Type\n Q : Type\n R : Type\n S : Type\n H1 : P -> Q\n H2 : R -> S\n H3 : Q -> R\n ============================\n P -> S\n]]\n\nSince we are proficient in the proofs via implications, it is not\ndifficult to construct the explicit proof term by a series of [apply:]\ntactic calls or via the [exact:] tactic, as it has been show in\n%Chapter~\\ref{ch:logic}%. Let us do something different, though,\nnamely _weaken_ the top assumption of the goal by means of applying\nthe hypothesis [H1] to it, so the overall goal will become [Q -> S].\n\n*)\n\nmove=>p; move: (H1 p).\n\n(** \n\nThis proof pattern of \"switching the view\" turns out to be so frequent\nthat Ssreflect introduces a special _view_ tactical %\\texttt{/}% for\nit, which is typically combined with the standard [move] or [case]\ntactics. In particular, the last proof line could be replaced by the\nfollowing:\n\n*)\n\nUndo.\nmove/H1.\n\n(** \n\n[[\n ...\n H1 : P -> Q\n H2 : R -> S\n H3 : Q -> R\n ============================\n Q -> S\n]]\n\nThe assumption [H1] used for weakening is usually referred to as a\n%\\index{view lemma}% _view lemma_. The spaces before and after\n%\\texttt{/}% are optional. One can also _chain_ the views into one\nseries, so the current proof can be completed as follows:\n\n*)\n\nby move/H3 /H2.\nQed.\n\n(** \n\n** Combining views and bookkeeping\n\nThe view tactical can be also combined with the standard bookkeeping\nmachinery, so it will apply the specified view lemma to the\ncorresponding assumption of the goal, as demonstrated by the following\nproof script, which use the partially-applied assumption [H p] as a\nview lemma:\n\n*)\n\nGoal forall P Q R, P -> (P -> Q -> R) -> Q -> R.\nProof.\nby move=>P Q R p H /(H p).\n\n(**\n\nIn fact, this proof can be shortened even further by using the view\nnotation for the _top_ assumption (denoted using the underscore):\n\n*)\n\nUndo.\nmove=> P Q R p. \nby move/(_ p). \nQed.\n\n(** \n\nThe last proof script first moved four assumptions to the context, so\nthe goal became [(P -> Q -> R) -> Q -> R]. Next, it partially applied\nthe top assumption [(P -> Q -> R)] to [p : P] from the context and\nmoved the result back to the goal, so it became [(Q -> R) -> Q -> R],\nwhich is trivially provable.\n\nIt is also possible to use views in combination with the [case]\ntactics, which first performs the \"view switch\" via the view lemma\nprovided and then case-analysed on the result, as demonstrated by the\nfollowing proof script:\n\n*)\n\nGoal forall P Q R, (P -> Q /\\ R) -> P -> R.\nProof.\nmove=> P Q R H.\nby case/H. \nQed.\n\n(** \n\nWhat has happened is that the combined tactic [case/H] first switched\nthe top assumption of the goal from [P] to [Q /\\ R] and then\ncase-analysed on it, which gave the proof of [R] right away, allowing\nus to conclude the proof.\n\n** Using views with equivalences\n%\\label{seq:viewseq}%\n\nSo far we have explored only views that help to weaken the hypothesis\nusing the view lemma, which is an implication. In fact, Ssreflect's\nview mechanism is elaborate enough to deal with view lemmas defined\nby means of equivalence (double implication) %\\texttt{<->}%, and the\nsystem can figure out itself, \"in which direction\" the view lemma\nshould be applied. Let us demonstrate it with the following example,\nwhich makes use of the hypothesis [STequiv],%\\footnote{The Coq's\ncommand \\texttt{Hypothesis} is a synonym for \\texttt{Axiom} and\n\\texttt{Variable}.\\ccom{Hypothesis}\\ccom{Variable}\\ccom{Axiom}}% whose\nnature is irrelevant for the illustration purposes:\n\n*)\n\nVariables S T: bool -> Prop.\nHypothesis STequiv : forall a b, T a <-> S (a || b). \n\nLemma ST_False a b: (T a -> False) -> S (a || b) -> False.\nProof.\nby move=>H /STequiv.\nQed.\n\n(**\n\n** Declaring view hints\n\nIn the example from %Section~\\ref{seq:viewseq}%, we have seen how\nviews can deal with equivalences. The mentioned elaboration, which\nhelped the system to recognize, in which direction the double\nimplication hypothesis [STequiv] should have been used, is not\nhard-coded into Ssreflect. Instead, it is provided by a flexible\nmechanism of %\\index{view hints}% _view hints_, which allows one to\nspecify view lemmas that should be applied _implicitly_ whenever it is\nnecessary and can be figured out unambiguously.\n\nIn the case of the proof of the [ST_False] lemma the view hint [iffRL]\nfrom the included module [ssreflect]%\\footnote{Implicit view hints are\ndefined by means of \\texttt{Hint View}\\ccom{Hint View} command, added\nto Coq by Ssreflect. See the implementation of the module\n%[ssrbool]%\\ssrm{ssrbool} and Section 9.8 of the Reference\nManual~\\cite{Gontier-al:TR}.}% %\\ssrm{ssreflect}% has been \"fired\" in\norder to adapt the hypothesis [STequiv], so the adapted variant could\nbe applied as a view lemma to the argument of type [S (a || b)].\n\n*)\n\nCheck iffRL.\n\n(** \n[[\niffRL\n : forall P Q : Prop, (P <-> Q) -> Q -> P\n]]\n\nThe type of [iffRL] reveals that what it does is simply switching the\nequivalence to the implication, which works right-to-left, as captured\nby the name. Let us now redo the proof of the [ST_False] lemma to see\nwhat is happening under the hood:\n\n*)\n\nLemma ST_False' a b: (T a -> False) -> S (a || b) -> False.\nProof.\nmove=> H.\nmove/(iffRL (STequiv a b)).\ndone.\nQed.\n\n(**\n\nThe view switch on the second line of the proof is what has been done\nimplicitly in the previous case: the implicit view [iffRL] has been\napplied to the call of [STequiv], which was in its turn supplied the\nnecessary arguments [a] and [b], inferred by the system from the goal,\nso the type of [(STequiv a b)] would match the parameter type of\n[iffRL], and the whole application would allow to make a view switch\nin the goal. What is left behind the scenes is the rest of the\nattempts made by Coq/Ssreflect in its search for a suitable implicit\nview, which ended when the system has finally picked [iffRL].\n\nIn general, the design of powerful view hints is non-trivial, as they\nshould capture precisely the situation when the \"view switch\" is\nabsolutely necessary and the implicit views will not \"fire\"\nspuriously. In the same time, implicit view hints is what allows for\nthe smooth implementation of the boolean reflection, as we will\ndiscuss in %Section~\\ref{sec:reflect}%.\n\n\n** Applying view lemmas to the goal\n\nSimilarly to how they are used for _assumptions_, views can be used to\ninterpret the goal by means of combining the Coq's standard [apply]\nand [exact] tactics with the view tactical%~\\texttt{/}%. In the case\nif [H] is a view lemma, which is just an implication [P -> Q], where\n[Q] is the statement of the goal, the enhanced tactic [apply/ H] will\nwork exactly as the standard Ssreflect's [apply:], that is, it will\nreplace the goal [Q] with [H]'s assumption [P] to prove.\n\nHowever, interpreting goals via views turns out to be very beneficial\nin the presence of implicit view hints. For example, let us consider\nthe following proposition to prove.\n\n*)\n\nDefinition TS_neg: forall a, T (negb a) -> S ((negb a) || a).\nProof.\nmove=>a H. \napply/STequiv.\ndone.\nQed.\n\n(**\n\nThe view switch on the goal via [apply/STequiv] immediately changed\nthe goal from [S ((negb a) || a)] to [T (negb a)], so the rest of the\nproof becomes trivial. Again, notice that the system managed to infer\nthe right arguments for the [STequiv] hypothesis by analysing the\ngoal.\n\nNow, if we print the body of [TS_neg], we will be able to see how an\napplication of the implicit application of the view lemma [iffLR] of\ntype [forall P Q : Prop, (P <-> Q) -> P -> Q] has been inserted,\nallowing for the construction of the proof term:\n\n*)\n\nPrint TS_neg.\n\n(**\n\n[[\nTS_neg = \n fun (a : bool) (H : T (negb a)) =>\n (fun F : T (negb a) =>\n iffLR (Q:=S (negb a || a)) (STequiv (negb a) a) F) H\n : forall a : bool, T (negb a) -> S (negb a || a)\n]]\n\n*)\n\n\n(** * %\\texttt{Prop} versus \\textbf{\\textsf{bool}}%\n%\\label{sec:propbool}%\n\nAs we have already explored in the previous chapters, in CIC, the\nlogical foundation of Coq, there is a number of important distinctions\nbetween logical propositions and boolean values. In particular, there\nis an infinite number of ways to represent different propositions in\nthe sort [Prop] by means of defining the datatypes. In contrast, the\ntype [bool] is represented just by two values: [true] and\n[false]. Moreover, as it was discussed in %Chapter~\\ref{ch:logic}%, in\nCoq only those propositions are considered to be _true_, whose proof\nterm can be constructed. And, of course, there is no such thing as a\n\"proof term of [true]\", as [true] is simply a value.\n\nA more interesting question, though, is for which propositions [P]\nfrom the sort [Prop] the proofs can be computed _automatically_ by\nmeans of running a program, whose result will be an answer to the\nquestion \"Whether [P] holds?\". Therefore, such programs should always\n_terminate_ and, upon terminating, say \"true\" or \"false\". The\npropositions, for which a construction of such programs (even a very\ninefficient one) is possible, are referred to %\\index{decidability}%\nas _decidable_ ones. Alas, as it was discussed in\n%Section~\\ref{sec:propsort} of Chapter~\\ref{ch:logic}%, quite a lot of\ninteresting propositions are undecidable. Such properties include the\nclassical halting problem %\\index{halting problem}% (\"Whether the\nprogram [p] terminates or not?\") and any higher-order formulae, i.e.,\nsuch that contain quantifiers. For instance, it is not possible to\nimplement a higher-order function, which would take two arbitrary\nfunctions $f_1$ and $f_2$ of type [nat -> nat] and return a boolean\nanswer, which would indicate whether these two functions are equal\n(point-wise) or not, as it would amount to checking the result of the\nboth function on each natural number, which, clearly, wouldn't\nterminate. Therefore, propositional equality of functions is a good\nexample of a proposition, which is undecidable in general, so we\ncannot provide a terminating procedure for any values of its arguments\n(i.e., $f_1$ and $f_2$).\n\nHowever, the _undecidability_ of higher-order propositions (like the\npropositional equality of functions) does not make them _non-provable_\nfor particular cases, as we have clearly observed thorough the past\nfew chapters. It usually takes a human intuition, though, to construct\na proof of an undecidable proposition by means of combining a number\nof hypotheses (i.e., constructing a proof term), which is what one\ndoes when building a proof using tactics in Coq. For instance, if we\nhave some extra insight about the two functions $f_1$ and $f_2$, which\nare checked for equality, we might be able to construct the proof of\nthem being equal or not, in the similar ways as we have carried the\nproofs so far. Again, even if the functions are unknown upfront, it\ndoes not seem possible to implement an always-terminating procedure\nthat would automatically decide whether they are equal or not.\n\nThe above said does not mean that all possible propositions should be implemented as instances of [Prop], making their clients to always construct their proofs, when it is necessary, since, fortunately, some propositions are _decidable_, so it is possible to construct a decision procedure for them. A good example of such proposition is a predicate, which ensures that a number [n] is prime. Of course, in Coq one can easily encode primality of a natural number by means of the following inductive predicate, which ensures that [n] is prime if it is [1] or has no other natural divisors but [1] and [n] itself.\n\n%\\ssrd{isPrime}%\n\n*)\n\nDefinition isPrime n : Prop :=\n forall n1 n2, n = n1 * n2 -> (n1 = 1 /\\ n2 = n) \\/ (n1 = n /\\ n2 = 1).\n\n(** \n\nSuch definition, although correct, is quite inconvenient to use, as it\ndoes not provide a direct way to _check_ whether some particular\nnumber (e.g., 239) is prime or not. Instead, it requires one to\nconstruct a proof of primality for _each_ particular case using the\nconstructors (or the contradiction, which would imply that the number\nis not prime). As it's well known, there is a terminating procedure to\ncompute whether the number is prime or not by means of _enumerating_\nall potential divisors of [n] from [1] to the square root of [n]. Such\nprocedure is actually implemented in the Ssreflect's [prime]\n%\\ssrm{prime}% module and proved correct with respect to the\ndefinition similar to the one above,%\\footnote{Although the\nimplementation and the proof are somewhat non-trivial, as they require\nto build a primitively-recursive function, which performs the\nenumeration, so we do not consider them here.}% so now one can test\nthe numbers by equality by simply _executing_ the appropriate function\nand getting a boolean answer:\n\n*)\n\nEval compute in prime 239.\n(** \n[[\n = true\n : bool\n]]\n\nTherefore, we can summarize that the _decidability_ is what draws the\nline between propositions encoded by means of Coq's [Prop] datatypes\nand procedures, returning a [bool] result. [Prop] provides a way to\nencode a _larger_ class of logical statements, in particular, thanks\nto the fact that it allows one to use quantifiers and, therefore,\nencode higher-order propositions. The price to pay for the\nexpressivity is the necessity to explicitly construct the proofs of\nthe encoded statements, which might lead to series of tedious and\nrepetitive scripts. [bool]-returning functions, when implemented in\nCoq, are decidable by construction (as Coq enforces termination), and,\ntherefore, provide a way to compute the propositions they\nimplement. Of course, in order to be reduced to [true] or [false], all\nquantifiers should be removed by means of instantiated the\ncorresponding bound variables, after which the computation becomes\npossible.\n\nFor instance, while the expression [(prime 239) || (prime 42)] can be\nevaluated to [true] right away, whereas the expression\n\n[[\nforall n, (prime n) || prime (n + 1)\n]]\n\nis not even well-typed. The reason for this is that polymorphic\n[forall]-quantification in Coq does not admit _values_ to come after\nthe comma (so the dependent function type \"$\\Pi{}n:~\\textsf{nat}, n$\"\nis malformed), similarly to how one cannot write a _type_ [Int -> 3]\nin Haskell%\\index{Haskell}%, as it does not make sense. This\nexpression can be, however, _coerced_ into [Prop] by means of\ncomparing the boolean expression with [true] using propositional\nequality\n\n[[\nforall n, ((prime n) || prime (n + 1) = true)\n]]\n\nwhich makes the whole expression to be of type [Prop]. This last\nexample brings us to the insight that the [bool]-returning functions\n(i.e., decidable predicates) can be naturally _injected_\n%\\index{injection}% into propositions of sort [Prop] by simply\ncomparing their result with [true] via propositional equality, defined\nin Chapter%~\\ref{ch:eqrew}%. This is what is done by Ssreflect\nautomatically using the implicit%\\index{coercion}\\ccom{Coercion}%\n_coercion_, imported by the [ssrbool] module:%\\ssrm{ssrbool}%\n\n[[\nCoercion is_true (b: bool) := b = true\n]]\n\nThis coercion can be seen as an implicit type conversion, familiar\nfrom the languages like Scala or Haskell, \n%\\index{Scala}\\index{Haskell}%and it inserted by Coq automatically\nevery time it expects to see a proposition of sort [Prop], but instead\nencounters a boolean value. Let us consider the following goal as an\nexample:\n\n*)\n\nGoal prime (16 + 14) -> False.\nProof. done. Qed.\n\n(** \n\nAs we can see, the proof is rather short, and, in fact, done by\nCoq/Ssreflect fully automatically. In fact, the system first\n_computes_ the value of [prime (16 + 14)], which is, obviously\n[false]. Then the boolean value [false] is coerced into the\npropositional equality [false = true], as previously described. The\nequality is then automatically discriminated (%see\nSection~\\ref{sec:discr}%), which allows the system to infer the\nfalsehood, completing the proof.\n\nThis example and the previous discussion should convey the idea that\n_decidable propositions should be implemented as computable functions\nreturning a boolean result_. This simple design pattern makes it\npossible to take full advantage of the computational power of Coq as a\nprogramming language and prove decidable properties automatically,\nrather than by means of imposing a burden of constructing an explicit\nproof. We have just seen how a boolean result can be easily injected\nback to the world of propositions. This computational approach to\nproofs is what has been taken by Ssreflect to the extreme, making the\nproofs about common mathematical constructions to be very short, as\nmost of the proof obligations simply _do not appear_, as the system is\npossible to reduce them by means of performing the computations on the\nfly. Even though, as discussed, some propositions can be only encoded\nas elements of [Prop], our general advice is to rely on the\ncomputations whenever it is possible.\n\nIn the following subsections we will elaborate on some additional\nspecifications and proof patterns, which are enabled by using boolean\nvalues instead of full-fledged propositions from [Prop].\n\n** Using conditionals in predicates\n\nThe ternary conditional operator [if-then-else] is something that\nprogrammers use on a regular basis. However, when it comes to the\nspecifications in the form of Coq's standard propositions it turns out\none cannot simply employ the [if-then-else] connective in them, as it\nexpects its conditional argument to be of type [bool]. This\nrestriction is, again, a consequence of the fact that the result of\n[if-then-else] expression should be computable, which conflicts with\nthe fact that not every proposition is decidable and, hence, there is\nno sound way overload the conditional operator, so it would rely on\nthe existence of the proof of its conditional (or its negation).\n\n[[\nDefinition prime_spec_bad n m : Prop := m = (if isPrime n then 1 else 2).\n\nError: In environment\nm : nat\nn : nat\nThe term \"isPrime n\" has type \"Prop\" while it is expected to have type \"bool\".\n]]\n\nFortunately, the computable predicates are free from this problem, so\non can freely use them in the conditionals:\n\n*)\n\nDefinition prime_spec n m : Prop := m = (if prime n then 1 else 2).\n\n(**\n\n** Case analysing on a boolean assumption\n\nAnother advantage of the boolean predicates is that they automatically\ncome with a natural case analysis principle: reasoning about an\noutcome of a particular predicate, one can always consider two\npossibilities: when it returned [true] or [false].%\\footnote{We have\nalready seen an instance of such case analysis in the proof of the\n%[leqP]% lemma in Section~\\ref{sec:enccustom} of\nChapter~\\ref{ch:eqrew}, although deliberately did not elaborate on it\nback then.}% This makes it particularly pleasant to reason about the\nprograms and specifications that use conditionals, which is\ndemonstrated by the following example.\n\n*)\n\nDefinition discr_prime n := (if prime n then 0 else 1) + 1.\n\n(** \n\nLet us now prove that the definition [prime_spec] gives a precise\nspecification of the function [discr_prime]:\n\n*)\n\nLemma discr_prime_spec : forall n, prime_spec n (discr_prime n).\nProof.\nmove=>n. rewrite /prime_spec /discr_prime.\n\n(**\n\n[[\n n : nat\n ============================\n (if prime n then 0 else 1) + 1 = (if prime n then 1 else 2)\n]]\n\nThe proof of the specification is totally in the spirit of what one\nwould have done when proving it manually: we just case-analyse on the\nvalue of [prime n], which is either [true] or [false]. Similarly to\nthe way the rewritings are handled by means of unification, in both\ncases the system substitutes [prime n] with its boolean value in the\nspecification as well. The evaluation completes the proof.\n\n*)\n\nby case: (prime n).\nQed.\n\n(**\n\nAnother common use case of boolean predicates comes from the\npossibility to perform a case analysis on the boolean _computable\nequality_, which can be employed in the proof proceeding by an\nargument \"let us assume [a] to be equal to [b] (or not)\". As already\nhinted by the example with the function equality earlier in this\nsection, the computable equality is not always possible to\nimplement. Fortunately, it can be implemented for a large class of\ndatatypes, such as booleans, natural numbers, lists and sets (of\nelements with computable equality), and it was implemented in\nSsreflect, so one can take an advantage of it in the\nproofs.%\\footnote{The way the computable equality is encoded so it\nwould work uniformly for different types is an interesting topic by\nitself, so we postpone its explanation until\nChapter~\\ref{ch:depstruct}}%\n\n*)\n\n(** * %The \\textsf{\\textbf{reflect}} type family%\n%\\label{sec:reflect}%\n\n\nBeing able to state all the properties of interest in a way that they\nare decidable is a true blessing. However, even though encoding\neverything in terms of [bool]-returning functions and connectives\ncomes with the obvious benefits, reasoning in terms of [Prop]s might\nbe more convenient when the information of the structure of the proofs\nmatters. For instance, let us consider the following situation:\n\n*)\n\nVariables do_check1 do_check2 : nat -> bool.\nHypothesis H: forall n, do_check2 n -> prime n.\n\nLemma check_prime n : (do_check1 n) && (do_check2 n) -> prime n.\n\n(** \n\nThe lemma [check_prime] employs the boolean conjunction [&&] from the\n[ssrbool] module in its assumption, so we know that its result is some\nboolean value. However simply case-analysing on its component does not\nbring any results. What we want indeed is a way to _decompose_ the\nboolean conjunction into the components and then use the hypothesis\n[H]. This is what could be accomplished easily, had we employed the\n_propositional conjunction_ [/\\] instead, as it comes with a\ncase-analysis principle.\n\n\n*)\n\n(** %\\ccom{Abort}% *)\nAbort.\n\n(**\n\nThis is why we need a mechanism to conveniently switch between two\npossible representation. Ssreflect solves this problem by employing\nthe familiar rewriting machinery (%see Section~\\ref{sec:indexed} of\nChapter~\\ref{ch:eqrew}%) and introducing the inductive predicate\nfamily [reflect], which connects propositions and booleans:\n\n%\\ssrd{reflect}%\n%\\index{reflect datatype@{\\textsf{reflect} datatype}}%\n\n*)\n\nPrint Bool.reflect.\n\n(**\n[[\nInductive reflect (P : Prop) : bool -> Set :=\n | ReflectT of P : reflect P true\n | ReflectF of ~ P : reflect P false.\n]]\n\nSimilarly to the custom rewriting rules, the [reflect] predicate is\nnothing but a convenient way to encode a \"truth\" table with respect to\nthe predicate [P], which is [reflect]'s only parameter. In other\nwords, the propositions [(reflect P b)] ensures that [(is_true b)] and\n[P] are logically equivalent and can be replaced one by another. For\ninstance, the following rewriting lemmas %\\index{rewriting lemma}% can\nbe proved for the simple instances of [Prop].\n\n*)\n\nLemma trueP : reflect True true.\nProof. by constructor. Qed.\n\nLemma falseP : reflect False false.\nProof. by constructor. Qed.\n\n(** \n\nThe proofs with boolean truth and falsehood can be then completed by\ncase analysis, as with any other rewriting rules:\n\n*)\n\nGoal false -> False.\nProof. by case:falseP. Qed.\n\n(**\n\n** Reflecting logical connectives\n\nThe true power of the [reflect] predicate, though, is that it might be\nput to work with arbitrary logical connectives and user-defined\npredicates, therefore delivering the rewriting principles, allowing\none to switch between [bool] and [Prop] (in the decidable case) by\nmeans of rewriting lemmas. Ssreflect comes with a number of such\nlemmas, so let us consider one of them, [andP].\n\n*)\n\nLemma andP (b1 b2 : bool) : reflect (b1 /\\ b2) (b1 && b2).\nProof. by case b1; case b2; constructor=> //; case. Qed.\n\n(** \n\nNotice that [andP] is stated over two boolean variables, [b1] and\n[b2], which, nevertheless, are treated as instances of [Prop] in the\nconjunction [/\\], being implicitly coerced. \n\nWe can now put this lemma to work and prove our initial example:\n\n*)\n\nLemma check_prime n : (do_check1 n) && (do_check2 n) -> prime n.\nProof.\ncase: andP=>//.\n\n(**\n[[\n n : nat\n ============================\n do_check1 n /\\ do_check2 n -> true -> prime n\n]]\n\nCase analysis on the rewriting rule [andP] generates two goals, and\nthe second one has [false] as an assumption, so it is discharged\nimmediately by using %\\texttt{//}\\ssrtl{//}%. The remaining goal has a\nshape that we can work with, so we conclude the proof by applying the\nhypothesis [H] declared above.\n\n*)\n\nby case=>_ /H.\nQed.\n\n(** \n\nAlthough the example above is a valid usage of the reflected\npropositions, Ssreflect leverages the rewriting with respect to\nboolean predicates even more by defining a number of _hint views_ for\nthe rewriting lemmas that make use of the [reflect] predicates. This\nallows one to use the rewriting rules (e.g., [andP]) in the form of\n_views_ %\\index{views}%, which can be applied directly to an\nassumption or a goal, as demonstrated by the next definition.\n\n*)\n\nDefinition andb_orb b1 b2: b1 && b2 -> b1 || b2.\nProof.\ncase/andP=>H1 H2.\nby apply/orP; left.\nQed.\n\n(** \n\nThe first line of the proof switched the top assumption from the\nboolean conjunction to the propositional one by means of [andP] used\nas a view. The second line applied the [orP] view, doing the similar\nswitch in the goal, completing the proof by using a constructor of the\npropositional disjunction.\n\n*)\n\nPrint andb_orb.\n\n\n(**\n\nLet us take a brief look to the obtained proof term for [andb_orb].\n\n[[\nandb_orb = \nfun (b1 b2 : bool) (goal : b1 && b2) =>\n(fun F : forall (a : b1) (b : b2),\n (fun _ : b1 /\\ b2 => is_true (b1 || b2)) (conj a b) =>\n match\n elimTF (andP b1 b2) goal as a return ((fun _ : b1 /\\ b2 => is_true (b1 || b2)) a)\n with\n | conj x x0 => F x x0\n end)\n (fun (H1 : b1) (_ : b2) =>\n (fun F : if true then b1 \\/ b2 else ~ (b1 \\/ b2) =>\n introTF (c:=true) orP F) (or_introl H1))\n : forall b1 b2 : bool, b1 && b2 -> b1 || b2\n]]\n\nAs we can see, the calls to the rewriting lemmas [andP] and [orP] were\nimplicitly \"wrapped\" into the call of hints [elimTF] and [introTF],\ncorrespondingly. Defined via the conditional operator, both these view\nhints allowed us to avoid the second redundant goal, which we would be\nbe forced to deal with, had we simply gone with case analysis on\n[andP] and [orP] as rewriting rules.\n\n*)\n\nCheck elimTF.\n\n(** \n[[\nelimTF\n : forall (P : Prop) (b c : bool),\n reflect P b -> b = c -> if c then P else ~ P\n]]\n\n%\\begin{exercise}[Reflecting exclusive disjunction]%\n\nLet us define a propositional version of the _exclusive or_\n%\\index{exclusive disjunction}% predicate:\n\n*)\n\nDefinition XOR (P Q: Prop) := (P \\/ Q) /\\ ~(P /\\ Q).\n\n(** \n%\\noindent%\nas well as its boolean version (in a curried form, so it takes just\none argument and returns a function):\n\n*)\n\nDefinition xorb b := if b then negb else fun x => x.\n\n(** \n%\\noindent%\nNow, prove the following _generalized_ reflection lemma [xorP_gen] and\nits direct consequence, the usual reflection lemma [xorP]:\n\n%\\hint% Recall that the _reflect_ predicate is just a rewriting rule,\n so one can perform a case analysis on it.\n\n*)\n\nLemma xorP_gen (b1 b2 : bool)(P1 P2: Prop): \n reflect P1 b1 -> reflect P2 b2 -> reflect (XOR P1 P2) (xorb b1 b2).\n(* begin hide *)\nProof.\ncase=>H1; case=>H2; constructor; rewrite /XOR. \n- by case; case=>H; apply.\n- split; first by left. \n by case=>_ H; apply: H2.\n- split; first by right.\n by case=>H _; apply: H1.\n- intuition.\nQed.\n(* end hide *)\n\nLemma xorP (b1 b2 : bool): reflect (XOR b1 b2) (xorb b1 b2).\n(* begin hide *)\nProof.\nby apply: xorP_gen; case:b1=>//=; case:b2=>//=; constructor.\nQed.\n(* end hide *)\n\n\n(** \n%\\end{exercise}%\n\n%\\begin{exercise}[Alternative formulation of exclusive disjunction]%\n\nLet us consider an alternative version of exclusive or, defined by\nmeans of the predicate [XOR']:\n\n*)\n\nDefinition XOR' (P Q: Prop) := (P /\\ ~Q) \\/ (~P /\\ Q).\n(** \n%\\noindent%\n\nProve the following equivalence lemma between to versions of [XOR]:\n\n*)\n\nLemma XORequiv P Q: XOR P Q <-> XOR' P Q.\n(* begin hide *)\nProof.\nsplit. \n- case; case=>[p|q] H. \n - by left; split=>// q; apply: H.\n by right; split=>// p; apply H.\ncase; case=>p q.\n- split=>[| H]; first by left.\n by apply: q; case: H.\nsplit; first by right. \nby case=>/p.\nQed.\n(* end hide *)\n\n(** \n%\\noindent%\nThe final step is to use the equivalence we have just proved in order\nto establish an alternative version of the reflective correspondence\nof exclusive disjunction.\n\n%\\hint% Use the [Search] machinery to look for lemmas that might help\n to leverage the equivalence between two predicates and make the\n following proof to be a one-liner.\n\n*)\n\n(* Search _ (reflect _ _). *)\nLemma xorP' (b1 b2 : bool): reflect (XOR' b1 b2) (xorb b1 b2).\n(* begin hide *)\nProof.\nby apply: (equivP (xorP b1 b2) (XORequiv _ _)).\nQed.\n(* end hide *)\n \n(** \n\n%\\end{exercise}%\n\nUnsurprisingly, every statement about exclusive or, e.g., its\ncommutativity and associativity, is extremely easy to prove when it is\nconsidered as a boolean function. \n\n*)\n\nLemma xorbC (b1 b2: bool) : (xorb b1 b2) = (xorb b2 b1). \nProof. by case: b1; case: b2. Qed.\n\nLemma xorbA (b1 b2 b3: bool) : (xorb (xorb b1 b2) b3) = (xorb b1 (xorb b2 b3)). \nProof. by case: b1; case: b2; case: b3=>//. Qed.\n\n(** \n\nIt is also not difficult to prove the propositional counterparts of\nthe above lemmas for decidable propositions, reflected by them, hence\nthe following exercise.\n\n%\\begin{exercise}%\n\nProve the following specialized lemmas for decidable propositions\nrepresented by booleans (without using the [intuition] tactic):\n\n*)\n\nLemma xorCb (b1 b2: bool) : (XOR b1 b2) <-> (XOR b2 b1). \n(* begin hide *)\nProof.\nby split; move/xorP; rewrite xorbC; move/xorP.\nQed.\n(* end hide *)\n\nLemma xorAb (b1 b2 b3: bool) : (XOR (XOR b1 b2) b3) <-> (XOR b1 (XOR b2 b3)). \n(* begin hide *)\nProof.\nsplit=>H. \napply: (xorP_gen b1 (xorb b2 b3) b1 (XOR b2 b3)); first by case: b1 {H}; constructor.\n- by apply/xorP.\n- rewrite -xorbA. \n apply/(xorP_gen (xorb b1 b2) b3 (XOR b1 b2) b3)=>//; first by apply/xorP. \n by case: b3 {H} =>//; constructor.\napply: (xorP_gen (xorb b1 b2) b3 (XOR b1 b2) b3). \n- by apply/xorP.\n- by case: b3 {H}; constructor.\nrewrite xorbA. \napply/(xorP_gen b1 (xorb b2 b3) b1 (XOR b2 b3))=>//; last by apply/xorP. \nby case: b1 {H} =>//; constructor.\nQed.\n(* end hide *)\n\n(** \n\n%\\hint% In the proof of [xorAb] the generalized reflection lemma\n [xorP_gen] might come in handy.\n\n%\\hint% A redundant assumption [H] in the context can be erased by\n typing [clear H] %\\ttac{clear}% or [move => {H}]. The latter form can\n be combined with any bookkeeping sequence, not only with [move]\n tactics.\n\n%\\hint% The Coq's embedded tactic [intuition] can be helpful for\n automatically solving goals in propositional logic.%\\ttac{intuition}%\n\n%\\end{exercise}%\n\n** Reflecting decidable equalities\n%\\label{sec:eqrefl}%\n\nLogical connectives are not the only class of inductive predicates\nthat is worth building a [reflect]-based rewriting principle for.\nAnother useful class of decidable propositions, which are often\nreflected, are equalities.\n\nPostponing the description of a generic mechanism for declaring\npolymorphic decidable equalities until %Chapter~\\ref{ch:depstruct}%,\nlet us see how switching between decidable [bool]-returning equality\n[==] (defined in the Ssreflect's module [eqtype]%\\ssrm{eqtype}%) and\nthe familiar propositional equality can be beneficial.\n\n*)\n\nDefinition foo (x y: nat) := if x == y then 1 else 0.\n\n(** \n\nThe function [foo] naturally uses the natural numbers' boolean\nequality [==] in its body, as it is the only one that can be used in\nthe conditional operator. The next goal, though, assumes the\npropositional equality of [x] and [y], which are passed to [foo] as\narguments.\n\n*)\n\nGoal forall x y, x = y -> foo x y = 1.\nProof.\nmove=>x y; rewrite /foo.\n\n(** \n\n[[\n x : nat\n y : nat\n ============================\n x = y -> (if x == y then 1 else 0) = 1\n]]\n\nThe rewriting rule/view lemma [eqP], imported from [eqtype] allows us\nto switch from propositional to boolean equality, which\nmakes the assumption to be [x == y]. Next, we combine the implicit\nfact that [x == y] in the assumption of a proposition is in fact [(x\n== y) = true] to perform in-place rewriting (see\n%Section~\\ref{sec:in-place}%) by means of the %\\texttt{->}\\ssrtl{->}%\ntactical, so the rest of the proof is simply by computation.\n\n*)\n\nby move/eqP=>->.\nQed.\n\n\n(**\n\n%\\begin{exercise}%\n\nSometimes, the statement ``there exists unique $x$ and $y$, such that\n$P(x, y)$ holds'' is mistakingly formalized as $\\exists ! x~\\exists !\ny~P(x, y)$. In fact, the latter assertion is much weaker than the\nprevious one. The goal of this exercise is to demonstrate this\nformally.%\\footnote{I am grateful to Vladimir Reshetnikov\n(\\href{https://twitter.com/vreshetnikov}{\\texttt{@vreshetnikov}}) for\nmaking this observation on Twitter.}%\n\nFirst, prove the following lemma, stating that the first assertion can\nbe weakened from the second one.\n\n*)\n\nLemma ExistsUnique1 A (P : A -> A -> Prop): \n (exists !x, exists y, P x y) -> \n (exists !x, exists y, P y x) ->\n (exists !x, exists !y, P x y).\n\n(**\n\nThe notation [exists ! x, P x] is an abbreviation for the sigma-type,\nwhose second component is the higher-order predicate [unique], defined\nas follows:\n\n*)\n\nPrint unique.\n\n(**\n[[\nunique = \nfun (A : Type) (P : A -> Prop) (x : A) =>\nP x /\\ (forall x' : A, P x' -> x = x')\n : forall A : Type, (A -> Prop) -> A -> Prop\n]]\n\nAs we can see, the definition [unique] not just ensures that [P x]\nholds (the left conjunct), but also that any [x'] satisfying [P] is,\nin fact, equal to [x]. As on the top level [unique] is merely a\nconjunction, it can be decomposed by [case] and proved using the\n[split] tactics.\n\n*)\n\n(* begin hide *)\nProof.\ncase=>x1[[y1 Pxy1]] G1[x2[[y2 Pxy2]] G2]; exists y2; split.\n- by exists x2; split=>// x0 Pxy0; apply: G2; exists y2.\nmove=>x'. move:(G1 x')=>E G3.\nrewrite -E; last by case: G3=>y'; case=> Z _; exists y'.\nsuff X: x1 = y2; first by [].\nby apply: G1; exists x2.\nQed.\n(* end hide *)\n\n(**\n\nNext, let us make sure that the statement in the conclusion of lemma\n[ExistsUnique1], in fact, admits predicates, satisfied by non-uniquely\ndefined pair [(x, y)]. You goal is to prove that the following\npredicate [Q], which obviously satisfied by [(true, true)], [(false,\ntrue)] and [(false, false)] is nevertheless a subject of the second\nstatement.\n\n*)\n\nDefinition Q x y : Prop := \n (x == true) && (y == true) || (x == false).\n\nLemma qlm : (exists !x, exists !y, Q x y).\n\n(* begin hide *)\nProof.\nexists true; split; first by exists true; split=> //; case.\ncase=>//; rewrite /Q; case; case=>/=; case=>_ G.\n- by move:(G false (eqxx false)).\nby move:(G true (eqxx true)). \nQed.\n(* end hide *)\n\n(**\n\n%\\hint% The following lemma [eqxx], stating that the boolean equality\n [x == x] always holds, might be useful for instantiating arguments\n for hypotheses you will get during the proof.\n\n*)\n\nCheck eqxx.\n\n(**\n[[\neqxx\n : forall (T : eqType) (x : T), x == x\n]]\n\nFinally, you are invited to prove that the second statement is\n_strictly_ weaker than the first one by proving the following lemma,\nwhich states that the reversed implication of the two statements for\nan arbitrary predicate [P] implies falsehood.\n\n*)\n\nLemma ExistsUnique2 : \n (forall A (P : A -> A -> Prop),\n (exists !x, exists !y, P x y) ->\n (exists !x, exists y, P x y) /\\ (exists !x, exists y, P y x)) ->\n False.\n\n(* begin hide *)\nProof.\nmove/(_ _ _ qlm); rewrite /Q/=; case=> H1 H2.\ncase: H1; case; case; case; case=> //= _.\n- move=>G1; move:(G1 false)=>/=G2. \n by suff: true = false by []; last by apply: G2; exists true.\n- move=>G1; move:(G1 true)=>/=G2. \n by suff: false = true by []; last by apply: G2; exists true.\n- move=>G1; move:(G1 true)=>/=G2. \n by suff: false = true by []; last by apply: G2; exists true.\nQed.\n(* end hide *)\n\n(**\n%\\end{exercise}%\n*)\n\n(* begin hide *)\nEnd BoolReflect.\n(* end hide *)\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/coq/BoolReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.11596072894699294, "lm_q1q2_score": 0.05345984178585113}} {"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Stephane Le Roux, 2006-10-17\n- Adam Koprowski, 2006-04-28\n- Solange Coupet-Grimal and William Delobel, 2006-01-09\n- Frederic Blanqui, 2005-02-03, 2009-07-06\n- Sebastien Hinderer, 2004-05-25\n\nExtension of the Coq library on lists.\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import LogicUtil EqUtil RelUtil BoolUtil NatUtil.\n\nFrom Coq Require Import Setoid SetoidList FunInd.\nFrom Coq Require Export List.\nFrom Coq Require Program.\n\n\nArguments nil {A}.\nArguments incl {A} l m.\nArguments in_app_or [A l m a] _.\nArguments in_map [A B] f [l x] _.\nArguments in_combine_l [A B l l' x y] _.\nArguments in_combine_r [A B l l' x y] _.\nArguments nth_In [A n l] d _.\n\nLtac elt_type l := match type of l with list ?A => A end.\n\nInfix \"[=\" := incl (at level 70).\n\n(***********************************************************************)\n(** Properties of [In] (membership predicate on lists). *)\n\nSection In.\n\n Variable A : Type.\n\n Lemma in_app : forall l m (x : A), In x (l ++ m) <-> In x l \\/ In x m.\n\n Proof. intuition. Qed.\n\n Lemma notin_app : forall l m (x : A), ~In x (l ++ m) <-> ~In x l /\\ ~In x m.\n\n Proof. intuition. rewrite in_app in H0. intuition. Qed.\n\n Lemma in_appl : forall (x : A) l1 l2, In x l1 -> In x (l1 ++ l2).\n\n Proof.\n induction l1; simpl; intros. contr. destruct H. subst x. auto.\n right. apply IHl1. hyp.\n Qed.\n\n Lemma in_appr : forall (x : A) l1 l2, In x l2 -> In x (l1 ++ l2).\n\n Proof. induction l1; simpl; intros. hyp. right. apply IHl1. hyp. Qed.\n\n Lemma in_app_com : forall (x : A) l1 l2 l3,\n In x ((l1 ++ l3) ++ l2) -> In x ((l1 ++ l2) ++ l3).\n\n Proof. intros. rewrite !in_app in H. intuition. Qed.\n\n Lemma in_elim : forall (x : A) l,\n In x l -> exists l1, exists l2, l = l1 ++ x :: l2.\n\n Proof.\n induction l; simpl; intros. contr. destruct H. subst x.\n exists nil. exists l. refl. ded (IHl H). do 2 destruct H0. rewrite H0.\n exists (a :: x0). exists x1. refl.\n Qed.\n\n Variable eqA_dec : forall x y : A, {x=y}+{~x=y}.\n\n Lemma in_elim_dec : forall (x : A) l,\n In x l -> exists m, exists p, l = m ++ x :: p /\\ ~In x m.\n\n Proof.\n induction l; simpl; intros. contr. destruct H. subst x.\n exists nil. exists l. intuition. ded (IHl H). do 3 destruct H0.\n subst l. case (eqA_dec a x); intro.\n subst x. exists nil. exists (x0 ++ a :: x1). intuition.\n exists (a :: x0). exists x1. intuition. simpl in H2. destruct H2; auto.\n Qed.\n\n Lemma In_midex : eq_midex A -> forall (x : A) l, In x l \\/ ~In x l. \n\n Proof.\n induction l. tauto. simpl. destruct (H a x); destruct IHl; tauto.\n Qed.\n\n Lemma In_elim_right : eq_midex A -> forall (x : A) l,\n In x l -> exists l', exists l'', l = l'++x::l'' /\\ ~In x l''. \n\n Proof.\n induction l; simpl; intros. contr. \n destruct (In_midex H x l). destruct IHl. hyp. destruct H2. \n ex (a::x0) x1. rewrite (proj1 H2), <- (app_comm_cons x0 (x::x1) a). tauto. \n destruct H0. ex (@nil A) l. simpl. rewrite H0. tauto. contr.\n Qed.\n\n Lemma In_cons : forall (x a : A) l, In x (a::l) <-> a=x \\/ In x l. \n\n Proof.\n intros. simpl. tauto.\n Qed.\n\n Lemma In_InA_eq : forall (x : A) l, In x l <-> InA eq x l.\n\n Proof.\n induction l; simpl. sym. apply InA_nil. rewrite IHl, InA_cons.\n intuition.\n Qed.\n\nEnd In.\n\nArguments in_elim [A x l] _.\nArguments in_elim_dec [A] _ [x l] _.\n\nLtac intac := repeat (apply in_eq || apply in_cons).\n\nLtac list_ok := let x := fresh in intro x;\n match goal with\n | |- In _ ?l => vm_compute; destruct x; tauto\n end.\n\n(***********************************************************************)\n(** Properties of [incl]\n (non-order-preserving inclusion predicate on lists). *)\n\n#[export] Instance incl_preorder A : PreOrder (@incl A).\n\nProof.\n constructor.\n intro x. apply incl_refl.\n intros x y z xy yz. apply incl_tran with y; hyp.\nQed.\n\n#[export] Instance app_incl A : Proper (incl ==> incl ==> incl) (@app A).\n\nProof. intros l l' ll' m m' mm' x. rewrite !in_app. intuition. Qed.\n\nSection incl.\n\n Variable A : Type.\n\n Lemma incl_nil_elim : forall l : list A, l [= nil <-> l = nil.\n\n Proof.\n unfold incl. destruct l; intuition. assert (In a (a::l)). left. refl.\n ded (H _ H0). contr. discr.\n Qed.\n\n Lemma incl_nil : forall l : list A, nil [= l.\n\n Proof. induction l. refl. apply incl_tl. hyp. Qed.\n\n Lemma incl_cons_l : forall (a : A) l m, a :: l [= m -> In a m /\\ l [= m.\n\n Proof. intros a l m. unfold incl. simpl. intuition. Qed.\n\n Lemma incl_cons_l_in : forall (x : A) l m, x :: l [= m -> In x m.\n\n Proof. unfold incl. simpl. intros. apply H. left. refl. Qed.\n\n Lemma incl_cons_l_incl : forall (x : A) l m, x :: l [= m -> l [= m.\n\n Proof. unfold incl. simpl. intros. apply H. tauto. Qed.\n\n Lemma incl_app_elim : forall l1 l2 l3 : list A,\n l1 ++ l2 [= l3 -> l1 [= l3 /\\ l2 [= l3.\n\n Proof.\n intuition.\n trans (l1 ++ l2). apply incl_appl. refl. hyp.\n trans (l1 ++ l2). apply incl_appr. refl. hyp.\n Qed.\n\n Lemma incl_appr_incl : forall l1 l2 l3 : list A, l1 ++ l2 [= l3 -> l1 [= l3.\n\n Proof.\n induction l1; intros. apply incl_nil.\n trans ((a::l1) ++ l2). 2: hyp. apply incl_appl. refl.\n Qed.\n\n Lemma incl_appl_incl : forall l1 l2 l3 : list A, l1 ++ l2 [= l3 -> l2 [= l3.\n\n Proof.\n induction l1; intros. hyp.\n trans ((a::l1) ++ l2). 2: hyp. apply incl_appr. refl.\n Qed.\n\n Lemma appl_incl : forall l l2 l2' : list A, l2 [= l2' -> l ++ l2 [= l ++ l2'.\n\n Proof. intros. apply app_incl. refl. hyp. Qed.\n\n Lemma appr_incl : forall l l1 l1' : list A, l1 [= l1' -> l1 ++ l [= l1' ++ l.\n\n Proof. intros. apply app_incl. hyp. refl. Qed.\n\n Lemma app_com_incl : forall l1 l2 l3 l4 : list A,\n (l1 ++ l3) ++ l2 [= l4 -> (l1 ++ l2) ++ l3 [= l4.\n\n Proof. unfold incl. intros. apply H. apply in_app_com. hyp. Qed.\n\n Lemma incl_cons_r : forall x : A, forall m l, l [= x :: m -> In x l \\/ l [= m.\n\n Proof.\n induction l; simpl; intros. right. apply incl_nil.\n ded (incl_cons_l H). destruct H0. simpl in H0. destruct H0. auto.\n ded (IHl H1). destruct H2. auto.\n right. apply List.incl_cons; hyp.\n Qed.\n\n Variable eqA_dec : forall x y : A, {x=y}+{~x=y}.\n\n Lemma not_incl : forall l m, ~ l [= m <-> exists x:A, In x l /\\ ~In x m.\n\n Proof.\n induction l; simpl; intros.\n (* nil *)\n intuition. absurd (nil[=m). hyp. apply incl_nil.\n do 2 destruct H. contr.\n (* cons *)\n split; intro.\n 2:{ do 3 destruct H.\n subst. intro. apply H0. apply H. left. refl.\n intro. absurd (In x m). hyp. apply H1. right. hyp. }\n case (In_dec eqA_dec a m); intro.\n assert (~l[=m). intro. apply H. unfold incl. intro b. simpl. intuition.\n rewrite IHl in H0. do 2 destruct H0. exists x. tauto.\n exists a. tauto.\n Qed.\n\nEnd incl.\n\nArguments incl_app_elim [A l1 l2 l3] _.\n\n(***********************************************************************)\n(** Strict inclusion. *)\n\nDefinition strict_incl A (l m : list A) := l [= m /\\ ~m [= l.\n\nInfix \"[\" := strict_incl (at level 70).\n\nLemma strict_incl_tran : forall A (l m n : list A), l [ m -> m [ n -> l [ n.\n\nProof.\nunfold strict_incl. intuition. trans m; hyp.\napply H2. trans n; hyp.\nQed.\n\n#[export] Instance strict_incl_rel A : Transitive (@strict_incl A).\n\nProof. intros x y z xy yz. apply strict_incl_tran with y; hyp. Qed.\n\n(***********************************************************************)\n(** Equivalence (i.e. having the same elements). *)\n\nDefinition lequiv {A} (l1 l2 : list A) := l1 [= l2 /\\ l2 [= l1.\n\nInfix \"[=]\" := lequiv (at level 70).\n\n#[export] Instance lequiv_rel A : Equivalence (@lequiv A).\n\nProof. constructor. fo. fo. constructor. inversion H0. inversion H. unfold incl. unfold incl in H3. unfold incl in H1. clear H H0 H2 H4. intros. apply H3 in H. apply H1 in H. trivial. fo. Qed.\n\n\n\n#[export] Instance app_lequiv A : Proper (lequiv ==> lequiv ==> lequiv) (@app A).\n\nProof. intros l l' ll' m m' mm'. unfold lequiv in *. intuition. Qed.\n\n#[export] Instance incl_lequiv1 A1 B (f : list A1 -> relation B) :\n Proper (incl ==> inclusion) f -> Proper (lequiv ==> same) f.\n\nProof. intros hf l1 l1' [l1l1' l1'l1]. split; apply hf; hyp. Qed.\n\n#[export] Instance incl_lequiv2 A1 A2 B (f : list A1 -> list A2 -> relation B) :\n Proper (incl ==> incl ==> inclusion) f ->\n Proper (lequiv ==> lequiv ==> same) f.\n\nProof.\n intros hf l1 l1' [l1l1' l1'l1] l2 l2' [l2l2' l2'l2]. split; apply hf; hyp.\nQed.\n\n(***********************************************************************)\n(** Properties of the empty list. *)\n\nSection nil.\n\n Variable A : Type.\n\n Lemma list_empty_dec : forall l : list A, {l = nil} + {l <> nil}.\n\n Proof. destruct l; auto. right; congruence. Qed.\n\n Definition is_empty (l : list A) : bool :=\n match l with\n | nil => true\n | _ => false\n end.\n\nEnd nil.\n\n(***********************************************************************)\n(** Properties of [cons]. *)\n\n#[export] Instance cons_incl A : Proper (eq ==> incl ==> incl) (@cons A). \n\nProof. intros x x' xx'. subst x'. fo. Qed.\n\n#[export] Instance cons_lequiv A : Proper (eq ==> lequiv ==> lequiv) (@cons A).\n\nProof. intros x x' xx'. subst x'. fo. Qed.\n\nSection cons.\n\n Variable A : Type.\n\n Lemma cons_eq : forall x x' : A, forall l l',\n x = x' -> l = l' -> x :: l = x' :: l'.\n\n Proof. intros. rewrite H, H0. refl. Qed.\n\n Lemma head_eq : forall x x' : A, forall l, x = x' -> x :: l = x' :: l.\n\n Proof. intros. rewrite H. refl. Qed.\n\n Lemma tail_eq : forall x : A, forall l l', l = l' -> x :: l = x :: l'.\n\n Proof. intros. rewrite H. refl. Qed.\n\nEnd cons.\n\n(***********************************************************************)\n(** Properties of [app] (concatenation). *)\n\nSection app.\n\n Variable A : Type.\n\n Lemma length_app : forall l m : list A, length (l ++ m) = length l + length m.\n\n Proof. induction l; simpl; intros. refl. rewrite IHl. refl. Qed.\n\n Lemma app_nil : forall l1 l2 : list A, l1 = nil -> l2 = nil -> l1 ++ l2 = nil.\n\n Proof. intros. subst l1. subst l2. refl. Qed.\n\n Lemma app_eq : forall l1 l2 l1' l2' : list A,\n l1 = l1' -> l2 = l2' -> l1 ++ l2 = l1' ++ l2'.\n\n Proof. intros. rewrite H, H0. refl. Qed.\n\n Lemma appl_eq : forall l1 l2 l1' : list A, l1 = l1' -> l1 ++ l2 = l1' ++ l2.\n\n Proof. intros. rewrite H. refl. Qed.\n\n Lemma appr_eq : forall l1 l2 l2' : list A, l2 = l2' -> l1 ++ l2 = l1 ++ l2'.\n\n Proof. intros. rewrite H. refl. Qed.\n\n Lemma list_app_first_last : forall l m (a : A),\n (l ++ a::nil) ++ m = l ++ a::m.\n\n Proof.\n induction l. auto.\n intros m a'. rewrite <- !app_comm_cons. destruct (IHl m a'); trivial.\n Qed.\n\n Lemma list_app_last : forall l m n (a : A),\n l ++ m = n ++ a::nil -> m <> nil -> In a m.\n\n Proof.\n intros l m n; revert l m; induction n; simpl; intros.\n (* induction base *)\n destruct l.\n simpl in H; rewrite H; auto with datatypes.\n inversion H.\n absurd (m = nil); trivial.\n apply (proj2 (app_eq_nil l m H3)).\n (* induction case *)\n destruct l.\n simpl in H; rewrite H; auto with datatypes.\n inversion H.\n apply IHn with l; trivial.\n Qed.\n\n Lemma list_drop_last : forall l m n (a : A),\n l ++ m = n ++ a::nil -> m <> nil -> exists2 w, w [= m & l ++ w = n.\n\n Proof.\n induction l; intros.\n (* induction base *)\n simpl in H.\n exists n.\n rewrite H; auto with datatypes.\n auto.\n (* induction case *)\n destruct n.\n (* n = nil -> contr *)\n simpl in H.\n destruct (app_eq_unit (a::l) m H) as \n [[l_nil r_unit] | [l_unit r_nil]]; try contr.\n discr.\n (* n <> nil *) \n inversion H.\n destruct (IHl m n a0); trivial.\n exists x; trivial.\n rewrite <- H4.\n auto with datatypes.\n Qed.\n\n Lemma last_intro : forall l : list A, length l > 0 ->\n exists m, exists a, l = m ++ a :: nil /\\ length m = length l - 1.\n\n Proof.\n induction l; simpl; intros. apply False_ind. lia.\n destruct l. exists nil. exists a. intuition.\n assert (length (a0::l) > 0). simpl. lia.\n ded (IHl H0). do 3 destruct H1.\n exists (a::x). exists x0. split. rewrite H1. refl.\n simpl. simpl in H2. lia.\n Qed.\n\nEnd app.\n\n(***********************************************************************)\n(** Properties of [length]. *)\n\nSection length.\n\n Variable A : Type.\n\n Lemma length_0 : forall l : list A, length l = 0 -> l = nil.\n\n Proof. intros. destruct l. refl. discr. Qed.\n\nEnd length.\n\nArguments length_0 [A l] _.\n\n(***********************************************************************)\n(** Properties of [head] and [tail]. *)\n\nSection head_tail.\n\n Variable A : Type.\n\n Lemma head_app : forall (l l': list A) (lne: l <> nil),\n head (l ++ l') = head l.\n\n Proof. destruct l. tauto. auto. Qed.\n\n Lemma length_tail : forall l : list A, length (tail l) <= length l.\n\n Proof. induction l; simpl; intros; lia. Qed.\n\n Lemma tail_in : forall (x: A) l, In x (tail l) -> In x l.\n\n Proof. intros. destruct l; auto with datatypes. Qed.\n\n Lemma tail_cons_tail : forall (l1 l2: list A),\n l1 <> nil -> tail l1 ++ l2 = tail (l1 ++ l2).\n\n Proof. destruct l1. tauto. auto. Qed.\n\n Lemma length_tail_minus : forall (l : list A), length (tail l) = length l - 1.\n\n Proof. destruct l; simpl; lia. Qed.\n\n Lemma list_decompose_head : forall (l : list A) el (lne: l <> nil),\n head l = Some el -> l = el :: tail l.\n\n Proof. intros. destruct l. discr. inversion H. rewrite <- H1; trivial. Qed.\n\n Lemma in_head_tail : forall a (l : list A),\n In a l -> Some a = head l \\/ In a (tail l).\n\n Proof.\n induction l; intros; inversion H.\n left; simpl; rewrite H0; trivial.\n right; trivial.\n Qed.\n\n Lemma head_notNil : forall (l : list A) (lne : l <> nil),\n {a : A | head l = Some a}.\n\n Proof. destruct l. tauto. exists a; auto. Defined.\n\n Lemma head_of_notNil : forall (l : list A) a (lne: l <> nil),\n head l = Some a -> proj1_sig (head_notNil lne) = a.\n\n Proof. intros. destruct l; try discr. simpl; inversion H; trivial. Qed.\n\nEnd head_tail.\n\n#[export] Hint Resolve tail_in tail_cons_tail head_app : datatypes.\n#[export] Hint Rewrite head_app length_app : datatypes.\n\n(***********************************************************************)\n(** Iteration of [tail]. *)\n\nSection tail_nth.\n\n Variable A : Type.\n\n Fixpoint tail_nth (l : list A) (n : nat) : option (list A) :=\n match l, n with\n | _, 0 => Some l\n | a :: l', S n' => tail_nth l' n'\n | _, _ => None\n end.\n\nEnd tail_nth.\n\n(****************************************************************************)\n(** Function selecting the elements that satisfy some predicate. *)\n\nSection select.\n\n Context {A: Type} {f : A->Prop}.\n\n Variable (f_dec : forall x, {f x}+{~f x}).\n\n Fixpoint select (l : list A) :=\n match l with\n | nil => nil\n | cons a l' =>\n match f_dec a with\n | left _ => a :: select l'\n | right _ => select l'\n end\n end.\n\n Lemma incl_select : forall l, select l [= l.\n\n Proof.\n induction l; simpl. fo. destruct (f_dec a).\n apply cons_incl. refl. hyp. apply incl_tl. hyp.\n Qed.\n\n Lemma select_correct : forall l x, In x (select l) -> In x l /\\ f x.\n\n Proof.\n induction l; intro x; simpl. fo.\n destruct (f_dec a). intro. split. unfold In in H. destruct H. fo. replace ((fix In (a : A) (l : list A) {struct l} : Prop := match l with\n | nil => False\n | b :: m => b = a \\/ In a m\n end) x (select l)) with (In x (select l)) in H.\n apply IHl in H. right. destruct H. auto. auto.\n destruct (f_dec a).\n unfold In in H. destruct H. rewrite <- H. trivial. replace ((fix In (a : A) (l : list A) {struct l} : Prop := match l with\n | nil => False\n | b :: m => b = a \\/ In a m\n end) x (select l)) with (In x (select l)) in H. \n apply IHl in H. destruct H. trivial. auto. contradict n. trivial.\n intro. apply IHl in H. split. destruct H. right. trivial.\n destruct H. trivial.\n Qed.\n\n Lemma select_complete : forall l x, In x l -> f x -> In x (select l).\n\n Proof.\n induction l; intro x; simpl. intros. trivial.\n intros [h|h]; destruct (f_dec a); subst. intros. unfold In. left. trivial. \n intros. contradict n. trivial. \n intros. unfold In. right. apply IHl. trivial. trivial. \n apply IHl. trivial.\n Qed.\n\nEnd select.\n\n(***********************************************************************)\n(** Select the elements of a list wrt a boolean function. *)\n\nSection filter.\n\n Variables (A : Type) (f : A -> bool).\n\n Lemma filter_app : forall l m, filter f (l ++ m) = filter f l ++ filter f m.\n\n Proof.\n induction l; simpl; intros. refl. rewrite IHl. destruct (f a); refl.\n Qed.\n\n Lemma filter_incl : forall l, filter f l [= l.\n\n Proof.\n induction l; simpl; intros. refl. case (f a); rewrite IHl.\n refl. apply incl_tl. refl.\n Qed.\n\n Variable eq_dec : forall x y : A, {x=y}+{~x=y}.\n\n Lemma notIn_filter : forall x l,\n ~In x (filter f l) <-> ~In x l \\/ (In x l /\\ f x = false).\n\n Proof.\n intros. rewrite filter_In. intuition. case (In_dec eq_dec x l); intro.\n right. intuition. revert H. case (f x). cong. refl. auto.\n rewrite H2 in H3. discr.\n Qed.\n\nEnd filter.\n\nSection filter_opt.\n\n Variables (A B : Type) (f : A -> option B).\n\n Fixpoint filter_opt (l : list A) : list B :=\n match l with\n | nil => nil\n | cons a m =>\n match f a with\n | Some b => cons b (filter_opt m)\n | _ => filter_opt m\n end\n end.\n\nEnd filter_opt.\n\n(***********************************************************************)\n(** Boolean function testing membership. *)\n\nSection Inb.\n\n Variables (A : Type) (eq_dec : forall x y : A, {x=y}+{~x=y}).\n\n Fixpoint Inb (x : A) (l : list A) : bool :=\n match l with\n | nil => false\n | cons y l' =>\n match eq_dec x y with\n\t | left _ => true\n\t | _ => Inb x l'\n end\n end.\n \n Lemma Inb_true : forall x l, Inb x l = true -> In x l.\n\n Proof. induction l; simpl. intro. discr. case (eq_dec x a); auto. Qed.\n\n Lemma Inb_false : forall x l, Inb x l = false -> In x l -> False.\n\n Proof.\n induction l; simpl. intros. contr. case (eq_dec x a).\n intros. discr. intros. destruct H0; auto.\n Qed.\n\n Lemma Inb_intro : forall x l, In x l -> Inb x l = true.\n\n Proof.\n induction l; simpl; intros. contr. case (eq_dec x a). auto.\n destruct H. intro. absurd (x = a); auto. auto.\n Qed.\n\n Lemma Inb_elim : forall x l, ~In x l -> Inb x l = false.\n\n Proof.\n induction l; simpl; intros. refl. case (eq_dec x a). intro. subst x.\n intuition. intuition.\n Qed.\n\n Lemma Inb_correct : forall x l, In x l <-> Inb x l = true.\n\n Proof.\n intuition. apply Inb_intro. hyp. apply Inb_true. hyp.\n Qed.\n\n Lemma Inb_incl : forall x l l', l [= l' -> Inb x l = true -> Inb x l' = true.\n\n Proof.\n intros. apply Inb_intro. apply H. apply Inb_true. hyp.\n Qed.\n\n Lemma Inb_equiv : forall x l l', lequiv l l' -> Inb x l = Inb x l'.\n\n Proof.\n intros. destruct H.\n case_eq (Inb x l'); intros; case_eq (Inb x l); intros; try refl.\n ded (Inb_incl _ H0 H1). rewrite H2 in H3. discr.\n ded (Inb_incl _ H H2). rewrite H1 in H3. discr.\n Qed.\n\n Definition Inclb (l1 l2 : list A) := forallb (fun x => Inb x l2) l1.\n\n Lemma Inclb_ok : forall l1 l2, Inclb l1 l2 = true <-> l1 [= l2.\n\n Proof.\n intros. induction l2. unfold Inclb. simpl. case l1. simpl; split; auto.\n intro. refl.\n intros. simpl; split; intro. discr.\n rewrite incl_nil_elim in H. discr.\n split; unfold Inclb; simpl; rewrite forallb_forall; intro.\n intros x Hx. gen (H _ Hx). case (eq_dec x a); intros.\n rewrite e; apply in_eq. apply in_cons. apply Inb_true; auto.\n intros. case (eq_dec x a); auto; intros.\n destruct (in_inv (H _ H0)); auto. apply Inb_intro; auto.\n Qed.\n\nEnd Inb.\n\nLtac inbtac :=\n match goal with\n | _ : In ?x ?l |- _ =>\n let H0 := fresh \"H\" in\n\t(assert (H0 : Inb x l = true); apply Inb_intro; hyp; rewrite H0)\n end.\n\n(***********************************************************************)\n(** Remove an element from a list. *)\n\nSection remove.\n\n Variables (A : Type) (eq_dec : forall x y : A, {x=y}+{~x=y}).\n\n Fixpoint remove (y : A) (l : list A) : list A :=\n match l with\n | nil => nil\n | cons x l' =>\n match eq_dec x y with\n\t | left _ => remove y l'\n\t | right _ => cons x (remove y l')\n end\n end.\n\n Lemma length_remove : forall (x : A) l, length (remove x l) <= length l.\n\n Proof.\n induction l; simpl; intros. apply Nat.le_0_l. destruct (eq_dec a x).\n apply Nat.le_trans with (length l). apply IHl. apply Nat.le_succ_diag_r. simpl.\n apply le_n_S. apply IHl.\n Qed.\n\n Lemma In_length_remove : forall (x : A) l,\n In x l -> length (remove x l) < length l.\n\n Proof.\n induction l; simpl; intros. contr. destruct (eq_dec a x).\n apply Nat.lt_succ_r.\n apply length_remove. destruct H. rewrite H in n. tauto. simpl. apply Nat.lt_succ_r.\n apply IHl. hyp.\n Qed.\n\n Lemma In_remove : forall (x y : A) l, x <> y -> In y l -> In y (remove x l).\n\n Proof.\n induction l; simpl; intros. hyp. \n destruct (eq_dec a x); destruct H0. rewrite e in H0. tauto.\n tauto. rewrite H0. simpl. tauto. simpl. tauto.\n Qed.\n\n Lemma incl_remove : forall (x : A) l m, ~In x l -> l [= m -> l [= remove x m.\n\n Proof.\n induction l; simpl; intros. apply incl_nil. assert (~a=x /\\ ~In x l). tauto.\n unfold incl. intros. simpl in H2. destruct H2. subst a0.\n apply In_remove. auto. unfold incl in H0. apply H0. simpl. auto.\n apply IHl. auto. apply incl_cons_l_incl with (x := a). exact H0. exact H2.\n Qed.\n\n Lemma incl_remove2 (x : A) : forall l, remove x l [= l.\n\n Proof.\n induction l; simpl. refl. destruct (eq_dec a x).\n apply incl_tl. hyp. apply cons_incl. refl. hyp.\n Qed.\n\n Lemma notin_remove : forall x l, In x (remove x l) -> False.\n\n Proof.\n induction l; simpl. auto. destruct (eq_dec a x). auto. simpl. tauto.\n Qed.\n\n Lemma remove_In : forall a x l, In a (remove x l) -> In a l.\n\n Proof.\n induction l;intros. simpl in *. auto.\n simpl in H. destruct (eq_dec a0 x).\n subst; simpl; right; auto.\n simpl in *; tauto.\n Qed.\n\n Lemma remove_eq : forall a x l, In a (remove x l) <-> a <> x /\\ In a l.\n\n Proof.\n intuition. subst. eapply notin_remove. apply H. eapply remove_In. apply H.\n apply In_remove; auto.\n Qed.\n\n Lemma remove_notin (x : A) : forall l, ~In x l -> remove x l = l.\n\n Proof.\n induction l; intro nxl; simpl. refl. destruct (eq_dec a x).\n subst. fo. f_equal. fo.\n Qed.\n\nEnd remove.\n\n(***********************************************************************)\n(** Removes a list of elements from a list. *)\n\nSection removes.\n\n Variable (A : Type) (eqdec : forall x y : A, {x=y}+{x<>y}).\n\n Notation In_dec := (In_dec eqdec).\n\n Fixpoint removes (l m : list A) : list A :=\n match m with\n | nil => nil\n | x :: m' =>\n match In_dec x l with\n | left _ => removes l m'\n | right _ => x :: removes l m'\n end\n end.\n\n Lemma incl_removes : forall l m, removes l m [= m.\n\n Proof.\n unfold incl. induction m; simpl. contr.\n case (In_dec a l). intros. right. apply IHm. hyp.\n simpl. intuition.\n Qed.\n\n Lemma incl_removes_app : forall l m, m [= removes l m ++ l.\n\n Proof.\n unfold incl. induction m; simpl. contr. intros. destruct H.\n subst a0. case (In_dec a l); intro. apply in_appr. hyp. simpl. auto.\n case (In_dec a l); intro. apply IHm. hyp. simpl.\n case (eqdec a a0); intro. subst a0. auto. right. apply IHm. hyp.\n Qed.\n\n Lemma In_removes : forall x l m, In x (removes l m) <-> In x m /\\ ~In x l.\n\n Proof.\n induction m; simpl; intros. tauto. case (In_dec a l); intro. rewrite IHm.\n split; intros. split; destruct H. right. trivial. trivial. destruct H. split. destruct H.\n contradict H0. rewrite <- H. trivial. trivial. trivial.\n \n split; intros. split. unfold In in H. destruct H. left. trivial.\n replace ((fix In (a : A) (l : list A) {struct l} : Prop := match l with\n | nil => False\n | b :: m => b = a \\/ In a m\n end) x (removes l m)) with (In x (removes l m)) in H. rewrite IHm in H.\n right. destruct H. trivial. auto.\n unfold In in H. destruct H. \n rewrite <- H. trivial. replace ((fix In (a : A) (l : list A) {struct l} : Prop := match l with\n | nil => False\n | b :: m => b = a \\/ In a m\n end) x (removes l m)) with (In x (removes l m)) in H. rewrite IHm in H.\n destruct H. trivial. auto.\n\n unfold In. destruct H. destruct H. left. trivial.\n right. replace ((fix In (a : A) (l : list A) {struct l} : Prop := match l with\n | nil => False\n | b :: m => b = a \\/ In a m\n end) x (removes l m)) with (In x (removes l m)).\n rewrite IHm. split; trivial. auto.\n Qed.\n\nEnd removes.\n\n(***********************************************************************)\n(** Properties of [map]. *)\n\nSection map.\n\n Variable (A B : Type) (f : A->B).\n\n Lemma map_app : forall l1 l2, map f (l1 ++ l2) = (map f l1) ++ map f l2.\n\n Proof.\n induction l1; simpl; intros. refl. rewrite IHl1. refl.\n Qed.\n\n Lemma in_map_elim : forall x l, In x (map f l) -> exists y, In y l /\\ x = f y.\n\n Proof.\n induction l; simpl; intros. contr. destruct H.\n exists a. auto. ded (IHl H). do 2 destruct H0. exists x0. auto.\n Qed.\n\n Lemma map_eq : forall (g : A->B) l,\n (forall x, In x l -> f x = g x) -> map f l = map g l.\n\n Proof.\n induction l; simpl; intros. refl. apply cons_eq. ded (H a). intuition.\n apply IHl. intro. ded (H x). intuition.\n Qed.\n\nEnd map.\n\nArguments in_map_elim [A B f x l] _.\n\nLemma map_eq_id : forall A (f:A->A) l,\n (forall x, In x l -> f x = x) -> map f l = l.\n\nProof.\ninduction l; simpl; intros. refl. apply cons_eq. ded (H a). intuition.\napply IHl. intro. ded (H x). intuition.\nQed.\n\n(***********************************************************************)\n(** Properties of [flat_map]. *)\n\nSection flat_map.\n\n Variables (A B : Type) (f : A -> list B).\n\n Lemma In_flat_map_intro : forall x l y,\n In y l -> In x (f y) -> In x (flat_map f l).\n\n Proof.\n intros. apply (proj2 (@in_flat_map _ _ f l x)).\n exists y. auto.\n Qed.\n\n Lemma In_flat_map_elim : forall l y, \n In y (flat_map f l) -> exists x, In x l /\\ In y (f x).\n\n Proof.\n intros. exact (proj1 (@in_flat_map _ _ _ _ _) H).\n Qed.\n\n Lemma flat_map_app : forall l m,\n flat_map f (l ++ m) = flat_map f l ++ flat_map f m.\n\n Proof. induction l; simpl; intros. refl. rewrite IHl, app_ass. refl. Qed.\n\nEnd flat_map.\n\n(***********************************************************************)\n(** Concatenation of a list of lists. *)\n\nSection flat.\n\n Variable A : Type.\n\n Fixpoint flat (l : list (list A)) : list A :=\n match l with\n | nil => nil\n | cons x l' => x ++ flat l'\n end.\n\n Lemma In_incl_flat : forall x l, In x l -> x [= flat l.\n\n Proof.\n induction l; simpl; intros. contr. intuition. subst. apply incl_appl. refl.\n Qed.\n\n Lemma incl_flat_In : forall x c cs l,\n In x c -> In c cs -> flat cs [= l -> In x l.\n\n Proof. intros. apply H1. apply (In_incl_flat _ _ H0). hyp. Qed.\n\nEnd flat.\n\nArguments In_incl_flat [A x l] _ _ _.\n\n(****************************************************************************)\n(** Position of an element in a list (the result is meaningful only if\nthe element occurs in the list). *)\n\nSection pos.\n\n Variables (A : Type) (eq_dec : forall x y : A, {x=y}+{~x=y}).\n\n Section def.\n\n Variable x : A.\n\n Fixpoint pos l :=\n match l with\n | nil => 0\n | a :: l' => if eq_dec a x then 0 else S (pos l')\n end.\n\n Lemma nth_pos d : forall l, In x l -> nth (pos l) l d = x.\n\n Proof.\n induction l; intro h; simpl. fo. destruct (eq_dec a x). hyp.\n apply IHl. fo.\n Qed.\n\n Lemma pos_lt_length : forall l, In x l -> pos l < length l.\n\n Proof.\n induction l; intro h; simpl. fo. destruct (eq_dec a x). lia.\n apply -> Nat.succ_lt_mono. fo.\n Qed.\n\n End def.\n\n Lemma inj_pos x y : forall l, In x l -> pos x l = pos y l -> x = y.\n\n Proof.\n induction l; intro h; simpl. contr.\n destruct (eq_dec a x); destruct (eq_dec a y); subst; intro e.\n reflexivity. discr. discr. inversion e. fo.\n Qed.\n\nEnd pos.\n\nArguments pos_lt_length [A] _ [x l] _.\n\n(***********************************************************************)\n(** Element at a position (starting from 0) and its replacement. *)\n\nSection Element_At_List.\n \n Variable A : Type.\n \n Fixpoint element_at (l : list A) (p : nat) : option A := \n match l with \n | nil => None\n | h :: t =>\n\tmatch p with \n | 0 => Some h \n | S p' => element_at t p'\n end\n end.\n\n Notation \"l '[' p ']'\" := (element_at l p) (at level 50).\n\n Fixpoint replace_at (l : list A) (p : nat) (a : A) : list A :=\n match l with\n | nil => nil\n | h :: t =>\n\tmatch p with \n | 0 => a :: t\n | S p' => h :: (replace_at t p' a)\n end\n end.\n\n Notation \"l '[' p ':=' a ']'\" := (replace_at l p a) (at level 50).\n\n Lemma element_at_exists : forall l p,\n p < length l <-> ex (fun a => l[p] = Some a).\n\n Proof.\n intro l; induction l as [ | h t IHl].\n simpl; intro p; split; intro H; [inversion H | inversion H as [x Hx]].\n inversion Hx.\n simpl; intro p; split.\n intro Hp; destruct p as [ | p].\n exists h; trivial.\n assert (Hp' : p < length t).\n gen Hp; auto with arith.\n elim (IHl p); intros H1 H2.\n elim (H1 Hp'); intros a Ha; exists a; trivial.\n destruct p as [ | p]; intro H.\n auto with arith.\n elim (IHl p); intros H1 H2.\n gen (H2 H); auto with arith.\n Qed.\n\n Lemma element_at_replaced : forall l p a, p < length l -> l[p:=a][p] = Some a.\n\n Proof.\n intro l; induction l as [ | h t IHl]; simpl; intros p a Hlength.\n inversion Hlength.\n destruct p as [ | p]; simpl.\n trivial.\n apply IHl; gen Hlength; auto with arith.\n Qed.\n\n Lemma element_at_not_replaced : forall l p q a, p <> q -> l[p] = l[q:=a][p].\n\n Proof.\n intro l; induction l as [ | h t IHl]; intros p q a p_neq_q; simpl.\n trivial.\n destruct p as [ | p'].\n destruct q as [ | q']; simpl.\n elim p_neq_q; trivial.\n trivial.\n destruct q as [ | q']; simpl.\n trivial.\n apply IHl.\n intro H; apply p_neq_q; subst; trivial.\n Qed.\n\n Lemma in_exists_element_at :\n forall l a, In a l -> ex (fun p => l[p] = Some a).\n\n Proof.\n intro l; induction l as [ | h t IHl]; intros a a_in_l.\n inversion a_in_l.\n elim a_in_l; clear a_in_l; intro a_in_l.\n exists 0; subst; trivial.\n elim (IHl a a_in_l); intros p Hp.\n exists (S p); simpl; trivial.\n Qed.\n\n Lemma exists_element_at_in :\n forall l a, ex (fun p => l[p] = Some a) -> In a l.\n\n Proof.\n intro l; induction l as [ | h t IHl]; intros a Hex; \n elim Hex; clear Hex; intros p Hp.\n inversion Hp.\n destruct p as [ | p]; inversion Hp.\n left; trivial.\n right; apply IHl; exists p; trivial.\n Qed.\n\n Lemma element_at_in : forall (x:A) l n, l[n] = Some x -> In x l.\n\n Proof.\n induction l; simpl; intros. discr. destruct n.\n inversion H. subst. auto. ded (IHl _ H). auto.\n Qed.\n\n Lemma element_at_in2 :\n forall (x:A) l n, l[n] = Some x -> In x l /\\ n < length l.\n\n Proof.\n induction l; intros; simpl in H; try discr. destruct n.\n inversion H; subst; simpl; auto with *.\n ded (IHl n H). intuition; simpl; lia.\n Qed.\n\n Lemma element_at_app_r : forall l l' p, \n p >= length l -> (l ++ l') [p] = l' [p - length l].\n\n Proof.\n induction l. intuition.\n intros. destruct p.\n inversion H.\n simpl. apply IHl. simpl in H. auto with arith.\n Qed.\n\n Lemma replace_at_app_r : forall l l' p a,\n p >= length l -> (l ++ l') [p := a] = l ++ l' [p - length l := a].\n\n Proof.\n induction l; intros.\n simpl. rewrite Nat.sub_0_r. refl.\n destruct p. inversion H.\n simpl. rewrite IHl. refl. intuition.\n Qed.\n\nEnd Element_At_List.\n\nArguments element_at_in [A x l n] _.\nArguments element_at_in2 [A x l n] _.\nArguments in_exists_element_at [A l a] _.\nArguments element_at_exists {A l p}.\n\nNotation \"l '[' p ']'\" := (element_at l p) (at level 50) : list_scope.\nNotation \"l '[' p ':=' a ']'\" := (replace_at l p a) (at level 50) : list_scope.\n\n(***********************************************************************)\n(** Precidate saying that an element [a] in a list has been replaced\nby an element [a'] such that [r a a'] where [r] is a relation. *)\n\nSection one_less.\n\n Variables (A : Type) (r : relation A).\n \n Inductive one_less : relation (list A) := \n | one_less_cons : forall (l l' : list A) (p : nat) (a a' : A), \n r a a' -> l[p] = Some a -> l' = l[p:=a'] -> one_less l l'.\n \n Lemma one_less_length : forall l l', one_less l l' -> length l = length l'.\n\n Proof.\n intro l; induction l as [ | h t IHl]; intros l' Hr.\n inversion Hr; subst.\n simpl; trivial.\n inversion Hr; subst; simpl.\n destruct p as [ | p].\n simpl; trivial.\n simpl; rewrite IHl with (t[p:=a']); trivial.\n apply (@one_less_cons t (t[p:=a']) p a a'); trivial.\n Qed.\n\nEnd one_less.\n\nArguments one_less [A] _ _ _.\nArguments one_less_cons [A] _ _ _ _ _ _ _ _ _.\n\n(***********************************************************************)\n(** Properties of [rev]. *)\n\nSection reverse.\n\n Variable A : Type.\n\n Lemma in_rev : forall (x : A) l, In x l -> In x (rev l).\n\n Proof.\n induction l; simpl; intros. hyp. apply in_or_app. simpl. tauto.\n Qed.\n\n Lemma incl_rev : forall l : list A, l [= rev l.\n\n Proof.\n unfold incl. intros. apply in_rev. hyp. \n Qed.\n\n Lemma rev_incl : forall l : list A, rev l [= l. \n\n Proof.\n intros. pose (incl_rev (rev l)). rewrite (rev_involutive l) in i. hyp.\n Qed.\n\n Lemma incl_rev_intro : forall l l' : list A, rev l [= rev l' -> l [= l'.\n\n Proof.\n intros. trans (rev l). apply incl_rev. trans (rev l'). hyp. apply rev_incl.\n Qed.\n\nEnd reverse.\n\n(***********************************************************************)\n(** Tail-recursive reserve function. *)\n\nSection reverse_tail_recursive.\n\n Variable A : Type.\n\n Fixpoint rev_append (l' l : list A) : list A :=\n match l with\n | nil => l'\n | a :: l => rev_append (a :: l') l\n end.\n\n Notation rev' := (rev_append nil).\n\n Lemma rev_append_rev : forall l l', rev_append l' l = rev l ++ l'.\n\n Proof. induction l; simpl; auto; intros. rewrite <- ass_app; fo. Qed.\n\n Lemma rev_append_app : forall l l' acc : list A,\n rev_append acc (l ++ l') = rev_append (rev_append acc l) l'.\n\n Proof. induction l; simpl; intros. refl. rewrite IHl. refl. Qed.\n\n Lemma rev'_app : forall l l' : list A, rev' (l ++ l') = rev' l' ++ rev' l.\n\n Proof.\n intros. rewrite rev_append_app, !rev_append_rev, <- !app_nil_end. refl.\n Qed.\n\n Lemma rev'_rev : forall l : list A, rev' l = rev l.\n\n Proof. intro. rewrite rev_append_rev, <- app_nil_end. refl. Qed.\n\n Lemma rev'_rev' : forall l : list A, rev' (rev' l) = l.\n\n Proof. intro. rewrite !rev'_rev. apply rev_involutive. Qed.\n\n Lemma rev'_cons : forall a (l : list A), rev' (a::l) = rev' l ++ (a::nil).\n\n Proof.\n intros. change (rev' ((a::nil) ++ l) = rev' l ++ (a::nil)).\n rewrite rev'_app. refl.\n Qed.\n\nEnd reverse_tail_recursive.\n\nNotation rev' := (rev_append nil).\n\n(***********************************************************************)\n(** Given a list [l] and a position [n] in [l], return the pair of\nlists [l1] and [l2] such that [l = l1 ++ l2]. *)\n\nSection split.\n\n Variable A : Type.\n\n Fixpoint split_aux (acc l : list A) (n : nat) : option (list A * list A) :=\n match l, n with\n | _, 0 => Some (rev' acc, l)\n | a :: l', S n' => split_aux (a::acc) l' n'\n | _, _ => None\n end.\n\n Lemma split_aux_correct : forall l n l1 l2 acc,\n split_aux acc l n = Some (l1, l2) -> rev' acc ++ l = l1 ++ l2.\n\n Proof.\n induction l; destruct n; simpl; intros. inversion H. refl. discr.\n inversion H. refl. ded (IHl _ _ _ _ H). rewrite rev'_cons in H0.\n rewrite app_ass in H0. hyp.\n Qed.\n\n Arguments split_aux_correct [l n l1 l2] _ _.\n\n Notation split := (split_aux nil).\n\n Lemma split_correct : forall l n l1 l2,\n split l n = Some (l1, l2) -> l = l1 ++ l2.\n\n Proof.\n intros. change (rev' nil ++ l = l1 ++ l2). apply (split_aux_correct _ H).\n Qed.\n\nEnd split.\n\nNotation split := (split_aux nil).\n\nArguments split_correct [A l n l1 l2] _.\n\n(***********************************************************************)\n(** Last element of a list. *)\n\nSection last.\n\n Variable A : Type.\n\n Lemma last_nth : forall (d : A) l, last l d = nth (length l - 1) l d.\n\n Proof.\n induction l; simpl; intros. refl. rewrite IHl.\n elim l; simpl; intros. refl. destruct l0; simpl. refl. refl.\n Qed.\n\n Lemma last_default : forall (d1 : A) d2 l, l <> nil -> last l d1 = last l d2.\n\n Proof.\n induction l; simpl; intros. cong. destruct l. refl. apply IHl. discr.\n Qed.\n\nEnd last.\n\nArguments last_intro [A l] _.\n\n(***********************************************************************)\n(** Properties of [partition]. *)\n\nSection partition.\n\n Variables (A : Type) (f : A -> bool) (a : A) (l : list A).\n\n Lemma partition_complete : let p := partition f l in\n In a l -> In a (fst p) \\/ In a (snd p).\n\n Proof.\n induction l. auto.\n simpl. intro. destruct (partition f l0). destruct H.\n destruct (f a0); simpl; auto.\n destruct (f a0); simpl in *; destruct IHl0; auto.\n Qed.\n\n Lemma partition_inleft : In a (fst (partition f l)) -> In a l.\n\n Proof.\n induction l. auto.\n simpl. intro. destruct (partition f l0). destruct (f a0).\n destruct H; auto.\n right. apply IHl0. auto.\n Qed.\n\n Lemma partition_inright : In a (snd (partition f l)) -> In a l.\n\n Proof.\n induction l. auto.\n simpl. intro. destruct (partition f l0). destruct (f a0).\n right. apply IHl0. auto.\n destruct H; auto.\n Qed.\n\n Lemma partition_left : In a (fst (partition f l)) -> f a = true.\n\n Proof.\n induction l; simpl. auto.\n destruct (partition f l0). destruct (bool_dec (f a0) true).\n rewrite e. intro. destruct H.\n subst a0. hyp.\n apply IHl0. hyp.\n rewrite (not_true_is_false (f a0)); hyp.\n Qed.\n\n Lemma partition_right : In a (snd (partition f l)) -> f a = false.\n\n Proof.\n induction l; simpl. intuition.\n destruct (partition f l0). destruct (bool_dec (f a0) true).\n rewrite e. apply IHl0.\n rewrite (not_true_is_false (f a0)). intro. destruct H.\n subst a0. destruct (f a); intuition.\n apply IHl0. hyp. hyp.\n Qed.\n\nEnd partition.\n\nSection partition_by_prop.\n\n Variables (A : Type) (P : A -> Prop) (P_dec : forall x, {P x}+{~P x}).\n\n Definition partition_by_prop a :=\n match P_dec a with\n | left _ => true\n | right _ => false\n end.\n\n Lemma partition_by_prop_true : forall a, partition_by_prop a = true -> P a.\n\n Proof.\n intros. unfold partition_by_prop in H. \n destruct (P_dec a). hyp. discr.\n Qed.\n\nEnd partition_by_prop.\n\nSection partition_by_rel.\n\n Variables (A : Type) (R : relation A) (R_dec : rel_dec R).\n\n Definition partition_by_rel p := \n if R_dec (fst p) (snd p) then true else false.\n\n Lemma partition_by_rel_true : forall a b,\n partition_by_rel (a, b) = true -> R a b.\n\n Proof.\n intros. unfold partition_by_rel in H. simpl in H.\n destruct (R_dec a b). hyp. discr.\n Qed.\n\nEnd partition_by_rel.\n\n(***********************************************************************)\n(** Select the elements of a list according to a list of booleans. *)\n\nSection ListFilter.\n\n Variable A : Type.\n\n Fixpoint listfilter (L : list A) l :=\n match L with\n | nil => nil\n | a :: Q =>\n match l with \n | nil => nil\n | true :: q => a :: listfilter Q q\n | false :: q => listfilter Q q\n end\n end.\n\n Lemma listfilter_in : forall L l i x,\n L[i]=Some x -> l[i]=Some true -> In x (listfilter L l) .\n\n Proof.\n induction L.\n intros. simpl in *. discr.\n\n intros.\n destruct i; simpl in H.\n simpl.\n inversion H; subst.\n destruct l; simpl in *. discr.\n inversion H0; subst. simpl; left; auto.\n\n destruct l; auto. simpl in H0; discr.\n inversion H0.\n simpl.\n destruct b.\n right. eapply IHL; eauto.\n eapply IHL; eauto.\n Qed.\n\nEnd ListFilter.\n\n(****************************************************************************)\n(** Properties of [nth] and [nth_error]. *)\n\nSection ListsNth.\n\n Variable A: Type.\n\n Lemma In_nth : forall A d (x : A) l,\n In x l -> exists i, i < length l /\\ nth i l d = x.\n\n Proof.\n induction l; simpl; intros. contr. destruct H.\n subst. exists 0. intuition.\n destruct (IHl H) as [i hi]. exists (S i). intuition.\n Qed.\n\n Lemma nth_error_In : forall (l : list A) i, \n {a : A | nth_error l i = Some a} + {nth_error l i = None}.\n\n Proof.\n induction l.\n right; compute; case i; trivial.\n intro i.\n case i.\n left; exists a; trivial.\n intro n.\n destruct (IHl n) as [[a' a'nth] | nth_none].\n left; exists a'; trivial.\n right; trivial.\n Qed.\n\n Lemma nth_some_in :\n forall (l : list A) i a, nth_error l i = Some a -> In a l.\n\n Proof.\n induction l; intros.\n destruct i; simpl in *; discr.\n destruct i; simpl in *.\n left; compute in *; congruence.\n right; eapply IHl; eauto.\n Qed.\n\n Lemma list_In_nth : forall (l : list A) a,\n In a l -> exists p: nat, nth_error l p = Some a.\n\n Proof.\n induction l.\n contr.\n intros; destruct H.\n exists 0.\n rewrite H; trivial.\n destruct (IHl a0 H).\n exists (S x); trivial.\n Qed.\n\n Lemma nth_app_left : forall (l m: list A) i,\n i < length l -> nth_error (l ++ m) i = nth_error l i.\n\n Proof.\n induction l; simpl; intros m i i_l.\n lia.\n destruct i; simpl.\n trivial.\n apply (IHl m i).\n auto with arith.\n Qed.\n\n Lemma nth_app_right : forall (l m: list A) i, i >= length l ->\n nth_error (l ++ m) i = nth_error m (i - length l).\n\n Proof.\n induction l; simpl; intros m i i_l.\n auto with arith.\n destruct i; simpl.\n lia.\n apply IHl.\n auto with arith.\n Qed.\n\n Lemma nth_app : forall (l m: list A) a i, nth_error (l ++ m) i = Some a ->\n (nth_error l i = Some a /\\ i < length l) \\/ \n (nth_error m (i - length l) = Some a /\\ i >= length l).\n\n Proof.\n intros.\n destruct (le_lt_dec (length l) i).\n right; split; trivial.\n rewrite (nth_app_right l m l0) in H; trivial.\n left; split; trivial.\n rewrite (nth_app_left l m l0) in H; trivial.\n Qed.\n\n Lemma nth_beyond : forall (l : list A) i,\n i >= length l -> nth_error l i = None.\n\n Proof.\n induction l; simpl; intro i.\n destruct i; trivial.\n destruct i; simpl.\n intros.\n lia.\n intro.\n rewrite (IHl i); trivial.\n auto with arith.\n Qed.\n\n Lemma nth_beyond_idx : forall (l : list A) i,\n nth_error l i = None -> i >= length l.\n\n Proof.\n induction l; simpl; intro i.\n auto with arith.\n destruct i; simpl.\n intros.\n discr.\n intro.\n assert (i >= length l).\n apply (IHl i); trivial.\n auto with arith.\n Qed.\n\n Lemma nth_in : forall (l : list A) i,\n nth_error l i <> None <-> i < length l.\n\n Proof.\n induction l; simpl; intro i.\n split.\n destruct i; intro; exfalso; auto.\n intro; lia.\n destruct i; simpl.\n split; intro.\n auto with arith.\n discr.\n split; intro.\n assert (i < length l).\n apply (proj1 (IHl i)); trivial.\n auto with arith.\n apply (proj2 (IHl i)); auto with arith.\n Qed.\n\n Lemma nth_some : forall (l : list A) n a,\n nth_error l n = Some a -> n < length l.\n\n Proof. intros. apply (proj1 (nth_in l n)). rewrite H; discr. Qed.\n\n Lemma nth_map_none : forall (l : list A) i (f: A -> A),\n nth_error l i = None -> nth_error (map f l) i = None.\n\n Proof. \n induction l. trivial. intros i f; destruct i; simpl.\n intro; discr. apply IHl.\n Qed.\n\n Lemma nth_map_none_rev : forall (l : list A) i (f: A -> A),\n nth_error (map f l) i = None -> nth_error l i = None.\n\n Proof.\n induction l.\n trivial.\n intros i f; destruct i; simpl.\n intro; discr.\n apply IHl.\n Qed.\n\n Lemma nth_map_some : forall (l : list A) i (f: A -> A) a,\n nth_error l i = Some a -> nth_error (map f l) i = Some (f a).\n\n Proof.\n induction l.\n destruct i; intros; discr.\n intros i f a'.\n destruct i; simpl.\n intro aa'; inversion aa'; trivial.\n apply IHl.\n Qed.\n\n Lemma nth_map_some_rev : forall (l : list A) i (f: A -> A) a,\n nth_error (map f l) i = Some a ->\n exists a', nth_error l i = Some a' /\\ f a' = a.\n\n Proof.\n induction l.\n destruct i; intros; discr.\n intros i f a'.\n destruct i; simpl.\n intros aa'; inversion aa'; exists a; auto.\n apply IHl.\n Qed.\n\n Lemma nth_error_singleton_in : forall (a b: A) i,\n nth_error (a :: nil) i = Some b -> a = b /\\ i = 0.\n\n Proof.\n intros.\n destruct i.\n inversion H; auto.\n inversion H; destruct i; discr.\n Qed.\n\nEnd ListsNth.\n\nArguments In_nth [A] d [x l] _.\n\n(****************************************************************************)\n(** Total function returning the [i]th element of a list [ŀ]\nif [i < length l]. *)\n\nUnset Strict Implicit.\nSet Contextual Implicit.\n\nSection ith.\n\n Variable A : Type.\n\n Fixpoint ith (l : list A) : forall i, i < length l -> A :=\n match l as l return forall i, i < length l -> A with\n | nil => fun i H => False_rect A (Nat.nlt_0_r H)\n | cons x m => fun i =>\n match i return i < S (length m) -> A with\n\t | O => fun _ => x\n\t | S j => fun H => ith (Arith_prebase.lt_S_n_stt j (length m) H)\n end\n end.\n\nLemma ith_In : forall l i (h : i < length l), In (ith h) l.\n\n Proof.\n induction l; simpl; intros. lia. destruct i. auto. right. apply IHl.\n Qed.\n\n Lemma ith_eq : forall l i (hi : i < length l) j (hj : j < length l),\n i = j -> ith hi = ith hj.\n\n Proof. intros. subst j. rewrite (lt_unique hi hj). refl. Qed.\n\n Lemma ith_eq_app : forall m l i (hi : i < length (l++m))\n j (hj : j < length l), i = j -> ith hi = ith hj.\n\n Proof.\n induction l; simpl; intros. contradict hj; lia. subst j.\n destruct i. refl. apply IHl. refl.\n Qed.\n\nEnd ith.\n\nArguments ith_In [A l i] _.\n\n(****************************************************************************)\n(** Given a function [f:nat->A] and [j:nat], [values f j] returns the\nlist [f (j-1); ..; f 0] of the [j] first values of [f] starting from\n0 in reverse order. *)\n\nSection values.\n\n Variables (A : Type) (f : nat -> A).\n\n Fixpoint values j : list A :=\n match j with\n | 0 => nil\n | S k => f k :: values k\n end.\n\nEnd values.\n\n(****************************************************************************)\n(** Given a function [n:nat] and [f:forall i, i A], [pvalues n f]\nreturns the list [f 0; ..; f (n-1)] of the [n] first values of [f]\nstarting from 0. *)\n\nSection pvalues.\n\n Variable A : Type.\n\n Fixpoint pvalues n : (forall i, i < n -> A) -> list A :=\n match n as n return (forall i, i < n -> A) -> list A with\n | 0 => fun _ => nil\n | S k => fun f =>\n f 0 (Nat.lt_0_succ k) :: pvalues (fun i h => f (S i) (Arith_prebase.lt_n_S_stt i _ h))\n end.\n\n Lemma pvalues_eq : forall n (f g : forall i, i < n -> A),\n (forall i (hi : i < n), f i hi = g i hi) -> pvalues f = pvalues g.\n\n Proof.\n induction n; intros; simpl. refl. apply cons_eq. apply H. apply IHn.\n intros. apply H.\n Qed.\n\nEnd pvalues.\n\nSection pvalues_map.\n\n Variables (A B : Type) (f : A -> B).\n\n Definition f_ith (l : list A) i (hi : i < length l) := f (ith hi).\n\n Lemma pvalues_ith_eq_map : forall l, pvalues (@f_ith l) = map f l.\n\n Proof.\n induction l; intros; unfold f_ith; simpl. refl. apply tail_eq.\n rewrite <- IHl. apply pvalues_eq. intros. unfold f_ith. f_equal.\n apply ith_eq. refl.\n Qed.\n\nEnd pvalues_map.\n\n(***********************************************************************)\n(** First element satisfying some boolean function. *)\n\nSection first.\n\n Variable (A : Type) (f : A -> bool).\n\n Fixpoint first l :=\n match l with\n | nil => None\n | x :: l' => if f x then Some x else first l'\n end.\n\nEnd first.\n\n(***********************************************************************)\n(** Properties of [fold_left]. *)\n\n#[export] Instance transpose_inclusion A B :\n Proper (inclusion ==> eq ==> impl) (@transpose A B).\n\nProof. intros R R' RR' f f' ff' h x y z. subst f'. apply RR'. apply h. Qed.\n\n#[export] Instance transpose_same A B : Proper (same ==> eq ==> iff) (@transpose A B).\n\nProof.\n intros R R' [h1 h2] f f' ff'. subst f'.\n split; apply transpose_inclusion; auto.\nQed.\n\nSection fold_left.\n\n Variables (A : Type) (eqA : relation A) (B : Type) (eqB : relation B).\n\n Definition feq f f' :=\n forall a a', eqA a a' -> forall b b', eqB b b' -> eqA (f a b) (f' a' b').\n\n #[global] Instance fold_left_m_ext :\n Proper (feq ==> eqlistA eqB ==> eqA ==> eqA) (@fold_left A B).\n\n Proof.\n intros f f' ff' l l' ll' a a' aa'. revert l l' ll' a a' aa'.\n induction l; destruct l'; intros; simpl.\n hyp. inversion ll'. inversion ll'.\n inversion ll'. subst. apply IHl. hyp. apply ff'; hyp.\n Qed.\n\nEnd fold_left.\n\nSection fold_left_list.\n\n Variables (A B : Type) (f : list A -> B -> list A).\n\n Variable g : B -> list A.\n\n Variable hyp : forall l b, f l b = g b ++ l.\n\n Lemma fold_left_flat_map : forall bs l,\n fold_left f bs l = flat_map g (rev bs) ++ l.\n\n Proof.\n induction bs; simpl; intro. refl.\n rewrite IHbs, hyp, flat_map_app, app_ass. simpl.\n rewrite <- app_nil_end. refl.\n Qed.\n\n Lemma In_fold_left : forall a bs l,\n In a (fold_left f bs l) <-> (In a l \\/ exists b, In b bs /\\ In a (g b)).\n\n Proof.\n intros. rewrite fold_left_flat_map, in_app, in_flat_map.\n intuition. destruct H0. right. exists x. rewrite In_rev. hyp.\n destruct H0. left. exists x. rewrite <- In_rev. hyp.\n Qed.\n\nEnd fold_left_list.\n\nArguments fold_left_flat_map [A B f] _ _ _ _.\nArguments In_fold_left [A B f] _ _ _ _ _.\n\n(****************************************************************************)\n(** [lookup el default l] takes an association list of pairs of keys\nand values, and returns [v] such that [(el, v)] belongs to the list,\nor [default] if there is no element with key equal to [el]. *)\n\nSection lookup.\n\n Variable (A B : Type).\n Variable (eqA_dec : forall x y : A, {x = y} + {x <> y}).\n Variable (el : A). \n Variable (default : B).\n\n Fixpoint lookup (l : list (A * B)) : B :=\n match l with\n | nil => default\n | (el', v)::l' => \n if @eqA_dec el el' then\n v\n else\n lookup l'\n end.\n\n Variable P : B -> Prop.\n\n Lemma lookup_prop l : \n (forall x, In x l -> P (snd x)) -> P default -> P (lookup l).\n Proof with auto with datatypes.\n induction l; intros...\n simpl. destruct a. destruct (@eqA_dec el a).\n apply (H (a, b))...\n apply IHl...\n Qed.\n\nEnd lookup.\n\n(****************************************************************************)\n(** [lookup_dep] is equivalent to [lookup] above but works on lists of\ndependent pairs instead. *)\n\nSection lookup_dep.\n\n Variable (A : Type) (B : A -> Type).\n Variable (eqA_dec : forall x y : A, {x = y} + {x <> y}).\n Variable (el : A).\n Variable (default : forall a : A, B a).\n\n Program Fixpoint lookup_dep (l : list { el : A & B el}) : B el :=\n match l with\n | nil => @default el\n | x::l' => \n let (el', v) := x in\n if @eqA_dec el el' then\n v\n else\n lookup_dep l'\n end.\n\n Variable P : forall a : A, B a -> Prop.\n\n Lemma lookup_dep_prop (l : list {el : A & B el}) : \n (forall x, In x l -> P (projT2 x)) -> \n (forall a : A, P (@default a)) -> P (lookup_dep l).\n\n Proof with auto with datatypes.\n induction l; intros.\n apply H0.\n simpl. destruct a. destruct (@eqA_dec el x).\n\n unfold eq_rect, lookup_dep_obligation_1.\n set (w := eq_ind_r (fun el => x = el) eq_refl e).\n dependent inversion w.\n\n apply (H (existT b))...\n apply IHl...\n Qed.\n\nEnd lookup_dep.\n\n(****************************************************************************)\n(** Properties of [forallb]. *)\n\nSection forallb.\n\n Variables (A : Type) (P : A -> Prop)\n (f : A -> bool) (f_ok : forall x, f x = true <-> P x).\n\n Lemma forallb_false : forall l,\n forallb f l = false <-> exists x, In x l /\\ f x = false.\n\n Proof.\n induction l; simpl. intuition. destruct H. intuition.\n rewrite andb_eq_false, IHl. intuition.\n exists a. tauto. destruct H0. exists x. tauto.\n destruct H1. intuition. subst. tauto. right. exists x. tauto.\n Qed.\n\n Lemma forallb_neg : forall l,\n forallb f l = false <-> exists x, In x l /\\ ~P x.\n\n Proof.\n intro l. rewrite forallb_false. split; intro.\n do 2 destruct H. exists x. rewrite <- (ko (@f_ok)). tauto.\n do 2 destruct H. exists x. rewrite (ko (@f_ok)). tauto.\n Qed.\n\n Variables (As : list A) (As_ok : forall x, In x As).\n\n Lemma forallb_ok_fintype : forallb f As = true <-> forall x, P x.\n\n Proof.\n split; intro H.\n intro x. rewrite <- f_ok. rewrite forallb_forall in H. apply H. apply As_ok.\n rewrite forallb_forall. intros x hx. rewrite f_ok. apply H.\n Qed.\n\nEnd forallb.\n\n(****************************************************************************)\n(** [sub_list l k n] is the sublist of [l] of length [n] starting at\nposition [k]. *)\n\nSection sub_list.\n\n Variable A : Type.\n\n Fixpoint sub_list l k n : list A :=\n match l, k, n with\n | _ :: l', S k', _ => sub_list l' k' n\n | x :: l', 0, S n' => x :: sub_list l' 0 n'\n | _, _, _ => nil\n end.\n\n Functional Scheme sub_list_ind := Induction for sub_list Sort Prop.\n\n Lemma sub_list_ok : forall l k n i,\n k < length l -> k+n <= length l -> i < n ->\n element_at (sub_list l k n) i = element_at l (k+i).\n\n Proof.\n intros l k n. functional induction (sub_list l k n); simpl; intros.\n refl. lia. destruct i. refl. apply IHl0; try lia.\n apply IHl0; lia.\n Qed.\n\n Lemma length_sub_list : forall l k n,\n k < length l -> k+n <= length l -> length (sub_list l k n) = n.\n\n Proof.\n intros l k n. functional induction (sub_list l k n); simpl; intros.\n lia. lia.\n destruct l'. simpl in *. lia. rewrite IHl0; simpl in *; lia.\n rewrite IHl0; lia.\n Qed.\n\n Lemma eq_app_elim_l : forall l1 l l2,\n l = l1 ++ l2 -> l1 = sub_list l 0 (length l1).\n\n Proof.\n induction l1; destruct l; simpl; intros. refl. refl. discr.\n inversion H. subst. apply tail_eq. eapply IHl1. refl.\n Qed.\n\n Lemma eq_app_elim_r : forall l1 l l2,\n l = l1 ++ l2 -> l2 = sub_list l (length l1) (length l2).\n\n Proof.\n induction l1; simpl; intros. subst l2.\n induction l; simpl; intros. refl. rewrite <- IHl. refl.\n destruct l. discr. inversion H. subst. simpl. apply IHl1. refl.\n Qed.\n\n Lemma sub_list_0 : forall l k, sub_list l k 0 = nil.\n\n Proof.\n induction l; induction k; simpl; auto.\n Qed.\n\n Lemma sub_list_length : forall l, sub_list l 0 (length l) = l.\n\n Proof.\n induction l; simpl; intros. refl. rewrite IHl. refl.\n Qed.\n\n Lemma app_eq_sub_list : forall l1 l2, l1++l2 =\n sub_list (l1++l2) 0 (length l1)\n ++ sub_list (l1++l2) (length l1) (length l2).\n\n Proof.\n induction l1; simpl; intros. rewrite sub_list_0, sub_list_length.\n refl. rewrite <- IHl1. refl.\n Qed.\n\nEnd sub_list.\n\nArguments eq_app_elim_l [A l1 l l2] _.\nArguments eq_app_elim_r [A l1 l l2] _.\n\n(****************************************************************************)\n(** [lforall] checks whether a predicate is satisfied by every element. *)\n\nSection lforall.\n\n Variables (A : Type) (P : A->Prop).\n\n Fixpoint lforall (l : list A) : Prop :=\n match l with\n | nil => True\n | cons h t => P h /\\ lforall t\n end.\n\n Lemma lforall_eq : forall l, lforall l <-> (forall x, In x l -> P x).\n\n Proof. induction l; simpl; intuition. subst. hyp. Qed.\n\n Lemma lforall_nil : lforall nil.\n\n Proof. simpl. auto. Qed.\n\n Lemma lforall_cons a l : lforall (cons a l) -> P a /\\ lforall l.\n\n Proof. auto. Qed.\n\n Lemma lforall_app l2 : forall l1 : list A,\n lforall (l1 ++ l2) <-> lforall l1 /\\ lforall l2.\n\n Proof. induction l1; simpl; intuition. Qed.\n\n Lemma lforall_in a l : lforall l -> In a l -> P a.\n\n Proof.\n elim l.\n intros H1 H2. absurd (In a nil); [apply in_nil | hyp].\n intros b l' Hrec H1 H2. elim (in_inv H2).\n intro H3. subst a. unfold lforall in H1. intuition.\n clear H2. intro H2. gen (lforall_cons H1).\n intros (H3, H4). apply (Hrec H4 H2).\n Qed.\n\n Lemma lforall_intro : forall l, (forall x, In x l -> P x) -> lforall l.\n\n Proof.\n induction l; simpl; intros. exact I. split. apply H. auto.\n apply IHl. intros. apply H. auto.\n Qed.\n\n Lemma lforall_incl l1 l2 : l1 [= l2 -> lforall l2 -> lforall l1.\n\n Proof.\n intros. apply lforall_intro. intros. eapply lforall_in. apply H0.\n apply H. hyp.\n Qed.\n\n Lemma forallb_imp_lforall f : forall l,\n (forall x, f x = true -> P x) -> forallb f l = true -> lforall l.\n\n Proof with auto.\n induction l; simpl; intros...\n split.\n apply H. destruct (f a)...\n destruct (f a)... discr.\n Qed.\n\n Lemma forallb_lforall f (fok : forall x, f x = true <-> P x) :\n forall l, forallb f l = true <-> lforall l.\n\n Proof. induction l; simpl. tauto. rewrite andb_eq, fok. intuition. Qed.\n\n Variable P_dec : forall x, {P x}+{~P x}.\n\n Lemma lforall_dec : forall l, {lforall l} + {~lforall l}.\n\n Proof.\n induction l.\n left. simpl. trivial.\n simpl. destruct (@P_dec a). \n destruct IHl.\n left; auto.\n right; intuition.\n right; intuition.\n Defined.\n\nEnd lforall.\n\nArguments lforall_in [A P a l] _ _.\n\nLemma lforall_imp A (P1 P2 : A->Prop) :\n (forall x, P1 x -> P2 x) -> forall l, lforall P1 l -> lforall P2 l.\n\nProof.\nintros H l. elim l.\n intuition.\n intros a' l' Hrec. simpl. intros (H1, H2). split.\n apply H. hyp.\n apply Hrec. hyp.\nQed.\n", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/CoLoR/Coq8.16/ListUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10818896462614715, "lm_q1q2_score": 0.05324932480490646}} {"text": "(*\n * Copyright 2020 Youngju Song\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *)\n(* *********************************************************************)\n(* *)\n(* Software Foundations Laboratory's Lemmas & Tactic *)\n(* based on Viktor and Gil's lemmas & tactic *)\n(* *)\n(* *********************************************************************)\n\n(** This file collects a number of basic lemmas and tactics for better\n proof automation, structuring large proofs, or rewriting. Most of \n the rewriting support is ported from ssreflect. *)\n\n(** Symbols starting with [sflib__] are internal. *)\n\nRequire Import Bool List Arith ZArith String Program.\n(* Require Export paconotation newtac. *)\n\nSet Implicit Arguments.\n\nHint Unfold not iff id.\n\nExport ListNotations.\n\n(* Notation \"~ x\" := (forall (FH: x), False) : type_scope. *)\n\n(* Function composition *)\nNotation \"f <*> g\" := (compose f g) (at level 49, left associativity).\n\n(* ************************************************************************** *)\n(** * Coersion of [bool] into [Prop] *)\n(* ************************************************************************** *)\n\n(** Coersion of bools into Prop *)\nCoercion is_true (b : bool) : Prop := b = true.\n\n(** Hints for auto *)\nLemma sflib__true_is_true : true.\nProof. reflexivity. Qed.\n\nLemma sflib__not_false_is_true : ~ false.\nProof. discriminate. Qed.\n\nLemma sflib__negb_rewrite: forall {b}, negb b -> b = false.\nProof. intros []; (reflexivity || discriminate). Qed.\n\nLemma sflib__andb_split: forall {b1 b2}, b1 && b2 -> b1 /\\ b2.\nProof. intros [] []; try discriminate; auto. Qed.\n\nHint Resolve sflib__true_is_true sflib__not_false_is_true.\n\n(* ************************************************************************** *)\n(** * Basic automation tactics *)\n(* ************************************************************************** *)\n\n(** Set up for basic simplification *)\n\nCreate HintDb sflib discriminated. \n\n(** Adaptation of the ss-reflect \"[done]\" tactic. *)\n\nLtac sflib__basic_done := \n solve [trivial with sflib | apply sym_equal; trivial | discriminate | contradiction].\n\nLtac done := unfold not in *; trivial with sflib; hnf; intros;\n solve [try sflib__basic_done; split; \n try sflib__basic_done; split; \n try sflib__basic_done; split; \n try sflib__basic_done; split; \n try sflib__basic_done; split; sflib__basic_done\n | match goal with H : _ -> False |- _ => solve [case H; trivial] end].\n\n(** A variant of the ssr \"done\" tactic that performs \"eassumption\". *)\n\nLtac edone := try eassumption; trivial; hnf; intros;\n solve [try eassumption; try sflib__basic_done; split; \n try eassumption; try sflib__basic_done; split; \n try eassumption; try sflib__basic_done; split; \n try eassumption; try sflib__basic_done; split; \n try eassumption; try sflib__basic_done; split;\n try eassumption; sflib__basic_done\n | match goal with H : ~ _ |- _ => solve [case H; trivial] end].\n\nTactic Notation \"by\" tactic(tac) := (tac; done).\nTactic Notation \"eby\" tactic(tac) := (tac; edone).\n\nLtac sflib__complaining_inj f H :=\n let X := fresh in\n (match goal with | [|- ?P ] => set (X := P) end);\n injection H;\n (lazymatch goal with | [ |- f _ = f _ -> _] => fail | _ => idtac end);\n clear H; intros;\n subst X;\n try subst.\n\nLtac sflib__clarify1 :=\n try subst;\n repeat match goal with\n | [H: is_true (andb _ _) |- _] => case (sflib__andb_split H); clear H; intros ? H\n | [H: is_true (negb ?x) |- _] => rewrite (sflib__negb_rewrite H) in *\n | [H: is_true ?x |- _] => rewrite H in *\n | [H: ?x = true |- _] => rewrite H in *\n | [H: ?x = false |- _] => rewrite H in *\n | [H: ?f _ = ?f _ |- _] => sflib__complaining_inj f H\n | [H: ?f _ _ = ?f _ _ |- _] => sflib__complaining_inj f H\n | [H: ?f _ _ _ = ?f _ _ _ |- _] => sflib__complaining_inj f H\n | [H: ?f _ _ _ _ = ?f _ _ _ _ |- _] => sflib__complaining_inj f H\n | [H: ?f _ _ _ _ _ = ?f _ _ _ _ _ |- _] => sflib__complaining_inj f H\n | [H: ?f _ _ _ _ _ _ = ?f _ _ _ _ _ _ |- _] => sflib__complaining_inj f H\n | [H: ?f _ _ _ _ _ _ _ = ?f _ _ _ _ _ _ _ |- _] => sflib__complaining_inj f H\n end; try done.\n\n(** Perform injections & discriminations on all hypotheses *)\n\nLtac clarify :=\n sflib__clarify1;\n repeat match goal with\n | H1: ?x = Some _, H2: ?x = None |- _ => rewrite H2 in H1; sflib__clarify1\n | H1: ?x = Some _, H2: ?x = Some _ |- _ => rewrite H2 in H1; sflib__clarify1\n end.\n\n(** Kill simple goals that require up to two econstructor calls. *)\n\n(* from CompCert-2.4/lib/Coqlib.v *)\nLtac inv H := inversion H; clear H; subst.\n\nLtac hinv x := move x at bottom; inversion x; clarify.\n\nTactic Notation \"hinv\" ident(a) :=\n (hinv a).\nTactic Notation \"hinv\" ident(a) ident(b) :=\n (hinv a; hinv b).\nTactic Notation \"hinv\" ident(a) ident(b) ident(c) :=\n (hinv a; hinv b c).\nTactic Notation \"hinv\" ident(a) ident(b) ident(c) ident(d) := \n (hinv a b; hinv c d).\n\nLtac hinvc x := hinv x; clear x.\n\nTactic Notation \"hinvc\" ident(a) :=\n (hinvc a).\nTactic Notation \"hinvc\" ident(a) ident(b) :=\n (hinvc a; hinvc b).\nTactic Notation \"hinvc\" ident(a) ident(b) ident(c) :=\n (hinvc a; hinvc b c).\nTactic Notation \"hinvc\" ident(a) ident(b) ident(c) ident(d) := \n (hinvc a b; hinvc c d).\nTactic Notation \"hinvc\" ident(a) ident(b) ident(c) ident(d) ident(e) := \n (hinvc a b c; hinvc d e).\n\nLtac simpls := simpl in *; try done.\nLtac ins := simpl in *; try done; intros.\n\nTactic Notation \"case_eq\" constr(x) := case_eq (x).\n\nTactic Notation \"case_eq\" constr(x) \"as\" simple_intropattern(H) :=\n destruct x as [] eqn: H; try done.\n\n\n(* ************************************************************************** *)\n(** * Basic simplication tactics *)\n(* ************************************************************************** *)\n\nLtac sflib__clarsimp1 :=\n clarify; (autorewrite with sflib in * ); try done;\n match goal with\n | [H: is_true ?x |- _] => rewrite H in *; sflib__clarsimp1\n | [H: ?x = true |- _] => rewrite H in *; sflib__clarsimp1\n | [H: ?x = false |- _] => rewrite H in *; sflib__clarsimp1\n | _ => clarify; auto 1 with sflib\n end.\n\nLtac clarsimp := intros; simpl in *; sflib__clarsimp1.\n\nLtac autos := clarsimp; auto with sflib.\n\n(* hdesH, hdes: more general des *)\n\nDefinition NW A (P: () -> A) : A := P ().\n\n(* Notation \"<< x : t >>\" := (NW (fun x => (t):Prop)) (at level 80, x ident, no associativity). *)\nNotation \"<< x : t >>\" := (NW (fun x => (t))) (at level 80, x ident, no associativity).\nNotation \"<< t >>\" := (NW (fun _ => t)) (at level 79, no associativity).\nNotation \"<< t >>\" := (NW (fun _ => (t):Prop)) (at level 79, no associativity).\n\nLtac unnw := unfold NW in *.\nLtac rednw := red; unnw.\n\nHint Unfold NW.\n\nLtac get_concl := lazymatch goal with [ |- ?G ] => G end.\n\nLtac des1 :=\n match goal with\n | H : NW _ |- _ => red in H\n | H : exists x, NW (fun y => _) |- _ => \n let x' := fresh x in let y' := fresh y in destruct H as [x' y']; red in y'\n | H : exists x, ?p |- _ => \n let x' := fresh x in destruct H as [x' H]\n | H : ?p /\\ ?q |- _ => \n let x' := match p with | NW (fun z => _) => fresh z | _ => H end in\n let y' := match q with | NW (fun z => _) => fresh z | _ => fresh H end in\n destruct H as [x' y'];\n match p with | NW _ => red in x' | _ => idtac end;\n match q with | NW _ => red in y' | _ => idtac end\n | H : ?p <-> ?q |- _ => \n let x' := match p with | NW (fun z => _) => fresh z | _ => H end in\n let y' := match q with | NW (fun z => _) => fresh z | _ => fresh H end in\n destruct H as [x' y'];\n match p with | NW _ => unfold NW at 1 in x'; red in y' | _ => idtac end;\n match q with | NW _ => unfold NW at 1 in y'; red in x' | _ => idtac end\n | H : ?p \\/ ?q |- _ =>\n let x' := match p with | NW (fun z => _) => fresh z | _ => H end in\n let y' := match q with | NW (fun z => _) => fresh z | _ => H end in\n destruct H as [x' | y'];\n [ match p with | NW _ => red in x' | _ => idtac end\n | match q with | NW _ => red in y' | _ => idtac end]\n end.\n\nLtac des := repeat des1.\n\nLtac desc :=\n repeat match goal with\n | H : exists x, NW (fun y => _) |- _ =>\n let x' := fresh x in let y' := fresh y in destruct H as [x' y']; red in y'\n | H : exists x, ?p |- _ =>\n let x' := fresh x in destruct H as [x' H]\n | H : ?p /\\ ?q |- _ =>\n let x' := match p with | NW (fun z => _) => fresh z | _ => H end in\n let y' := match q with | NW (fun z => _) => fresh z | _ => fresh H end in\n destruct H as [x' y'];\n match p with | NW _ => red in x' | _ => idtac end;\n match q with | NW _ => red in y' | _ => idtac end\n | H : is_true (_ && _) |- _ =>\n let H' := fresh H in case (sflib__andb_split H); clear H; intros H H'\n | H : ?x = ?x |- _ => clear H\n end.\n\nLtac nbdes1 :=\n match goal with\n | H : NW _ |- _ => red in H\n | H : exists x, NW (fun y => _) |- _ => \n let x' := fresh x in let y' := fresh y in destruct H as [x' y']; red in y'\n | H : exists x, ?p |- _ => \n let x' := fresh x in destruct H as [x' H]\n | H : ?p /\\ ?q |- _ => \n let x' := match p with | NW (fun z => _) => fresh z | _ => H end in\n let y' := match q with | NW (fun z => _) => fresh z | _ => fresh H end in\n destruct H as [x' y'];\n match p with | NW _ => red in x' | _ => idtac end;\n match q with | NW _ => red in y' | _ => idtac end\n | H : ?p <-> ?q |- _ => \n let x' := match p with | NW (fun z => _) => fresh z | _ => H end in\n let y' := match q with | NW (fun z => _) => fresh z | _ => fresh H end in\n destruct H as [x' y'];\n match p with | NW _ => unfold NW at 1 in x'; red in y' | _ => idtac end;\n match q with | NW _ => unfold NW at 1 in y'; red in x' | _ => idtac end\n (* | H : ?p \\/ ?q |- _ => *)\n (* let x' := match p with | NW (fun z => _) => fresh z | _ => H end in *)\n (* let y' := match q with | NW (fun z => _) => fresh z | _ => H end in *)\n (* destruct H as [x' | y']; *)\n (* [ match p with | NW _ => red in x' | _ => idtac end *)\n (* | match q with | NW _ => red in y' | _ => idtac end] *)\n end.\n\nLtac nbdes := repeat nbdes1.\nLtac rrnbdes H := move H at bottom; repeat red in H; nbdes.\n\nLtac forall_split :=\n let H := fresh \"__forall_split__\" in first [intro; forall_split; match goal with [H:_|-_] => revert H end | split].\n\nDefinition _HID_ (A : Type) (a : A) := a.\n\nLtac hdesHi H P x y :=\n let FF := fresh \"__hdesfalse__\" in \n let TMP := fresh \"__hdesHi__\" in \n let P1 := fresh \"__hdesHi__\" in \n let P2 := fresh \"__hdesHi__\" in \n evar (P1 : Prop); evar (P2 : Prop);\n assert (TMP: False -> P) by\n (intro FF; forall_split;\n [ let G := get_concl in set (TMP := G); revert P1; instantiate (1:=G)\n | let G := get_concl in set (TMP := G); revert P2; instantiate (1:=G) ];\n destruct FF);\n try clear TMP; \n try (try (match goal with [Def := ?G : _ |- _] =>\n match Def with P1 =>\n match goal with [_ : G |- _] => fail 4 end end end);\n assert (x: P1) by (unfold P1; repeat (let x := fresh \"__xhj__\" in intro x; specialize (H x)); apply H));\n try unfold P1 in x; try clear P1;\n try (try (match goal with [Def := ?G : _ |- _] =>\n match Def with P2 =>\n match goal with [_ : G |- _] => fail 4 end end end);\n assert (y: P2) by (unfold P2; repeat (let x := fresh \"__xhj__\" in intro x; specialize (H x)); apply H)); \n try unfold P2 in y; try clear P2;\n fold (_HID_ P) in H;\n try clear H.\n\nLtac hdesHP H P :=\n let H' := fresh H in let H'' := fresh H in\n match P with \n | context[ NW (fun x => _) /\\ NW (fun y => _) ] => \n let x' := fresh x in let y' := fresh y in\n hdesHi H P x' y'; red in x'; red in y'\n | context[ NW (fun x => _) /\\ _ ] => \n let x' := fresh x in\n hdesHi H P x' H'; red in x'\n | context[ _ /\\ NW (fun y => _) ] => \n let y' := fresh y in\n hdesHi H P H' y'; red in y'\n | context[ _ /\\ _ ] => \n hdesHi H P H' H''\n | context[ NW (fun x => _) <-> NW (fun y => _) ] =>\n let x' := fresh x in let y' := fresh y in\n hdesHi H P x' y'; red in x'; red in y'\n | context[ NW (fun x => _) <-> _ ] => \n let x' := fresh x in\n hdesHi H P x' H'; red in x'\n | context[ _ <-> NW (fun y => _) ] => \n let y' := fresh y in\n hdesHi H P H' y'; red in y'\n | context[ _ <-> _ ] => \n hdesHi H P H' H''\n end.\n\nLtac hdesH H := let P := type of H in hdesHP H P; unfold _HID_ in *.\n\n(*\n(* It works, but too slows *)\nLtac hdesF P :=\n match P with\n | fun _ => _ /\\ _ => idtac\n | fun _ => _ <-> _ => idtac\n | fun x => forall y : @?ty x, @?f x y =>\n let P' := eval cbv beta in (fun p : sigT ty => f (projT1 p) (projT2 p)) in\n hdesF P'\n end.\n\nLtac hdes := \n repeat match goal with | H : ?P |- _ => hdesF (fun _ : unit => P); hdesHP H P end; \n unfold _HID_ in *.\n*)\n\nLtac hdesF P :=\n match P with | _ /\\ _ => idtac | _ <-> _ => idtac | forall _, _ => \n match P with | forall _, _ /\\ _ => idtac | forall _, _ <-> _ => idtac | forall _ _, _ => \n match P with | forall _ _, _ /\\ _ => idtac | forall _ _, _ <-> _ => idtac | forall _ _ _, _ =>\n match P with | forall _ _ _, _ /\\ _ => idtac | forall _ _ _, _ <-> _ => idtac | forall _ _ _ _, _ => \n match P with | forall _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _, _ =>\n match P with | forall _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _, _ =>\n match P with | forall _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ => \n match P with | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ /\\ _ => idtac | forall _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, _ <-> _ => idtac\n end end end end end end end end end end end end end end end end end end end end end.\n\n(** Fail if hypothesis [H] doesn't exist. *)\nLtac check_hyp H := match H with _ => idtac end.\n\n(** Fail if hypothesis [H1] is not [H2]. *)\nLtac check_equal H1 H2 := match H1 with H2 => idtac end.\n\nLtac hdes := \n repeat match goal with | H : ?P |- _ => hdesF P; hdesHP H P end; \n unfold _HID_ in *.\nLtac rdes H := red in H; des.\nLtac rrdes H := move H at bottom; repeat red in H; des.\nLtac rhdes H := red in H; hdes.\nLtac rrhdes H := check_hyp H; repeat red in H; hdes.\n\nTactic Notation \"rrdes\" ident(a) :=\n (rrdes a).\nTactic Notation \"rrdes\" ident(a) ident(b) :=\n (rrdes a; rrdes b).\nTactic Notation \"rrdes\" ident(a) ident(b) ident(c) :=\n (rrdes a; rrdes b c).\nTactic Notation \"rrdes\" ident(a) ident(b) ident(c) ident(d) := \n (rrdes a b; rrdes c d).\n\n(** Destruct the condition of an [if] expression occuring in the goal. *)\nLtac des_if :=\n match goal with\n | [ |- context[if ?X then _ else _] ] => destruct X\n end.\n(* Ltac desE_if := *)\n(* match goal with *)\n(* | [ |- context[if ?X then _ else _] ] => let E := fresh X in destruct X eqn:E *)\n(* end. *)\n\n(** Destruct the condition of an [if] expression occuring in the given hypothesis. *)\nLtac des_ifH H :=\n match goal with\n | [ H' : context[if ?X then _ else _] |- _ ] => check_equal H' H; destruct X\n end.\n\n(* TODO tactics such as these should always do clean at the end to remove junk like [H : x = x] *)\nLtac des_ifs :=\n clarify;\n repeat \n match goal with \n | |- context[match ?x with _ => _ end] => \n match (type of x) with\n | { _ } + { _ } => destruct x; clarify\n | _ => let Heq := fresh \"Heq\" in destruct x as [] eqn: Heq; clarify\n end \n | H: context[ match ?x with _ => _ end ] |- _ => \n match (type of x) with\n | { _ } + { _ } => destruct x; clarify\n | _ => let Heq := fresh \"Heq\" in destruct x as [] eqn: Heq; clarify\n end \n end.\n\nLtac desf := clarify; des; des_ifs.\nLtac isd := ins; desf.\n\n(** Create a copy of hypothesis [H]. *)\nTactic Notation \"dup\" hyp(H) :=\n let H' := fresh H in assert (H' := H).\n\n(* (** Call tactic [tac] on a copy of [H]. *) *)\n(* Tactic Notation \"dup\" hyp(H) tactic(tac) := *)\n(* let H' := fresh H in assert (H' := H); tac H'. *)\n\nLtac clarassoc := clarsimp; autorewrite with sflib sflibA in *; try done. \n\nLtac sflib__hacksimp1 :=\n clarsimp;\n match goal with\n | H: _ |- _ => solve [rewrite H; clear H; clarsimp\n |rewrite <- H; clear H; clarsimp]\n | _ => solve [f_equal; clarsimp]\n end.\n\nLtac hacksimp :=\n clarsimp;\n try match goal with\n | H: _ |- _ => solve [rewrite H; clear H; clarsimp\n |rewrite <- H; clear H; clarsimp]\n | |- context[if ?p then _ else _] => solve [destruct p; sflib__hacksimp1]\n | _ => solve [f_equal; clarsimp]\n end.\n\n(* ************************************************************************** *)\n(** * Delineating cases in proofs *)\n(* ************************************************************************** *)\n\n(** Named case tactics (taken from Libtactics) *)\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move x at top\n | assert_eq x name\n | fail 1 \"because we are working on a different case.\" ].\n\nLtac Case name := Case_aux case name.\nLtac SCase name := Case_aux subcase name.\nLtac SSCase name := Case_aux subsubcase name.\nLtac SSSCase name := Case_aux subsubsubcase name.\nLtac SSSSCase name := Case_aux subsubsubsubcase name.\n\n(** Lightweight case tactics (without names) *)\n\nTactic Notation \"-\" tactic(c) :=\n first [\n assert (WithinCaseM := True); move WithinCaseM at top\n | fail 1 \"because we are working on a different case.\" ]; c.\n\nTactic Notation \"+\" tactic(c) :=\n first [\n assert (WithinCaseP := True); move WithinCaseP at top\n | fail 1 \"because we are working on a different case.\" ]; c.\n\nTactic Notation \"*\" tactic(c) :=\n first [\n assert (WithinCaseS := True); move WithinCaseS at top\n | fail 1 \"because we are working on a different case.\" ]; c.\n\nTactic Notation \":\" tactic(c) :=\n first [\n assert (WithinCaseC := True); move WithinCaseC at top\n | fail 1 \"because we are working on a different case.\" ]; c.\n\n(* ************************************************************************** *)\n(** * Exploiting a hypothesis *)\n(* ************************************************************************** *)\n\n(** Exploit an assumption (adapted from CompCert). *)\n\nLtac exploit x :=\n refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _ _) _)\n || refine ((fun x y => y x) (x _ _ _) _)\n || refine ((fun x y => y x) (x _ _) _)\n || refine ((fun x y => y x) (x _) _).\n\n(* When 'exploit x' generates too many sub goals, try 'hexploit x' *)\n\nLemma mp: forall P Q: Type, P -> (P -> Q) -> Q.\nProof. intuition. Defined.\n\nLemma mp': forall P Q : Type, (P -> Q) -> P -> Q.\nProof. intuition. Qed.\n\nLtac hexploit x := eapply mp; [eapply x|].\nLtac hexploit' x := let H := fresh in set (H := x); clear H; eapply mp; [eapply x|].\n\n(* set_prop N T A performs 'assert (A : P); [|set (N := T A)]' when T is a term of type (P -> _) *)\n\nLtac set_prop N T A := \n let b := fresh in let ty := type of T in\n match ty with (forall (_:?P), _) => assert (A: P); [|set (N := T A)] end.\n\n(* ************************************************************************** *)\n(** * Induction tactics *)\n(* ************************************************************************** *)\n\nTactic Notation \"induction\" \"[\" ident_list(y) \"]\" ident(x) :=\n first [ try (intros until x); revert y; induction x\n | red; try (intros until x); revert y; induction x ].\n\nTactic Notation \"induction\" \"[\" ident_list(y) \"]\" ident(x) \"[\" ident(z) \"]\" :=\n first [ try (intros until x); revert y; induction x; destruct z\n | red; try (intros until x); revert y; induction x; destruct z ].\n\n(** Versions with hacksimp *)\n\nTactic Notation \"induct\" ident(x) := induction x; hacksimp.\n\nTactic Notation \"induct\" ident(x) \"[\" ident(z) \"]\" := \n induction x; destruct z; hacksimp.\n\nTactic Notation \"induct\" \"[\" ident_list(y) \"]\" ident(x) :=\n first [ try (intros until x); revert y; induction x; hacksimp\n | red; try (intros until x); revert y; induction x; hacksimp ].\n\nTactic Notation \"induct\" \"[\" ident_list(y) \"]\" ident(x) \"[\" ident(z) \"]\" :=\n first [ try (intros until x); revert y; induction x; destruct z; hacksimp\n | red; try (intros until x); revert y; induction x; destruct z; hacksimp ].\n\nTactic Notation \"edestructs\" ident(a) := \n (edestruct a).\nTactic Notation \"edestructs\" ident(a) ident(b) := \n (edestruct a; edestruct b).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) := \n (edestruct a; edestructs b c).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) := \n (edestruct a; edestructs b c d).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) ident(e) := \n (edestruct a; edestructs b c d e).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) :=\n (edestruct a; edestructs b c d e f).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) := \n (edestruct a; edestructs b c d e f g).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) :=\n (edestruct a; edestructs b c d e f g h).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) ident(i) := \n (edestruct a; edestructs b c d e f g h i).\nTactic Notation \"edestructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) ident(i) ident(j) := \n (edestruct a; edestructs b c d e f g h i j).\n\nTactic Notation \"destructs\" ident(a) :=\n (destruct a).\nTactic Notation \"destructs\" ident(a) ident(b) := \n (destruct a; destruct b).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) := \n (destruct a; destructs b c).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) :=\n (destruct a; destructs b c d).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) ident(e) :=\n (destruct a; destructs b c d e).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) :=\n (destruct a; destructs b c d e f).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) :=\n (destruct a; destructs b c d e f g).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) := \n (destruct a; destructs b c d e f g h).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) ident(i) := \n (destruct a; destructs b c d e f g h i).\nTactic Notation \"destructs\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) ident(i) ident(j) := \n (destruct a; destructs b c d e f g h i j).\n\nTactic Notation \"depdes\" ident(_something_which_shold_not_occur_in_the_goal_) :=\n (let _x_ := type of _something_which_shold_not_occur_in_the_goal_ \n in dependent destruction _something_which_shold_not_occur_in_the_goal_).\nTactic Notation \"depdes\" ident(a) ident(b) := \n (depdes a; depdes b).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) := \n (depdes a; depdes b c).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) :=\n (depdes a; depdes b c d).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) ident(e) :=\n (depdes a; depdes b c d e).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) :=\n (depdes a; depdes b c d e f).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) :=\n (depdes a; depdes b c d e f g).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) := \n (depdes a; depdes b c d e f g h).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) ident(i) := \n (depdes a; depdes b c d e f g h i).\nTactic Notation \"depdes\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) ident(g) ident(h) ident(i) ident(j) := \n (depdes a; depdes b c d e f g h i j).\n\nTactic Notation \"depgen\" ident(x) := generalize dependent x.\n\n(* eappleft, eappright *)\n\nLtac eappleft H :=\n let X := fresh \"__lem__\" in let X1 := fresh \"__lem__\" in let X2 := fresh \"__lem__\" in\n assert (X:= H); let P := type of X in hdesHi X P X1 X2;\n eapply X1; clear X1 X2.\n\nLtac eappright H :=\n let X := fresh \"__lem__\" in let X1 := fresh \"__lem__\" in let X2 := fresh \"__lem__\" in\n assert (X:= H); let P := type of X in hdesHi X P X1 X2;\n eapply X2; clear X1 X2.\n\n(* guard for simpl *)\n\n(* for Coq8.4 *)\n\nDefinition __guard__ A (a : A) : A := a.\nDefinition __GUARD__ A (a : A) : A := a.\nArguments __guard__ A a : simpl never.\nArguments __GUARD__ A a : simpl never.\n\nTactic Notation \"guard\" constr(t) \"in\" hyp(H) := fold (__guard__ t) in H.\nTactic Notation \"guardH\" hyp(H) := let t := type of H in guard t in H.\nTactic Notation \"guard\" := \n repeat match goal with [H: ?P |- _] =>\n try (match P with __guard__ _ => fail 2 end); guardH H\n end.\nTactic Notation \"sguard\" constr(t) \"in\" hyp(H) := fold (__GUARD__ t) in H.\nTactic Notation \"sguard\" \"in\" hyp(H) := let t := type of H in sguard t in H.\n\nLtac unguard := unfold __guard__ in *.\nLtac unguardH H := unfold __guard__ in H.\nLtac unsguard H := unfold __GUARD__ in H.\n\nLtac desH H := guard; unguardH H; des; unguard.\n\nLtac splits :=\n intros; unfold NW;\n repeat match goal with \n | [ |- _ /\\ _ ] => split\n end.\nLtac esplits :=\n intros; unfold NW;\n repeat match goal with \n | [ |- @ex _ _ ] => eexists\n | [ |- _ /\\ _ ] => split\n | [ |- @sig _ _ ] => eexists\n | [ |- @sigT _ _ ] => eexists\n | [ |- @prod _ _ ] => split\n end.\n\nTactic Notation \"replace_all\" constr(e) := repeat (\n let X := fresh in assert (X: e) by (clarify; eauto; done); \n first [rewrite !X | setoid_rewrite X]; clear X).\n\nLemma all_conj_dist: forall A (P Q: A -> Prop), \n (forall a, P a /\\ Q a) -> (forall a, P a) /\\ (forall a, Q a).\nProof. intros; hdes; eauto. Qed.\n\n(* extensionalities *)\n\nTactic Notation \"extensionalities\" :=\n repeat let x := fresh in extensionality x.\nTactic Notation \"extensionalities\" ident(a) :=\n (extensionality a).\nTactic Notation \"extensionalities\" ident(a) ident(b) :=\n (extensionality a; extensionality b).\nTactic Notation \"extensionalities\" ident(a) ident(b) ident(c) :=\n (extensionality a; extensionalities b c).\nTactic Notation \"extensionalities\" ident(a) ident(b) ident(c) ident(d) :=\n (extensionality a; extensionalities b c d).\nTactic Notation \"extensionalities\" ident(a) ident(b) ident(c) ident(d) ident(e) :=\n (extensionality a; extensionalities b c d e).\nTactic Notation \"extensionalities\" ident(a) ident(b) ident(c) ident(d) ident(e) ident(f) :=\n (extensionality a; extensionalities b c d e f).\n\n(* short for common tactics *)\n\nTactic Notation \"inst\" := instantiate.\nTactic Notation \"econs\" := econstructor.\nTactic Notation \"econs\" int_or_var(x) := econstructor x.\nTactic Notation \"i\" := intros.\nTactic Notation \"ii\" := repeat intro.\nTactic Notation \"s\" := simpl.\nTactic Notation \"s\" ident(a) := simpl a.\nTactic Notation \"s\" constr(t) := simpl t.\nTactic Notation \"s\" \"in\" hyp(H) := simpl in H.\nTactic Notation \"ss\" := simpls.\nTactic Notation \"r\" := red.\nTactic Notation \"r\" \"in\" hyp(H) := red in H.\nTactic Notation \"rr\" := repeat red.\nTactic Notation \"rr\" \"in\" hyp(H) := repeat red in H.\n\n(* running a tactic selectively on subgoals *)\n\nDefinition __mark__ A (a : A) : A := a.\n\nTactic Notation \"M\" := \n match goal with [|-?G] => fold (__mark__ G) end.\n\nTactic Notation \"Mdo\" tactic(tac) :=\n first [ try match goal with [|- __mark__ _ ] => fail 2 end | unfold __mark__; tac ].\n\nTactic Notation \"Mskip\" tactic(tac) :=\n first [ match goal with [|- __mark__ _ ] => unfold __mark__ end | tac ].\n\nTactic Notation \"Mfirst\" tactic(main) \";;\" tactic(post) := \n main; (Mdo (post; M)); (Mskip post).\n\n(* revert until *)\n\nLtac on_last_hyp tac :=\n match goal with [ H : _ |- _ ] => first [ tac H | fail 1 ] end.\n\nLtac revert_until id :=\n on_last_hyp ltac:(fun id' =>\n match id' with\n | id => idtac\n | _ => revert id' ; revert_until id\n end).\n\nOpen Scope string_scope.\nOpen Scope list_scope.\n\nFixpoint beq_str (s1 s2: string) : bool := \n match s1, s2 with\n | \"\", \"\" => true\n | String a s1', String b s2' => if Ascii.ascii_dec a b then beq_str s1' s2' else false\n | _, _ => false\n end.\n\nLtac uf := (autounfold with * in *).\n\nTactic Notation \"patout\" constr(z) \"in\" hyp(a) :=\n pattern z in a; match goal with [a:=?f z|-_] => unfold a; clear a; set (a:=f) end.\n\nLtac clear_upto H :=\n repeat (match goal with [Hcrr : _ |- _ ] => first [ check_equal Hcrr H; fail 2\n | clear Hcrr ] end).\n\nDefinition _Evar_sflib_ (A:Type) (x:A) := x.\n\nTactic Notation \"hide_evar\" int_or_var(n) := let QQ := fresh \"QQ\" in\n hget_evar n; intro;\n lazymatch goal with [ H := ?X |- _] => \n set (QQ := X) in *; fold (_Evar_sflib_ X) in QQ; clear H \n end.\n\nLtac hide_evars := repeat (hide_evar 1).\n\nLtac show_evars := repeat (match goal with [ H := @_Evar_sflib_ _ _ |- _ ] => unfold\n _Evar_sflib_ in H; unfold H in *; clear H end).\n\nLtac revert1 := match goal with [H: _|-_] => revert H end.\n\nLemma eqimpl: forall P Q : Prop, P = Q -> P -> Q. \nProof. by i; subst; auto. Qed.\n\nLtac ginduction H :=\n move H at top; revert_until H; induction H.\n\nTactic Notation \"greflgen\" constr(t) \"as\" ident(g) := \n let EQ := fresh \"XEQ\" in\n generalize (eq_refl t); generalize t at -2 as g\n ; intros ? EQ ?; revert EQ.\n\nLtac eadmit :=\n exfalso; clear; admit.\n\nLtac special H :=\n (* eapply mp; refine (H _). *)\n match type of H with\n | ?A -> ?B =>\n let a := fresh in assert (a: A); [|specialize (H a)]\n end.\n\n(** Useful for e.g. [ex @nil]. *)\nLtac ex x := eapply (ex_intro _ (x _)).\n\nLtac inst_pairs :=\n repeat first\n [instantiate (9 := (_, _))\n |instantiate (8 := (_, _))\n |instantiate (7 := (_, _))\n |instantiate (6 := (_, _))\n |instantiate (5 := (_, _))\n |instantiate (4 := (_, _))\n |instantiate (3 := (_, _))\n |instantiate (2 := (_, _))\n |instantiate (1 := (_, _))].\n\n(* Problem: unfold fst doesn't always result in a lambda *)\n(* Ltac fold_proj := *)\n(* try match goal with |- context[fun _ : ?A * ?B => _] => *)\n(* first [fold (@fst A B) | fold (@snd A B)]; fail *)\n(* end. *)\n(* Ltac fold_projH H := *)\n(* match type of H with | context[fun _ : ?A * ?B => _] => *)\n(* first [fold (@fst A B) in H | fold (@snd A B) in H]; fail *)\n(* end. *)\n(* Ltac simpl_proj := *)\n(* unfold fst in *; Hdo fold_projH; fold_proj. *)\n\n(* Lemma simpl_fst: forall A (a: A) B (b: B), *)\n(* fst (a, b) = a. *)\n(* Proof. *)\n(* auto. *)\n(* Qed. *)\n\n(* Lemma simpl_snd: forall B (b: B) A (a: A), *)\n(* snd (a, b) = b. *)\n(* Proof. *)\n(* auto. *)\n(* Qed. *)\n\nLtac simpl_proj :=\n do 5 (simpl (fst (_, _)) in *; simpl (snd (_, _)) in *).\n (* ; repeat first [rewrite !simpl_fst | rewrite !simpl_snd] *)\n (* ; Hdo (fun H => repeat first [rewrite !simpl_fst in H | rewrite !simpl_snd in H]). *)\n\nLtac clean :=\n repeat match goal with\n | H: True |- _\n => clear H\n | H: ?x = ?y |- _\n => try (has_evar x; fail 2); try (has_evar y; fail 2);\n change x with y in H; clear H\n end\n ; simpl_proj.\n (* without the evar check, clean removes equations such as the following:\n X : length (getVal ?28711 ?28712 ?28713 ?28714) = S n *)\n\n\nTactic Notation \"lhs\" tactic(tac) :=\n match goal with |- ?op ?lhs ?rhs =>\n let tmp := fresh in set (tmp := rhs); tac; unfold tmp; clear tmp\n end.\n\n(* Variant of lhs that allows prover to combine lhs/rhs tactics in\n * tacticals. For example:\n * lhs (rewrite blah); rhs (rewrite blah).\n * is allowed. lhs fails because the precedence for the tactic\n * was higher than the \";\" and so tac = rewrite blah; rhs (rewrite blah).\n * TODO: Check whether it's safe to override the definition of lhs/rhs.\n *)\nTactic Notation \"lhs3\" tactic3(tac) :=\n match goal with |- ?op ?lhs ?rhs =>\n let tmp := fresh in set (tmp := rhs); tac; unfold tmp; clear tmp\n end.\n\nTactic Notation \"rhs\" tactic(tac) :=\n match goal with |- ?op ?lhs ?rhs =>\n let tmp := fresh in set (tmp := lhs); tac; unfold tmp; clear tmp\n end.\n\n(* See the comment for lhs3. *)\nTactic Notation \"rhs3\" tactic3(tac) :=\n match goal with |- ?op ?lhs ?rhs =>\n let tmp := fresh in set (tmp := lhs); tac; unfold tmp; clear tmp\n end.\n\n\n(* TODO generalize to hyps *)\n\n\n(** Execute a tactic only if the goal contains no evars. *)\nTactic Notation \"safe\" tactic(tac) :=\n try match goal with |- ?G => try (has_evar G; fail 2); tac end.\n\n\n(** Rename a hypothesis to a fresh name. *)\nLtac ren H :=\n let X := fresh H in rename H into X.\n\n(* (** Instantiate consecutive evars. *) *)\n(* Tactic Notation \"insts\" constr(terms) := *)\n(* Hdo (fun x => instantiate (1 := x)) terms. *)\n(* (* TODO this is not very useful after all *) *)\n\n\n\n(** Automation using econstructor.\n What it does is clear from the definition below. *)\nTactic Notation \"econsby\" tactic(tac) :=\n first [econstructor 1; (by tac)\n |econstructor 2; (by tac)\n |econstructor 3; (by tac)\n |econstructor 4; (by tac)\n |econstructor 5; (by tac)\n |econstructor 6; (by tac)\n |econstructor 7; (by tac)\n |econstructor 8; (by tac)\n |econstructor 9; (by tac)\n |econstructor 10; (by tac)\n |econstructor 11; (by tac)\n |econstructor 12; (by tac)\n |econstructor 13; (by tac)\n |econstructor 14; (by tac)\n |econstructor 15; (by tac)\n |econstructor 16; (by tac)\n |econstructor 17; (by tac)\n |econstructor 18; (by tac)\n |econstructor 19; (by tac)\n |econstructor 20; (by tac)\n ].\n\n\n(* Youngju's Tactics *)\n\nLemma f_equal6 (A1 A2 A3 A4 A5 A6 B: Type) (f: A1 -> A2 -> A3 -> A4 -> A5 -> A6 -> B)\n (x1 y1: A1) (EQ1: x1 = y1)\n (x2 y2: A2) (EQ2: x2 = y2)\n (x3 y3: A3) (EQ3: x3 = y3)\n (x4 y4: A4) (EQ4: x4 = y4)\n (x5 y5: A5) (EQ5: x5 = y5)\n (x6 y6: A6) (EQ6: x6 = y6)\n :\n <>\n.\nProof. subst. reflexivity. Qed.\n\nLemma f_equal7 (A1 A2 A3 A4 A5 A6 A7 B: Type) (f: A1 -> A2 -> A3 -> A4 -> A5 -> A6 -> A7 -> B)\n (x1 y1: A1) (EQ1: x1 = y1)\n (x2 y2: A2) (EQ2: x2 = y2)\n (x3 y3: A3) (EQ3: x3 = y3)\n (x4 y4: A4) (EQ4: x4 = y4)\n (x5 y5: A5) (EQ5: x5 = y5)\n (x6 y6: A6) (EQ6: x6 = y6)\n (x7 y7: A7) (EQ7: x7 = y7)\n :\n <>\n.\nProof. subst. reflexivity. Qed.\n\nLemma f_equal8 (A1 A2 A3 A4 A5 A6 A7 A8 B: Type) (f: A1 -> A2 -> A3 -> A4 -> A5 -> A6 -> A7 -> A8 -> B)\n (x1 y1: A1) (EQ1: x1 = y1)\n (x2 y2: A2) (EQ2: x2 = y2)\n (x3 y3: A3) (EQ3: x3 = y3)\n (x4 y4: A4) (EQ4: x4 = y4)\n (x5 y5: A5) (EQ5: x5 = y5)\n (x6 y6: A6) (EQ6: x6 = y6)\n (x7 y7: A7) (EQ7: x7 = y7)\n (x8 y8: A8) (EQ8: x8 = y8)\n :\n <>\n.\nProof. subst. reflexivity. Qed.\n\nLtac rpapply_raw H :=\n first[erewrite f_equal8 | erewrite f_equal7 | erewrite f_equal6 | erewrite f_equal5 |\n erewrite f_equal4 | erewrite f_equal3 | erewrite f_equal2 | erewrite f_equal];\n [eapply H|..]; try reflexivity.\n\nLtac is_applied_function TARGET :=\n match TARGET with\n | ?f ?x =>\n idtac\n | _ => fail\n end\n.\n\nLtac has_inside_strict A B :=\n match A with\n | context[B] => tryif (check_equal A B) then fail else idtac\n | _ => fail\n end\n.\n\nLtac is_inside_others_body TARGET :=\n tryif (repeat multimatch goal with\n | [ |- context[?f ?x] ] =>\n (* idtac f; idtac x; *)\n tryif (has_inside_strict x TARGET)\n then fail 2\n else fail\n end)\n then fail\n else idtac\n.\n\nLtac on_leftest_function TAC :=\n (* repeat *)\n multimatch goal with\n | [ |- context[?f ?x] ] =>\n tryif (is_applied_function f)\n then fail\n else\n tryif (is_inside_others_body f)\n then fail\n else TAC f\n (* else TAC constr:(f) *)\n (* TODO: What is the difference? *)\n end\n.\n(* TODO: more cannonical way to get leftest function? *)\n(* I tried match reverse but it was not good *)\n(* TODO: I want to define \"get_leftest_function\" *)\n(* TODO: try tactic notation ? *)\n\nLtac leftest_rpapply H :=\n on_leftest_function ltac:(fun f =>\n (idtac f; first\n (* TODO: why rewrite \"with\" doesn't work? *)\n [ erewrite (f_equal8 f)\n | erewrite (f_equal7 f)\n | erewrite (f_equal6 f)\n | erewrite (f_equal5 f)\n | erewrite (f_equal4 f)\n | erewrite (f_equal3 f)\n | erewrite (f_equal2 f)\n | erewrite (f_equal f) | fail]); [ eapply H | .. ]; try reflexivity)\n.\n\n\n\n\n\nLtac is_type x :=\n match type of x with\n | Type => idtac\n | Set => idtac\n | Prop => idtac (* TODO: needed? *)\n | _ => fail\n end.\n\nLtac is_term_applied_function TARGET :=\n match TARGET with\n | ?f ?x =>\n tryif (is_type x) then fail else idtac\n | _ => fail\n end\n.\n\nLtac on_leftest_function_with_type TAC :=\n (* repeat *)\n multimatch goal with\n | [ |- context[?f ?x] ] =>\n tryif (is_term_applied_function f)\n then fail\n else\n tryif (is_inside_others_body f)\n then fail\n else TAC f\n end\n.\n\nLtac rpapply H :=\n on_leftest_function_with_type ltac:(fun f =>\n (idtac f; first\n (* TODO: why rewrite \"with\" doesn't work? *)\n [ erewrite (f_equal8 f)\n | erewrite (f_equal7 f)\n | erewrite (f_equal6 f)\n | erewrite (f_equal5 f)\n | erewrite (f_equal4 f)\n | erewrite (f_equal3 f)\n | erewrite (f_equal2 f)\n | erewrite (f_equal f) | fail]); [ eapply H | .. ]; try reflexivity)\n.\n\n\n\n(* it may run infinite loop *)\nLtac all TAC :=\n repeat multimatch goal with\n | H: _ |- _ => TAC H\n end;\n try TAC\n.\n\nLtac fold_in x H := fold x in H; fold x.\n\nLtac fold_all x := all ltac:(fold_in x).\n\nLtac clears x :=\n repeat match goal with\n | H: context[x] |- _ => clear H\n | |- context[x] => fail 2 \"It appears in the goal!\"\n end\n.\n\n\n\nLtac hide_goal :=\n match goal with\n | [ |- ?G ] => let name := fresh \"HIDDEN_GOAL\" in\n set (name := G); replace G with name by reflexivity\n (* ; move name at top <---- it breaks \"unhide (hide X) = X\". User may do it manually *)\n end.\nLtac unhide_goal :=\n match goal with\n | [ |- ?G ] => subst G\n end.\nLtac is_local_definition X :=\n hide_goal;\n tryif (unfold X)\n then (unhide_goal)\n else (unhide_goal; fail)\n.\nLtac negate TAC := tryif TAC then fail else idtac.\nLtac clear_unused :=\n repeat multimatch goal with\n | [H: ?T |- _] =>\n negate ltac:(is_local_definition H);\n match (type of T) with\n | Prop => idtac\n | _ => try clear H\n end\n end\n.\nGoal let x := 0 in forall n: nat, False.\nProof.\n intros.\n clear_unused.\nAbort.\n\n(* TODO: Currently I use \"is_local_definition\" filter, but it may replaced with checking if it is Prop *)\nLtac clear_tautology :=\n repeat multimatch goal with\n | [H: ?A = ?B, H2: ?B = ?A |- _] => clear H2\n (* | [H: True |- _] => clear H *) (* clear_universal_truth takes care of this now *)\n | [H: ?X, H2: ?X |- _] =>\n negate ltac:(is_local_definition H2);\n clear H2\n (* | [H: ?A = ?A |- _] => clear H *) (* clear_universal_truth takes care of this now *)\n end\n.\n\nLtac clear_reducible_truth :=\n let smart_tac := ss in\n repeat multimatch goal with\n | [H: ?P |- _ ] =>\n match (type of P) with\n | Prop =>\n let temp := fresh \"temp\" in\n tryif assert(temp: P) by (clear H; smart_tac)\n (* check if it is reducible from other premises *)\n then clear temp; clear H\n else idtac\n | _ => idtac\n end\n end\n.\n\nLtac clear_universal_truth :=\n let smart_tac := ss in\n repeat multimatch goal with\n | [H: ?P |- _ ] =>\n match (type of P) with\n | Prop =>\n let temp := fresh \"temp\" in\n tryif assert(temp: P) by (all clear; smart_tac)\n (* check if it is reducible without any premise *)\n then clear temp; clear H\n else idtac\n | _ => idtac\n end\n end\n.\n\nLtac clear_tac := repeat (clear_unused; clear_tautology; clear_universal_truth).\n\nLtac des_ifs_safe_aux TAC :=\n TAC;\n repeat\n multimatch goal with\n | |- context[match ?x with _ => _ end] =>\n match (type of x) with\n | { _ } + { _ } => destruct x; TAC; []\n | _ => let Heq := fresh \"Heq\" in destruct x as [] eqn: Heq; TAC; []\n end\n | H: context[ match ?x with _ => _ end ] |- _ =>\n match (type of x) with\n | { _ } + { _ } => destruct x; TAC; []\n | _ => let Heq := fresh \"Heq\" in destruct x as [] eqn: Heq; TAC; []\n end\n end.\nTactic Notation \"des_ifs_safe\" := des_ifs_safe_aux clarify.\nTactic Notation \"des_ifs_safe\" tactic(TAC) := des_ifs_safe_aux TAC.\n\nLtac abstr_aux x var_name :=\n let hyp_name := fresh \"abstr_hyp_name\" in\n remember x as var_name eqn:hyp_name; clear hyp_name\n.\n\nTactic Notation \"abstr\" constr(H) := let var_name := fresh \"abstr_var_name\" in abstr_aux H var_name.\nTactic Notation \"abstr\" constr(H) ident(var_name) := abstr_aux H var_name.\n\nHint Rewrite\n andb_true_iff andb_false_iff\n orb_true_iff orb_false_iff\n negb_true_iff negb_false_iff\n\n andb_true_r andb_true_l andb_false_r andb_false_l\n orb_true_r orb_true_l orb_false_r orb_false_l\n negb_andb negb_orb negb_involutive\n : simpl_bool.\n\nLtac simpl_bool := unfold Datatypes.is_true; unfold is_true; autorewrite with simpl_bool in *.\n\nLtac des_safe_aux TAC :=\n TAC;\n repeat (des1; TAC; [])\n.\n\nTactic Notation \"des_safe\" := des_safe_aux clarify.\nTactic Notation \"des_safe\" tactic(TAC) := des_safe_aux TAC.\n\nDefinition admit (excuse: String.string) {T: Type} : T. Admitted.\nTactic Notation \"admit\" constr(excuse) := idtac excuse; exact (admit excuse).\n\n(* Copied from SoftwareFoundations - LibTactics.v *)\n(* ---------------------------------------------------------------------- *)\n(** ** Generalization *)\n\n(** [gen X1 .. XN] is a shorthand for calling [generalize dependent]\n successively on variables [XN]...[X1]. Note that the variables\n are generalized in reverse order, following the convention of\n the [generalize] tactic: it means that [X1] will be the first\n quantified variable in the resulting goal. *)\n\nTactic Notation \"gen\" ident(X1) :=\n generalize dependent X1.\nTactic Notation \"gen\" ident(X1) ident(X2) :=\n gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) :=\n gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) :=\n gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5) :=\n gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5)\n ident(X6) :=\n gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5)\n ident(X6) ident(X7) :=\n gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5)\n ident(X6) ident(X7) ident(X8) :=\n gen X8; gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5)\n ident(X6) ident(X7) ident(X8) ident(X9) :=\n gen X9; gen X8; gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\nTactic Notation \"gen\" ident(X1) ident(X2) ident(X3) ident(X4) ident(X5)\n ident(X6) ident(X7) ident(X8) ident(X9) ident(X10) :=\n gen X10; gen X9; gen X8; gen X7; gen X6; gen X5; gen X4; gen X3; gen X2; gen X1.\n\n(* ---------------------------------------------------------------------- *)\n\nLtac exists_prop PROP :=\n tryif\n (repeat multimatch goal with\n | [H: PROP |- _ ] => (* idtac \"Found!\"; idtac H; *) fail 2\n end)\n then fail\n else idtac\n.\n\nLtac propagate_eq :=\n repeat (multimatch goal with\n | [H1: ?A = ?B, H2: ?B = ?C |- _ ] =>\n tryif (check_equal A C)\n then fail\n else\n tryif (exists_prop (A = C) + exists_prop (C = A))\n then idtac\n else\n let name := fresh \"EQ_CLOSURE_TAC\" in\n hexploit eq_trans; [exact H1|exact H2|]; intro name\n | [H1: ?B = ?A, H2: ?B = ?C |- _ ] =>\n tryif (check_equal A C)\n then fail\n else\n tryif (exists_prop (A = C) + exists_prop (C = A))\n then idtac\n else\n let name := fresh \"EQ_CLOSURE_TAC\" in\n hexploit eq_trans; [exact (eq_sym H1)|exact H2|]; intro name\n end)\n.\n\n(* get equality's transitive closure *)\n(* TODO: it checks equality too naive way; \"(0, 1).fst != 0\" here. *)\nLtac eq_closure_tac :=\n repeat (propagate_eq; clarify); clear_tac\n.\n\nLtac rev_all TAC :=\n repeat multimatch reverse goal with\n | H: _ |- _ => TAC H\n end;\n try TAC\n.\n\n(* Adapted from CompCert's Coqlib *)\nDefinition proj_sumbool (P Q: Prop) (pq: {P} + {Q}): bool := if pq then true else false.\nCoercion proj_sumbool: sumbool >-> bool.\n\nLemma proj_sumbool_true\n P Q\n (pq: {P} + {Q})\n (PROJ: proj_sumbool pq = true)\n :\n P\n.\nProof. destruct pq; ss. Qed.\n\nLemma proj_sumbool_is_true\n P\n (pq: {P} + {~P})\n (p: P)\n :\n proj_sumbool pq = true\n.\nProof. destruct pq; ss. Qed.\n\nLemma proj_sumbool_false\n P Q\n (pq: {P} + {Q})\n (FALSE: proj_sumbool pq = false)\n :\n Q\n.\nProof. destruct pq; ss. Qed.\n\nLemma proj_sumbool_is_false\n P\n (a: {P} + {~ P})\n (FALSE: ~ P)\n :\n proj_sumbool a = false\n.\nProof. unfold proj_sumbool. case a; tauto. Qed.\n\nLtac des_sumbool :=\n repeat\n (unfold Datatypes.is_true, is_true in *;\n match goal with\n | [ H: proj_sumbool ?x = true |- _ ] => apply proj_sumbool_true in H\n | [ H: proj_sumbool ?x = false |- _ ] => apply proj_sumbool_false in H\n | [ H: true = proj_sumbool ?x |- _ ] => symmetry in H; apply proj_sumbool_true in H\n | [ H: false = proj_sumbool ?x |- _ ] => symmetry in H; apply proj_sumbool_false in H\n\n | [ |- proj_sumbool ?x = true ] => apply proj_sumbool_is_true\n | [ |- proj_sumbool ?x = false ] => apply proj_sumbool_is_false\n | [ |- true = proj_sumbool ?x ] => symmetry; apply proj_sumbool_is_true\n | [ |- false = proj_sumbool ?x ] => symmetry; apply proj_sumbool_is_false\n end)\n.\n\nFixpoint update A (la: list A) (idx: nat) (a: A): (list A) :=\n match idx with\n | O =>\n match la with\n | hd :: tl => a :: tl\n | _ => la\n end\n | S midx =>\n match la with\n | hd :: tl => hd :: (update tl midx a)\n | _ => la\n end\n end\n.\n\nLemma update_spec\n A (la: list A) idx a\n :\n forall n (LT: (n < List.length la)%nat),\n <>.\nProof.\n ginduction la; ii; ss.\n { omega. }\n destruct n; ss.\n { des_ifs; ss. }\n destruct idx; ss.\n exploit (IHla idx a0 n); eauto. { omega. }\nQed.\n\nFixpoint update_err A (la: list A) (idx: nat) (a: A): option (list A) :=\n match idx with\n | O =>\n match la with\n | hd :: tl => Some (a :: tl)\n | _ => None\n end\n | S midx =>\n match la with\n | hd :: tl =>\n match (update_err tl midx a) with\n | Some tl => Some (hd :: tl)\n | _ => None\n end\n | _ => None\n end\n end\n.\n", "meta": {"author": "snu-sf", "repo": "HafniumCore", "sha": "b70a56c38938ce4900f8400f3420da47a94d32b5", "save_path": "github-repos/coq/snu-sf-HafniumCore", "path": "github-repos/coq/snu-sf-HafniumCore/HafniumCore-b70a56c38938ce4900f8400f3420da47a94d32b5/lib/sflib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.1259227631950178, "lm_q1q2_score": 0.0532029510785045}} {"text": "(* -*- coq-prog-args: (\"-nois\") -*- *)\nDelimit Scope type_scope with type.\nDelimit Scope function_scope with function.\n\nBind Scope type_scope with Sortclass.\nBind Scope function_scope with Funclass.\n\nReserved Notation \"x -> y\" (at level 99, right associativity, y at level 200).\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\n\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n fun x : A => g (f x).\n\nNotation \" g ∘ f \" := (compose g f)\n (at level 40, left associativity) : function_scope.\n\nFail Check (fun x => x) ∘ (fun x => x). (* this [Check] should fail, as [function_scope] is not opened *)\nCheck compose ((fun x => x) ∘ (fun x => x)) (fun x => x). (* this check should succeed, as [function_scope] should be automatically bound in the arugments to [compose] *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/3080.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10970577969958141, "lm_q1q2_score": 0.05313929481655552}} {"text": "(** * Tutorial for Mtac2 *)\n(** Author: Beta Ziliani *)\n(** with fixes from Michael Soegtrop *)\n\n(** * Introduction\n\nMtac2 is a typechecked language for proof automation. In its core, it\nconsists of a monadic type [M A] for a type [A], which is interpreted\nvia a tactic [mrun]. The best way of understanding the type [M A] is\nas _maybe_ [A], so, for instance, a function of type [M nat] _may_\nreturn a natural number. It can also fail or loop forever, but it can\nnever produce a value of a different type (that is, the interpreter is\nsound). We call functions of type [M A] _Mtactics_, to distinguish\nthem from the usual tactics provided by Coq. *)\n\n(** One of the key aspects of Mtac2 is that it subsumes Gallina, the\nlanguage of Coq, and it inherits from Coq the beta delta iota zeta\nreduction rules. This makes programming tactics very pleasant, since\ndevelopers only need to learn the new features and their semantics,\nsince the rest is _exactly the same_. These new features are, among\nothers:\n\n- Exceptions,\n- Unbounded fixpoints,\n- Unification,\n- Fresh name generation,\n- Abstraction of variables.\n*)\n\n(** In this tutorial we illustrate these features, building up from\nsimple examples. In order to execute the code in this file you will\nneed to install our plugin. For details, follow this link: #Mtac2 home page#\n*)\n\n(** * Simple examples *)\n\n(** To begin working with the new language we need to import the [M]\ntype. *)\nRequire Import Mtac2.Mtac2.\n\n(** In Mtac2 there are two major modules, in our case we are going to\nuse the module with basic operators, called also [M]. We import it alongside with its notations: *)\nImport M.\nImport M.notations.\n\n(** In addition, we import a couple of modules from the standard\nlibrary that we are going to use in some examples. *)\n\nRequire Import Arith.Arith Arith.Div2.\nRequire Import Lists.List.\nRequire Import Strings.String.\n\nSet Implicit Arguments.\nNotation \"x == y\" := (beq_nat x y) (at level 60).\n\n(** We start by showing the standard _unit_ and _bind_ operators,\nwhich in our language are called [ret] (for return) and [bind]. The\nlanguage also defines the standard notation [x <- a; b] for\n[bind]. This example computes the value [1] by passing the result of\ncomputing [0] to the successor.\n*)\n\nDefinition produces_a_value :=\n x <- ret 0;\n ret (S x).\n\n(** We check the type of the definition. It has type [M nat]. *)\n\nCheck produces_a_value.\n\n(** There are different ways to execute it. The first one is to call\nthe tactic [mrun]. *)\nDefinition the_value_tactic : nat.\nProof. mrun produces_a_value. Defined.\n\nPrint the_value_tactic.\n\n(** The result should be [the_value = 1 : nat]. As you can see, [mrun\nproduces_a_value] solved the goal with the result of computing the\ncode in [produces_a_value]. *)\n\n(** Another option is to use the [MProof] command, which implicitly\nappends an [mrun] at each line. *)\nDefinition the_value_mproof : nat.\nMProof. produces_a_value. Defined.\n\n(** Finally, it is also possible to use the Ltac keyword [ltac:] to\nexecute the tactic. One advantage is that we can bake it into regular\nGallina terms. In our case, this means that we do not need to annotate\nthe type of the definition. *)\nDefinition the_value_ltac := ltac:(mrun produces_a_value).\n\n(** Throughout the tutorial we are going to use this last one a lot,\nso we better make some nice notation: *)\n\nNotation \"! t\" := ltac:(mrun t) (at level 200).\n\n(** ** Exceptions *)\n(** The monad includes exceptions, like the following silly example\nillustrates. [Exception]s are constructed with the constructor\n[exception]. In order to make distinguishable exceptions we make them\nopaque, sealing the definition with the [Qed] word. *)\n\nDefinition AnException : Exception.\n exact exception.\nQed.\n\n(* They can be parametrized as well. *)\n\nDefinition MyException (s : string) : Exception.\n exact exception.\nQed.\n\n(** Note how they are equal to [exception], but we can still\ndifferentiate them. *)\n\nDefinition test_ex e :=\n mtry raise e\n with\n | AnException => ret \"\"%string\n | MyException \"hello\"%string => ret \"world\"%string\n | [? s] MyException s => ret s\n end.\n\nDefinition empty_string := ! test_ex AnException.\nDefinition world_string := ! test_ex (MyException \"hello\"%string).\nDefinition other_string := ! test_ex (MyException \"other\"%string).\n\nPrint empty_string.\nPrint world_string.\nPrint other_string.\n\n(** Results should be the empty string, the string \"world\" and the\nstring \"other\" respectively. *)\n\n(** If an exception is not caught, then we get a meaningful error.\nThe [Fail] command below will show the exception thrown by the code: *)\n\nFail Check (! raise (MyException \"This is printed out\"%string) : M nat).\n(** (We need to provide a type to the expression because [ltac:]\ndoesn't like open terms.) *)\n\n\n(** ** Unbounded fixpoints *)\n\n(** Fixpoints in Coq should terminate to ensure soundness. Checking\ntermination is hard, so Coq relies on a pretty restrictive syntactic\ncondition to ensure termination. We allow non-termination in our\nlanguage via an unbounded fixpoint, which we call [mfix].\nFor instance, an endless loop can be written simply as: *)\n\nDefinition endless_loop := mfix1 f (n : nat) : M False := f n.\n\n(** In this definition we decided to add the type annotation\n[M False], since otherwise it is impossible for the type inference\nmechanism to guess the type. It is important to note that the body of\n[mfix] should always be of type [M]. *)\n\n(** Uncomment the code below and execute it: it will loop forever! You\nwill have to interrupt the proof assistant (C-c C-c in Emacs). *)\n\n(**[\nCheck (! endless_loop 0).\n]*)\n\n(** *** Endless loop... Is it still safe? *)\n\n(** The key to understanding why it is perfectly safe to allow for\nsuch effects is to notice that [mrun] is not a function living in the\nkernel typechecker of Coq. That is, for [t] of type [M A], [mrun t]\nconstructs a witness for [A] only if it's safe to do so, but _it\nitself is not a witness for [A]_. Take as example the definitions we\nconstructed so far: we used [mrun] but when we printed them we saw no\n[mrun] in their proof terms.\n\nAs an exercise, we can try to break soundness of Coq by constructing an\n element of type [False] without any further hypothesis. Take the\n function [endless_loop] above, which has type [nat -> M False]. To\n get an element of type [False] we have to execute it through [mrun] as\n in the commented code. Since it will not terminate, [mrun\n (endless_loop 0)] doesn't produce an offending witness. *)\n\n(** *** Constructing Collatz sequences *)\n\n(** To show the use of this unbounded fixpoint we define a function\ncomputing the #Collatz\nsequence#, which cannot be defined in vanilla Coq since its\ntermination is a conjecture. *)\n\n(* begin hide *)\nFixpoint is_even n :=\n match n with\n 0 => true\n | S n' => negb (is_even n')\n end.\n(* end hide *)\n\nDefinition collatz :=\n mfix1 f (n : nat) : M (list nat) :=\n let n := rcbv n in\n let rest :=\n if n == 1 then\n ret nil\n else if is_even n then\n f (div2 n)\n else\n f (3 * n + 1)\n in\n s <- rest;\n ret (n :: s).\n\n(** We perform reduction on the natural number *)\n\n(** We try it with the value [6]. *)\nDefinition the_sequence_6 := ! (collatz 6).\n\nPrint the_sequence_6.\n(** Result: [(6 :: 3 :: 10 :: 5 :: 16 :: 8 :: 4 :: 2 :: 1 :: nil) : list nat] *)\n\n\n(** ** Unification match *)\n\n(** Mtac2 provides a powerful construct: the unification\nmatch. Unlike the native Coq pattern matching, the unification match\nlet us specify any term as a pattern, even patterns containing\nvariables bound in the context.\n\nFor instance, the code below shows a function that searches for an\nelement in a list. *)\n\nMtac Do New Exception NotFound.\n(** (This is just a handy way of declaring an exception without parameters.) *)\n\nDefinition inlist A (x : A) :=\n mfix1 f (s : list A) : M (In x s) :=\n mmatch s as s' return M (In x s') with\n | [? s'] (x :: s') => ret (in_eq _ _)\n | [? y s'] (y :: s') =>\n r <- f s';\n ret (in_cons y _ _ r)\n | _ => raise NotFound\n end.\n\nCheck inlist.\n\n(** We also depart from the standard notation for patterns: since they\nmay now refer to variables in the context, we need to specify a list\nof pattern variables, like [[? s']] in the first pattern. All the\nvariables not included in this list should be bound by the context,\nlike [x] in the same pattern, which is bound to the argument of the\ndefinition. That is, this pattern matches a list containing the\nelement [x] in the head.\n*)\n\n\n(** So far we have constructed the proof terms directly, without using\nthe interactive mode of Coq. We can use any standard tactic ([apply],\n[refine], [exact], [set], ...) with [run], although not all of them\nare suitable if we want to avoid writing inferable arguments. For\ninstance, if we have to prove a goal of the form [In x s] for some\nlist [s] and some element [x], then we would like to use [mrun (inlist\n_ _)], that is, without specifying the arguments. This will help us\nbuild more robust proof scripts, since tomorrow we may replace [x] by\nsome other element in the list and still get a valid proof script. *)\n\nExample x_in_zyx (x y z : nat) : In x (z :: y :: x :: nil).\nProof.\n mrun (inlist _ _).\nQed.\n\n(** One tricky thing about our nice notation [!] is that it doesn't\nwork for open terms: *)\n\nFail Example z_in_xyz (x y z : nat) : In z (x :: y :: z :: nil)\n := ! (inlist _ _).\n\n(** We can still call it with the [ltac:] construct directly: *)\nExample z_in_xyz (x y z : nat) : In z (x :: y :: z :: nil)\n := ltac:(mrun (inlist _ _)).\n\n(** An alternative is to use [eval], which is similar to [mrun],\nexcept that it performs the execution of the Mtactic after the type\ninference mechanism of Coq has done its job: *)\n\nExample y_in_zyx (x y z : nat) : In y (z :: y :: x :: nil)\n := eval (inlist _ _).\n\n(** Behinds the scene, [eval] uses the typeclass mechanism. As a\ndrawback, it leaves the tactic code in the proof term: *)\nPrint y_in_zyx. (** Note the call to [inlist] showing up here. *)\n\n(** *** Interaction with [Program] *)\n\n(** When writing tactics, we can use [Program] to avoid having to\nwrite the proof terms ourselves. As an example, we will extend our\n[inlist] function to handle list concatenation in order to handle more\ncases and get shorter proof terms. By using [Program], Coq will ask us\nto provide (interactively) the proof terms for the cases where there is\na hole ([_]) and it cannot guess what to fill in that hole.\n*)\n\nProgram\nDefinition inlist' A (x : A) :=\n mfix1 f (s : list A) : M (In x s) :=\n mmatch s as s' return M (In x s') with\n | [? l r] l ++ r =>\n mtry\n il <- f l;\n ret _\n with _ =>\n ir <- f r;\n ret _\n end\n | [? s'] (x :: s') => ret (in_eq _ _)\n | [? y s'] (y :: s') =>\n r <- f s';\n ret (in_cons y _ _ r)\n | _ => raise NotFound\n end.\nNext Obligation.\nintros; apply in_or_app; left; assumption.\nQed.\nNext Obligation.\nintros; apply in_or_app; right; assumption.\nQed.\n\n(** If the list is a concatenation of two lists [l] and [r], we first\ntry to search for the element on [l] and, if it fails, on [r]. Notice\nthat the pattern is not a constructor, but the application of the\nfunction [++] to two lists. As mentioned before, we can use _any_ Coq term\nas a pattern! It is important to make this case the first case of the\nmatch, as the unification of the scrutinee with the pattern takes into\naccount beta delta iota zeta reductions. That is, if the concatenation case were\nput third in the match, then the list [(x :: nil) ++ (z :: nil)] will\nbe matched against the pattern [(x :: s')], by reducing it to [(x :: z\n:: nil)]. *)\n\n(** One problem with [Program] is that it tends to generate\nunnecessarily big proof terms. *)\n\nPrint inlist'.\n\n(** Let's look at the proof terms generated in the obligations and plug\nthose terms into the holes. *)\n\nPrint inlist'_obligation_1.\nPrint inlist'_obligation_2.\n\n(** The important bits are [in_or_app l r x (or_introl H)] and\n[in_or_app l r x (or_intror H)]. We write our function again filling\nin the holes with these two terms. *)\n\nDefinition inlist'' A (x : A) :=\n mfix1 f (s : list A) : M (In x s) :=\n mmatch s as s' return M (In x s') with\n | [? l r] l ++ r =>\n mtry\n il <- f l;\n ret (in_or_app l r x (or_introl il))\n with _ =>\n ir <- f r;\n ret (in_or_app l r x (or_intror ir))\n end\n | [? s'] (x :: s') => ret (in_eq _ _)\n | [? y s'] (y :: s') =>\n r <- f s';\n ret (in_cons y _ _ r)\n | _ => raise NotFound\n end.\n\n(** Let's prove an example using the three functions just created to\ncompare the proof terms they generate.\n*)\n\nExample ex_inlist (x y z : nat) : In x ((y :: z :: nil)++(x :: z :: nil)).\nProof.\n mrun (inlist _ _).\nQed.\n\nExample ex_inlist' (x y z : nat) : In x ((y :: z :: nil)++(x :: z :: nil)).\nProof.\n mrun (inlist' _ _).\nQed.\n\nExample ex_inlist'' (x y z : nat) : In x ((y :: z :: nil)++(x :: z :: nil)).\nProof.\n mrun (inlist'' _ _).\nQed.\n\nPrint ex_inlist.\nPrint ex_inlist'.\nPrint ex_inlist''.\n\n(** Inspect the result. The last example has the shortest proof term. *)\n\n(** * A simple tautology prover *)\n\n(** We show by example some useful constructs for dealing with Higher\nOrder Abstract Syntax (HOAS). As the driving example we will write a\nrudimentary tautology prover similar to that found in VeriML [[1]] and\nCPDT [[2]]. Compared to VeriML, our approach has the benefit that it\ndoesn't require any special context treatment, since for us a context is\nnothing more than a Coq list. And unlike in the Ltac version\npresented in [[2]], we have meaningful types to prevent ourselves from\nshooting ourselves in the foot.\n*)\n\n(** ** Warming the engine: a simple propositional prover *)\n\n(** We start with a very simple propositional prover. It considers\nonly three cases:\n\n- The proposition is [True]. In this case, it returns the trivial proof [I].\n- The proposition is a conjunction of [p1] and [p2]. In this case, it proves both propositions and returns the introduction form of the conjunction.\n- The proposition is a disjunction of [p1] and [p2]. In this case, it tries to prove the proposition [p1], and if it fails it tries to prove the proposition [p2]. The corresponding introduction form of the disjunction is returned.\n- In any other case, it raises an exception, since no proof could be found.\n*)\n\nDefinition simpl_prop_auto :=\n mfix1 f (p : Prop) : M p :=\n mmatch p as p' return M p' with\n | True => ret I\n | [? p1 p2 ] p1 /\\ p2 =>\n r1 <- f p1 ;\n r2 <- f p2 ;\n ret (conj r1 r2)\n | [? p1 p2] p1 \\/ p2 =>\n mtry\n r1 <- f p1 ;\n ret (or_introl r1)\n with _ =>\n r2 <- f p2 ;\n ret (or_intror r2)\n end\n | _ => raise NotFound\n end.\n\n(** Given this definition we can easily discharge the following example. *)\nExample ex1 : True /\\ (False \\/ True).\nProof.\n mrun (simpl_prop_auto _).\nQed.\n\nPrint ex1.\n\n(** The proof term is exactly what we would have written by hand:\n\n [ex1 = conj I (or_intror I)] *)\n\n(** ** Adding a context *)\n\n(** Our previous function is very limited since it cannot prove\ntautologies as simple as [P -> P]. To handle implications we need a\nlist of hypotheses where we can search for a proof of the atom we are\nconsidering. We create a record type containing a proposition and a\nwitness for the proposition. *)\n\nRecord dyn := Dyn { prop : Prop ; elem : prop }.\n\n(** We will need to search a list of [dyn]s to find a witness for some\nproposition. The [search] function below is similar to the [inlist] above,\nbut keying on the [prop] projector of the record. We have to prepend [Program]\nbecause it calls a more agressive typechecker, otherwise it fails to notice\nthat the element in the body of the first case should return a [P]. *)\n\nDefinition search (P : Prop) :=\n mfix1 f (s:list dyn) : M P :=\n mmatch s with\n | [? (x:P) s'] (Dyn x) :: s' => ret x\n | [? d s'] d :: s' => f s'\n | _ => raise NotFound\n end.\n\n(** The proposition in the [Dyn] constructor is implicit, since it can\nbe inferred from the element, so we write [Dyn x] instead of [Dyn A\nx]. *)\n\n(** The tautology prover takes a context [c] (e.g., a list of [dyn]s)\nand a proposition. The first three cases are the same as before. *)\n\nDefinition prop_auto' :=\n mfix2 f (c : list dyn) (p : Prop) : M p :=\n mmatch p in Prop as p' return M p' with\n | True => ret I\n | [? p1 p2 ] p1 /\\ p2 =>\n r1 <- f c p1 ;\n r2 <- f c p2 ;\n ret (conj r1 r2)\n | [? p1 p2] p1 \\/ p2 =>\n mtry\n r1 <- f c p1 ;\n ret (or_introl r1)\n with _ =>\n r2 <- f c p2 ;\n ret (or_intror r2)\n end\n | [? (p1 p2 : Prop)] p1 -> p2 =>\n \\nu x:p1,\n r <- f (Dyn x :: c) p2;\n abs_fun x r\n | [? p'] p' : Prop => search p' c\n end.\n\n\n(** Let's look at the new case for handling the implication. We need\n to return an element of type [M (p1 -> p2)], that is, _maybe_ a\n function from [p1] to [p2]. Of course, we cannot simply write\n\n[ret (fun x:p1 => f (Dyn x :: c) p2)]\n\nsince this code has type [M (p1 -> M p2)] which is not what we\nwant. Instead, we use two new operators: [nu] and [abs_fun]. The first one\nis analogous to the nu operator in [[3]] and [[4]], but a bit more low-level.\nIts type is the following: *)\n\nAbout nu.\n\n(* That is: [forall {A B}, name -> moption -> (A -> M B) -> M B]. [name] is a\nstructure to control the naming of the variable to be introduced, and\n[moption] is a universe polymorphic [option] type. The effect of\ncomputing [nu n None (fun x=>b)], where [b : T B], is the result of\nexecuting [b], replacing any occurrence of [x] with a fresh\n_parameter_ [a] named after [n]. If the execution results in a term\n[ret t] for some [t] with [a] not appearing free in it, then the value\n[ret t] is used as result for [nu n None (fun x => b)]. Otherwise, a\nfailure is raised. Intuitively, the idea is that it is safe to execute\nthe body of a function as long as it doesn't get stuck (i.e., it\nshouldn't inspect its argument), and the returning value doesn't\nreturn the argument (i.e., it shouldn't violate the context).\n\nThe name can be generated fresh (this is what the notation [\\nu]\ndoes); it can be named with a specific name (a string), in which case\nit shouldn't have a name clash with other variable in scope; or it can\nbe generated fresh from a given string (for instance, with \"H\" it will\ngenerate H0, H1, ...).\n\n[abs_fun] abstracts over parameters created by [nu]. It has type [forall A\nP (x : A), P x -> M (forall x, P x)] where [A] and [P] are left\nimplicit. If [a] is a parameter created by [nu] and [t] is a term with\n[a] appearing free in it, then [abs_fun a t] is replaced by [ret (fun\nx=>r)], where [r] is [t] with [a] replaced by [x]. That is, [a] is\nabstracted from [t].\n\nComing back to the implication case, we use [nu] to create a parameter\n[x] as a witness for [p1]. Then we add it to the list of hypothesis to\nprove [p2] and get the result [r], which may refer to [x]. Therefore,\nwe use [abs_fun x r] to abstract [x] from the result. We encourage the\nreader to check that the type of the whole expression returned in the\nimplication case indeed has type [M (p1 -> p2)].\n\nFinally, we changed the last case of the algorithm: instead of\nthrowing an error, now we search for a witness for the proposition in\nthe list using the [search] function defined before.\n*)\n\n(** We create a definition to avoid passing the empty list *)\nDefinition prop_auto {P} :=\n @prop_auto' nil P.\n\n(** We can now easily prove this tautology. *)\nExample ex_with_implication (p q : Prop) : p -> q -> p /\\ q.\nProof.\n mrun prop_auto.\nQed.\n\n(** Again, the proof term generated is exactly what we would expect\nfor such a proof. *)\n\nPrint ex_with_implication.\n\n(** Result:\n[ex_with_implication = fun (p q : Prop) (H : p) (H0 : q) => conj H H0] *)\n\n(** * Getting first order *)\n\n(** We can generalize our algorithm very easily to deal with [forall] and\n[exists]. Below is the code, where the first four cases and the last one\nare the same as before. *)\n\nDefinition tauto' :=\n mfix2 f (c : list dyn) (p : Prop) : M p :=\n mmatch p as p' return M p' with\n | True => ret I\n | [? p1 p2] p1 /\\ p2 =>\n r1 <- f c p1 ;\n r2 <- f c p2 ;\n ret (conj r1 r2)\n | [? p1 p2] p1 \\/ p2 =>\n mtry\n r1 <- f c p1 ;\n ret (or_introl r1)\n with _ =>\n r2 <- f c p2 ;\n ret (or_intror r2)\n end\n | [? (p1 p2 : Prop)] p1 -> p2 =>\n \\nu x:p1,\n r <- f (Dyn x :: c) p2;\n abs_fun x r\n | [? A (q:A -> Prop)] (forall x:A, q x) =>\n \\nu x:A,\n r <- f c (q x);\n abs_fun x r\n | [? A (q:A -> Prop)] (exists x:A, q x) =>\n X <- evar A;\n r <- f c (q X) ;\n b <- is_evar X;\n if b then\n raise NotFound\n else\n ret (ex_intro q X r)\n | [? p'] p':Prop => search p' c\n end.\n\n(** The [forall] case is similar to the implication case from before but taking\ninto account the following:\n- The type of [x] is any type [A], not just [Prop].\n- The possible dependency of [x] in [q], the body of the [forall]. This dependency is marked by making [q] a function from [A] to [Prop]. The unification algorithm used to unify the pattern with the proposition [p] will take care of instantiating [q] with a function taking an element of type [A] and returning the body of the [forall].\n- The context is not extended.\n\nFor the existential case, we create a fresh meta-variable [X] via the\ncommand [evar], which takes a type (in this case [A]) and returns a\nnew meta-variable of that type. Then, we call the function recursively\nwith the body [q] of the existential, replacing the argument [x] with\n[X]. Hopefully, the result will instantiate [X] and we return this as\nthe witness for the existential. If not, that is, if [X] is still\nan uninstantiated meta-variable, then we raise an error.\n\nAs before, we create a definition to avoid passing the empty list:\n*)\n\nDefinition tauto {P} :=\n @tauto' nil P.\n\n(** Here is an example to test [tauto]: *)\nExample ex_first_order (p q : nat -> Prop) :\n forall x, p x -> q x -> exists y, p y /\\ q y.\nProof.\n mrun tauto.\nQed.\n\n(** If we cannot instantiate an existential, then an error is thrown. *)\nExample ex_fail (p q : nat -> Prop) :\n exists y, p y /\\ q y.\nProof.\n Fail mrun tauto.\nAbort.\n\n(** Actually, we can omit the check for the existential and let the\nuser come up with the witness by itself. *)\n\n(** * Delayed execution via [eval] *)\n\n(** We mentioned brefly that with [eval] we can delay the execution of\nthe Mtactic in order to get arguments from the goal, and that we\nmust use it with care, as the proof term generated is bigger than with\n[mrun]. This said, [eval] is particularly useful when rewriting\nprocedures returning equalities. Here is an example using boolean\nequality of natural numbers. *)\n\nProgram Definition eq_nats :=\n mfix2 f (x : nat) (y : nat) : M (x == y = true) :=\n mmatch (x, y) with\n | (x, x) => [H] ret _\n | [? x1 x2] (x1 + x2, x2 + x1) => [H]\n ret _\n end.\nNext Obligation.\n inversion H.\n symmetry.\n apply beq_nat_refl.\nQed.\nNext Obligation.\n inversion H.\n rewrite beq_nat_true_iff.\n apply plus_comm.\nQed.\n(** Notice how we use the [[H]] notation after the right arrow in the\npattern. The name [H] will be instantiated with a proof of equality of\nthe scrutinee with the pattern, which we use to apply [inverstion] on\nit. Of course, we could (should!) avoid [Program] and write the proof\nterm directly, but that's unnecessary for illustrating the use of\n[eval] with [rewrite], the purpose of the section. *)\n\n(** We call the Mtactic with [eval]: *)\nExample plus_S n m : n + m == m + n = true /\\ m == m = true /\\ n == n = true.\nProof.\n rewrite !(eval (eq_nats _ _)). (** Notice how at each rewrite it picks the right terms. *)\n auto.\nQed.\n\n(** * Where now? *)\n\n(** After seeing the basics of the Mtac2 infrastructure, and until\nnewer documentation comes, you are invited to see the examples in the\nsame directory as this tutorial, and the theory files. Mtac2 comes\nwith a lot of different useful tools. And feel free to ask any\nquestion in the Zulip channel! [[6]] *)\n\n\n(** * References *)\n(** [[1]] VeriML: Typed Computation of Logical Terms inside a Language\nwith Effects. Antonis Stampoulis and Zhong Shao. In Proc. 2010 ACM\nSIGPLAN International Conference on Functional Programming (ICFP'10).\n\n[[2]] http://adam.chlipala.net/cpdt/\n\n[[3]] Aleksandar Nanevski. Meta-programming with names and\nnecessity. In Proceedings of the seventh ACM SIGPLAN international\nconference on Functional programming, ICFP'02, pages 206-217, New\nYork, NY, USA, 2002. ACM.\n\n[[4]] Carsten Schuermann, Adam Poswolsky, and Jeffrey Sarnat. The\nnabla-calculus. functional programming with higher-order encodings. In\nProceedings of the 7th international conference on Typed Lambda\nCalculi and Applications, TLCA'05, pages 339-353, Berlin, Heidelberg,\n2005. Springer-Verlag.\n\n[[5]] https://math-comp.github.io/mcb/\n\n[[6]] https://coq.zulipchat.com/#narrow/stream/254619-Mtac2\n*)\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/examples/basics_tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.1159607258918425, "lm_q1q2_score": 0.05300990551512995}} {"text": "(* Copyright (c) 2008-2012, 2015, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n * http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import List.\n\nRequire Import Cpdt.CpdtTactics.\n\nDefinition bad : unit := tt.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\n\n(**\n(if\n (string= default-directory \"/Users/ksk/project/cpdt-japanese/src/\")\n (setq coq-prog-name\n\t (ocaml-dir \"bin/coqtop\"))) (** %\\chapter{Infinite Data and Proofs}% *)\n*)\n(** %\\chapter{無限の大きさをもつデータと証明}% *)\n\n(**\n(**\nIn lazy functional programming languages like %\\index{Haskell}%Haskell, infinite data structures are everywhere%~\\cite{whyfp}%. Infinite lists and more exotic datatypes provide convenient abstractions for communication between parts of a program. Achieving similar convenience without infinite lazy structures would, in many cases, require acrobatic inversions of control flow. \n\n%\\index{laziness}%Laziness is easy to implement in Haskell, where all the definitions in a program may be thought of as mutually recursive. In such an unconstrained setting, it is easy to implement an infinite loop when you really meant to build an infinite list, where any finite prefix of the list should be forceable in finite time. Haskell programmers learn how to avoid such slip-ups. In Coq, such a laissez-faire policy is not good enough.\n\nWe spent some time in the last chapter discussing the %\\index{Curry-Howard correspondence}%Curry-Howard isomorphism, where proofs are identified with functional programs. In such a setting, infinite loops, intended or otherwise, are disastrous. If Coq allowed the full breadth of definitions that Haskell did, we could code up an infinite loop and use it to prove any proposition vacuously. That is, the addition of general recursion would make CIC _inconsistent_. For an arbitrary proposition [P], we could write:\n[[\nFixpoint bad (u : unit) : P := bad u.\n]]\n\nThis would leave us with [bad tt] as a proof of [P].\n\nThere are also algorithmic considerations that make universal termination very desirable. We have seen how tactics like [reflexivity] compare terms up to equivalence under computational rules. Calls to recursive, pattern-matching functions are simplified automatically, with no need for explicit proof steps. It would be very hard to hold onto that kind of benefit if it became possible to write non-terminating programs; we would be running smack into the halting problem.\n\nOne solution is to use types to contain the possibility of non-termination. For instance, we can create a \"non-termination monad,\" inside which we must write all of our general-recursive programs; several such approaches are surveyed in Chapter 7. This is a heavyweight solution, and so we would like to avoid it whenever possible.\n\nLuckily, Coq has special support for a class of lazy data structures that happens to contain most examples found in Haskell. That mechanism,%\\index{co-inductive types}% _co-inductive types_, is the subject of this chapter. *)\n*)\n\n(**\n%\\index{Haskell}%Haskellのような遅延評価を行う関数型プログラミング言語では,\n無限の大きさをもつデータ構造があらゆるところで扱われています%~\\cite{whyfp}%.\n無限リストなどの特殊なデータ構造は,\nプログラム内でのデータのやり取りを抽象的に捉えるためには便利なものです.\n遅延評価を伴う無限のデータ構造を使わずに同じような利便性を得るためには,\n制御フローを元にしてプログラムを記述するという巧妙な反転の仕組みが必要となるでしょう.\n\nHakellにおいて%\\index{遅延評価}%遅延評価を行うプログラムを実装するのは\n簡単です.\nこれは,プログラム内のすべての定義が相互再帰によって与えられていると考えることができるためです.\nこのように自由な関数定義が許されている設定では,\n本当に無限の大きさをもつリストを作るの際には無限ループになる式を書くだけですが,\nそのリストの先頭の有限個の要素だけが必要なら有限の時間で結果を得られるように注意する必要があります.\nHaskellプログラマはそういった点に気をつけながらプログラムを書く方法を学習します.\nCoqでは,関数やデータを定義する際にはこのような自由放任主義が通用しません.\n\n前の章でカリーハワード同型について時間をかけて説明してきたように,\n証明は関数型プログラムと見なすことができます.\nこの考えのもとでは,無限ループは,\nそれが意図的であってもそうでなくても,ひどい結果をもたらします.\nもしCoqがHaskellのような定義の柔軟さを許すならば,\n無限にループするプログラムを記述することができてしまい,\nそれによって任意の命題が証明できることになるでしょう.\nつまり,CICに一般再帰を追加すると「矛盾」が生じてしまうのです.\nたとえば,任意の命題 [P] に対して,\n次の再帰関数が定義できたとしましょう:\n[[\nFixpoint bad (u : unit) : P := bad u.\n]]\n\nこの関数を使えば [P] 型をもつ式 [bad tt] を作ることができるので,\n命題 [P] が証明できてしまいます.\n\nあらゆる入力に対する停止性が強く望まれるようなアルゴリズム的な配慮もあります.\nこれまで,[reflexivity] のようなタクティックがどのようにして項同士を比較し,\n計算規則のもとで等価性を判定するかを見てきました.\n明示的な証明ステップを経るまでもなく,\n再帰的でパターンマッチを利用した関数の呼び出しは自動的に簡約されます.\nそういった利点を維持しながら,停止しないプログラムも書けるようにするのは簡単ではありません.\nそこにはチューリング機械の停止性問題が立ちはだかることでしょう.\n\n1つの解決方法は,停止しない可能性があることを表すような型を使うことです.\nたとえば,「非停止モナド」を作ってその内側に一般再帰のプログラムを閉じ込めることも考えられます.この手法のいくつかは7章で解説しますが,非常に煩雑な方法なのでできれば避けたいところです.\n\n幸運なことにCoqには遅延データ構造のクラスが特別に用意されていて,\nHaskellで使われている多くの例はこのクラスに含まれています.\nこれが%\\index{余帰納型}%余帰納型と呼ばれる仕組みであり,本章の主題です.\n*)\n\n(**\n(** * Computing with Infinite Data *)\n*)\n(** * 無限の大きさをもつデータを使った計算 *)\n\n(**\n(** Let us begin with the most basic type of infinite data, _streams_, or lazy lists.%\\index{Vernacular commands!CoInductive}% *)\n*)\n(**\nまずは最も基本的な無限データである「ストリーム」(遅延リスト) を考えましょう.%\\index{Vernacular commands!CoInductive}%\n*)\n\nSection stream.\n Variable A : Type.\n\n CoInductive stream : Type :=\n | Cons : A -> stream -> stream.\nEnd stream.\n\n(* begin hide *)\n(* begin thide *)\nCoInductive evilStream := Nil.\n(* end thide *)\n(* end hide *)\n\n(**\n(** The definition is surprisingly simple. Starting from the definition of [list], we just need to change the keyword [Inductive] to [CoInductive]. We could have left a [Nil] constructor in our definition, but we will leave it out to force all of our streams to be infinite.\n\n How do we write down a stream constant? Obviously, simple application of constructors is not good enough, since we could only denote finite objects that way. Rather, whereas recursive definitions were necessary to _use_ values of recursive inductive types effectively, here we find that we need%\\index{co-recursive definitions}% _co-recursive definitions_ to _build_ values of co-inductive types effectively.\n\n We can define a stream consisting only of zeroes.%\\index{Vernacular commands!CoFixpoint}% *)\n*)\n(**\nこの定義は驚くほど単純です.\n[list]の定義の[Inductive]というキーワードを[CoInductive]に変えただけです.\n[Nil]構成子を定義に残すこともできましたが,\n無限の大きさをもつストリームしか表現できないようにするために外すことにします.\n\nストリーム型の値を書き下すにはどうすればよいでしょう?\n単純に構成子を適用していくだけでは有限の大きさのデータしか表現できないということは明らかです.\n(* より正確に言えば,*)\n再帰的な帰納型の値を有限時間で「消費」するために\n再帰的な定義を使うのと同じように,\n余帰納型の値を有限時間で「生産」するためには,\n%\\index{余再帰的定義}%余再帰的定義が必要になるということです.\n\n0しか含まないようなストリームは次のように定義できます.%\\index{Vernacular commands!CoFixpoint}% \n\n*)\n\nCoFixpoint zeroes : stream nat := Cons 0 zeroes.\n\n(* EX: Define a stream that alternates between [true] and [false]. *)\n(* begin thide *)\n\n(**\n(** We can also define a stream that alternates between [true] and [false]. *)\n*)\n(** [true]と[false]が交互に現れるストリームは次のように定義できます. *)\n\nCoFixpoint trues_falses : stream bool := Cons true falses_trues\nwith falses_trues : stream bool := Cons false trues_falses.\n(* end thide *)\n\n(**\n(** Co-inductive values are fair game as arguments to recursive functions, and we can use that fact to write a function to take a finite approximation of a stream. *)\n*)\n(** \n余帰納的な値を再帰的関数の引数として与えることにより,\nストリームに対する有限の近似を求める関数を定義することができます.\n*)\n\n(* EX: Define a function to calculate a finite approximation of a stream, to a particular length. *)\n(* begin thide *)\n\nFixpoint approx A (s : stream A) (n : nat) : list A :=\n match n with\n | O => nil\n | S n' =>\n match s with\n | Cons h t => h :: approx t n'\n end\n end.\n\nEval simpl in approx zeroes 10.\n(** %\\vspace{-.15in}% [[\n = 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: nil\n : list nat\n ]]\n *)\n\nEval simpl in approx trues_falses 10.\n(** %\\vspace{-.15in}% [[\n = true\n :: false\n :: true\n :: false\n :: true :: false :: true :: false :: true :: false :: nil\n : list bool\n ]]\n*)\n\n(* end thide *)\n\n(* begin hide *)\n(* begin thide *)\nDefinition looper := 0.\n(* end thide *)\n(* end hide *)\n\n(**\n(** So far, it looks like co-inductive types might be a magic bullet, allowing us to import all of the Haskeller's usual tricks. However, there are important restrictions that are dual to the restrictions on the use of inductive types. Fixpoints _consume_ values of inductive types, with restrictions on which _arguments_ may be passed in recursive calls. Dually, co-fixpoints _produce_ values of co-inductive types, with restrictions on what may be done with the _results_ of co-recursive calls.\n\nThe restriction for co-inductive types shows up as the%\\index{guardedness condition}% _guardedness condition_. First, consider this stream definition, which would be legal in Haskell.\n[[\nCoFixpoint looper : stream nat := looper.\n]]\n\n<<\nError:\nRecursive definition of looper is ill-formed.\nIn environment\nlooper : stream nat\n\nunguarded recursive call in \"looper\"\n>>\n\nThe rule we have run afoul of here is that _every co-recursive call must be guarded by a constructor_; that is, every co-recursive call must be a direct argument to a constructor of the co-inductive type we are generating. It is a good thing that this rule is enforced. If the definition of [looper] were accepted, our [approx] function would run forever when passed [looper], and we would have fallen into inconsistency.\n\nSome familiar functions are easy to write in co-recursive fashion. *)\n*)\n(**\nこれまでの説明では,\n余帰納型はまるで魔法の仕組みのようであり,\nHaskellユーザが使っていたすべての技法がCoqでも使えると感じてしまうでしょう.\nしかしながら,帰納型を利用するときの制約と双対となる重要な制約があります.\n[Fixpoint]によって定義される関数が帰納型の値を「消費」するとき,\n再帰呼び出しの際に渡される「引数」に制約があります.\nこれとは双対的に,\n[CoFixpoint]によって定義される関数が余帰納型の値を「生産」するとき,\n余再帰呼び出しの「結果」の使われ方に制約があるのです.\n\nこの余帰納型に対する制約は%\\index{ガード条件}%「ガード条件」として現れます.\nまず,Haskellでは問題なく記述できる次の定義を考えましょう.\n\n[[\nCoFixpoint looper : stream nat := looper.\n]]\n\n<<\nError:\nRecursive definition of looper is ill-formed.\nIn environment\nlooper : stream nat\n\nunguarded recursive call in \"looper\"\n>>\n\nここで違反している規則は「すべての余再帰呼び出しは構成子によってガードされていなければならない」というものです.\nつまり,すべての余再帰呼び出しは,作りたい余帰納型の構成子の直接的な引数になっていなければなりません.\nこの規則を強要するのはよいことです.\nもし,この[looper]の定義が許されるとすると,\n[approx]関数の引数として[looper]を渡すことで無限に実行されてしまい,\n矛盾に陥ってしまうでしょう.\n\nお馴染みの関数を余再帰的に書くことも簡単です.\n*)\n\nSection map.\n Variables A B : Type.\n Variable f : A -> B.\n\n CoFixpoint map (s : stream A) : stream B :=\n match s with\n | Cons h t => Cons (f h) (map t)\n end.\nEnd map.\n\n(* begin hide *)\n(* begin thide *)\nDefinition filter := 0.\n(* end thide *)\n(* end hide *)\n\n(**\n(** This code is a literal copy of that for the list [map] function, with the [nil] case removed and [Fixpoint] changed to [CoFixpoint]. Many other standard functions on lazy data structures can be implemented just as easily. Some, like [filter], cannot be implemented. Since the predicate passed to [filter] may reject every element of the stream, we cannot satisfy the guardedness condition.\n\n The implications of the condition can be subtle. To illustrate how, we start off with another co-recursive function definition that _is_ legal. The function [interleave] takes two streams and produces a new stream that alternates between their elements. *)\n*)\n(** \nこのコードはリストに対する[map]関数をほぼそのまま写したもので,\n[nil]の場合を削除して[Fixpoint]を[CoFixpoint]に変えただけです.\nストリームを扱う他の多くの標準的な関数も簡単に定義できます.\n一方,[filter]のように定義できない関数もあります.\n[filter]関数に渡される述語がストリームのすべての要素をふるい落としてしまう可能性もあるので,\nガード条件が満たされません.\n\nこの条件の扱いには慎重さを必要とすることがあります.\nそれを確認するために,まずは「合法」とされる別の余再帰関数の定義を見てみましょう.\n次の[interleave]関数は2つのストリームを入力として,\nそれらの要素を交互に並べた1つのストリームを返す関数です.\n*)\n\nSection interleave.\n Variable A : Type.\n\n CoFixpoint interleave (s1 s2 : stream A) : stream A :=\n match s1, s2 with\n | Cons h1 t1, Cons h2 t2 => Cons h1 (Cons h2 (interleave t1 t2))\n end.\nEnd interleave.\n\n(**\n(** Now say we want to write a weird stuttering version of [map] that repeats elements in a particular way, based on interleaving. *)\n*)\n(**\nここで,ちょっと変わった[map]関数を考えてみましょう.\n[interleave]関数を使って\n特定の方法で要素を繰り返しながらストリームを生成する関数です.\n*)\n\nSection map'.\n Variables A B : Type.\n Variable f : A -> B.\n \n(* begin thide *)\n(**\n (** %\\vspace{-.15in}%[[\n CoFixpoint map' (s : stream A) : stream B :=\n match s with\n | Cons h t => interleave (Cons (f h) (map' t)) (Cons (f h) (map' t))\n end.\n ]]\n %\\vspace{-.15in}%We get another error message about an unguarded recursive call. *)\n*)\n (** %\\vspace{-.15in}%[[\n CoFixpoint map' (s : stream A) : stream B :=\n match s with\n | Cons h t => interleave (Cons (f h) (map' t)) (Cons (f h) (map' t))\n end.\n ]]\n %\\vspace{-.15in}%これを入力すると,再帰呼出しがガード条件に違反していることを指摘するエラーメッセージが表示されます. *)\n\nEnd map'.\n\n(** \n(** What is going wrong here? Imagine that, instead of [interleave], we had called some other, less well-behaved function on streams. Here is one simpler example demonstrating the essential pitfall. We start by defining a standard function for taking the tail of a stream. Since streams are infinite, this operation is total. *)\n*)\n(**\nどこが間違っていたのでしょう?\n仮に,[interleave]関数の代わりに\nストリーム上の別の不適切な関数が呼ばれていた場合を考えてみましょう.\nこのような関数呼出しが本質的な危険となるということを説明するために,\n更に簡単な例を用意しました.\nまずはストリームに対する標準的な関数である[tail]関数を定義します.\nリストと違ってストリームの長さは常に無限であるため,\nこの関数は全域関数です.\n*)\n\nDefinition tl A (s : stream A) : stream A :=\n match s with\n | Cons _ s' => s'\n end.\n\n(**\n(** Coq rejects the following definition that uses [tl].\n[[\nCoFixpoint bad : stream nat := tl (Cons 0 bad).\n]]\n\nImagine that Coq had accepted our definition, and consider how we might evaluate [approx bad 1]. We would be trying to calculate the first element in the stream [bad]. However, it is not hard to see that the definition of [bad] \"begs the question\": unfolding the definition of [tl], we see that we essentially say \"define [bad] to equal itself\"! Of course such an equation admits no single well-defined solution, which does not fit well with the determinism of Gallina reduction.\n\nCoq's complete rule for co-recursive definitions includes not just the basic guardedness condition, but also a requirement about where co-recursive calls may occur. In particular, a co-recursive call must be a direct argument to a constructor, _nested only inside of other constructor calls or [fun] or [match] expressions_. In the definition of [bad], we erroneously nested the co-recursive call inside a call to [tl], and we nested inside a call to [interleave] in the definition of [map'].\n\nCoq helps the user out a little by performing the guardedness check after using computation to simplify terms. For instance, any co-recursive function definition can be expanded by inserting extra calls to an identity function, and this change preserves guardedness. However, in other cases computational simplification can reveal why definitions are dangerous. Consider what happens when we inline the definition of [tl] in [bad]:\n[[\nCoFixpoint bad : stream nat := bad.\n]]\nThis is the same looping definition we rejected earlier. A similar inlining process reveals an alternate view on our failed definition of [map']:\n[[\nCoFixpoint map' (s : stream A) : stream B :=\n match s with\n | Cons h t => Cons (f h) (Cons (f h) (interleave (map' t) (map' t)))\n end.\n]]\nClearly in this case the [map'] calls are not immediate arguments to constructors, so we violate the guardedness condition. *)\n*)\n(**\nこの[tl]関数を使って次のようなストリームを定義しようとしても,\nCoqは受け入れてくれません.\n[[\nCoFixpoint bad : stream nat := tl (Cons 0 bad).\n]]\n\n仮にCoqがこの定義を受け入れたとして,\n[approx bad 1]という式を評価しようとした場合を考えましょう.\nこの式は,[bad]ストリームの最初の要素を取り出そうとしています.\nしかしながら,この[bad]の定義が問題を引き起こすことは容易に想像できます.\n[tl]関数の定義を展開すると,\n[bad]が結局[bad]自身と等しくなるように定義されていることがわかります.\nもちろん,\n[bad]が[bad]と等しいというだけの定義では唯一の値を特定することはできないので,\nGallina簡約の決定性に反する結果となります.\n\nCoqにおける余再帰定義の完全な規則には,\n基本的なガード条件だけではなく,\n余再帰呼出しがどこに現れるべきかという制約もあります.\n具体的には,\n余再帰呼出しは構成子の直接の引数でなければならず,\nその外側には「別の構成子」「[fun]」「[match]式」以外が現れてはいけません.\n先ほどの[bad]の定義では,余再帰呼出しの外側に[tl]の関数呼出しがあり,\n[map']の定義では,\n余再帰呼出しの外側に[interleave]の関数呼出しがあるため,\nどちらもエラーになります.\n\nCoqには,構文的な制約を緩和するために,\n項を簡約してからガード条件を検査するという手法を採用しています.\nたとえば,余再帰的定義の外側で恒等関数が呼び出されていたとしてもガード条件には影響しません.\nしかしながら,\nそれ以外の場合には項の簡約によってなぜ定義に問題があるのかがよくわかります.\n先ほどの[bad]の例において[tl]の定義をインライン展開してみましょう.\n\n[[\nCoFixpoint bad : stream nat := bad.\n]]\nこれは以前の[looper]の例と同じで適切な定義ではありません.\nエラーになってしまった[map']の定義においても同様にインライン展開すると\n次のようになります.\n[[\nCoFixpoint map' (s : stream A) : stream B :=\n match s with\n | Cons h t => Cons (f h) (Cons (f h) (interleave (map' t) (map' t)))\n end.\n]]\nこの場合は明らかに[map']関数の呼出しが構成子の直接の引数になっていないため,\nガード条件に違反していることがわかります.\n*)\n(* end thide *)\n\n(**\n(** A more interesting question is why that condition is the right one. We can make an intuitive argument that the original [map'] definition is perfectly reasonable and denotes a well-understood transformation on streams, such that every output would behave properly with [approx]. The guardedness condition is an example of a syntactic check for%\\index{productivity}% _productivity_ of co-recursive definitions. A productive definition can be thought of as one whose outputs can be forced in finite time to any finite approximation level, as with [approx]. If we replaced the guardedness condition with more involved checks, we might be able to detect and allow a broader range of productive definitions. However, mistakes in these checks could cause inconsistency, and programmers would need to understand the new, more complex checks. Coq's design strikes a balance between consistency and simplicity with its choice of guard condition, though we can imagine other worthwhile balances being struck, too. *)\n*)\n(**\n興味深いのはなぜこの条件が正しいのかということです.\n直観的には最初に示した[map']関数の定義はとても自然で,\nストリーム上の変換としても理解しやすいものですし,\n[approx]に渡しても適切に実行されそうに見えるでしょう.\nCoqにおけるガード条件は,\n余再帰的定義の「生産的であるか」%\\index{productivity}%を構文的に検査しているだけです.\n生産的な定義とは,[approx]のような関数を使ったどんな有限の近似においても\n有限の時間で出力が得られるものであると考えてかまいません.\nガード条件にもっと複雑な検査を追加すれば,\nより広い範囲の生産的な定義を扱うこともできるかもしれません.\nしかしながら,\nそのような検査でのエラーは一貫性のないものになるかもしれませんし,\nプログラマがその新しい複雑な検査を理解する必要が出てきてしまいます.\n現在のCoqの設計では,\n一貫性とわかりやすさのバランスを重視してガード条件を定めていますし,\n他にも抑えておきたい重要なバランスもあるでしょう.\n*)\n\n(**\n(** * Infinite Proofs *)\n*)\n(** * 無限の大きさをもつ証明 *)\n\n(**\n(** Let us say we want to give two different definitions of a stream of all ones, and then we want to prove that they are equivalent. *)\n*)\n(**\nすべての要素が1であるストリームを異なる二つの方法で定義してみましょう.\nあとでこれらが等しいことを証明します.\n*)\n\nCoFixpoint ones : stream nat := Cons 1 ones.\nDefinition ones' := map S zeroes.\n\n(**\n(** The obvious statement of the equality is this: *)\n*)\n(** 単純に考えればこれらが等しいことを示す言明は次の通りです.*)\n\nTheorem ones_eq : ones = ones'.\n\n(* begin hide *)\n(* begin thide *)\nDefinition foo := @eq.\n(* end thide *)\n(* end hide *)\n\n(**\n (** However, faced with the initial subgoal, it is not at all clear how this theorem can be proved. In fact, it is unprovable. The [eq] predicate that we use is fundamentally limited to equalities that can be demonstrated by finite, syntactic arguments. To prove this equivalence, we will need to introduce a new relation. *)\n*)\n (**\nしかしながら,\n最初のゴールを見ても\nこの定理をどう証明すればいいのか全くわかりません.\n実際,この言明は証明できません.\nここで使われている[eq]という述語は基本的に,\n有限回の構文的な比較によって証明できるような等価性に限定されています.\nストリームのような値の等価性を示すには,新たな関係を導入する必要があるのです.\n*)\n(* begin thide *)\n\nAbort.\n\n(**\n(** Co-inductive datatypes make sense by analogy from Haskell. What we need now is a _co-inductive proposition_. That is, we want to define a proposition whose proofs may be infinite, subject to the guardedness condition. The idea of infinite proofs does not show up in usual mathematics, but it can be very useful (unsurprisingly) for reasoning about infinite data structures. Besides examples from Haskell, infinite data and proofs will also turn out to be useful for modelling inherently infinite mathematical objects, like program executions.\n\nWe are ready for our first %\\index{co-inductive predicates}%co-inductive predicate. *)\n*)\n(**\n余帰納的データ型はHaskellとの対比によって理解できます.\nいま必要なのは「余帰納的命題」です.\nつまり,\nガード条件に従って構成された無限の大きさになりうる証明をもつような命題を\n定義する必要があるのです.\nこの考え方は通常の数学で出てくることはありませんが,\n無限の大きさをもつ構造を考えるためには(当然ながら)とても有用です.\nHaskellの例の他にも,無限の大きさをもつデータや証明は,\nプログラム実行などの\n本質的に無限の大きさをもつ数学的対象を扱う際にもにも有用であることがわかるでしょう.\n\n%\\index{余帰納的述語}%余帰納的述語の最初の例がこちらです.\n*)\n\nSection stream_eq.\n Variable A : Type.\n\n CoInductive stream_eq : stream A -> stream A -> Prop :=\n | Stream_eq : forall h t1 t2,\n stream_eq t1 t2\n -> stream_eq (Cons h t1) (Cons h t2).\nEnd stream_eq.\n\n(**\n(** We say that two streams are equal if and only if they have the same heads and their tails are equal. We use the normal finite-syntactic equality for the heads, and we refer to our new equality recursively for the tails.\n\nWe can try restating the theorem with [stream_eq]. *)\n*)\n(**\n二つのストリームが等しいということを,\n先頭が同じで残りのストリームが等しいと定義します.\n先頭は通常の有限回の構文的な比較による等価性を使い,\n残りのストリームは新たに定義している等価性を再帰的に使います.\n\nそれでは,\n当初の目標だった等式について\n[stream_eq]を使った定理とし,\n改めて証明してみましょう.\n*)\n\nTheorem ones_eq : stream_eq ones ones'.\n(**\n (** Coq does not support tactical co-inductive proofs as well as it supports tactical inductive proofs. The usual starting point is the [cofix] tactic, which asks to structure this proof as a co-fixpoint. *)\n*)\n (**\n帰納的証明のときとは異なり,\nCoqには余帰納的証明を直接支援するタクティックが提供されていません.\n通常最初に使うタクティックは[cofix]で,\nこのタクティックは余不動点として証明を構成するためのものです.\n*)\n\n cofix ones_eq.\n(** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq ones ones'\n \n ]]\n\n なんだか思った以上に簡単に証明ができそうですね!\n*)\n\n assumption.\n(*\n (** <<\nProof completed.\n>>\n\n Unfortunately, we are due for some disappointment in our victory lap.\n [[\nQed.\n]]\n\n<<\nError:\nRecursive definition of ones_eq is ill-formed.\n\nIn environment\nones_eq : stream_eq ones ones'\n\nunguarded recursive call in \"ones_eq\"\n>>\n\nVia the Curry-Howard correspondence, the same guardedness condition applies to our co-inductive proofs as to our co-inductive data structures. We should be grateful that this proof is rejected, because, if it were not, the same proof structure could be used to prove any co-inductive theorem vacuously, by direct appeal to itself!\n\nThinking about how Coq would generate a proof term from the proof script above, we see that the problem is that we are violating the guardedness condition. During our proofs, Coq can help us check whether we have yet gone wrong in this way. We can run the command [Guarded] in any context to see if it is possible to finish the proof in a way that will yield a properly guarded proof term.%\\index{Vernacular commands!Guarded}%\n [[\nGuarded.\n]]\n\n Running [Guarded] here gives us the same error message that we got when we tried to run [Qed]. In larger proofs, [Guarded] can be helpful in detecting problems _before_ we think we are ready to run [Qed].\n \n We need to start the co-induction by applying [stream_eq]'s constructor. To do that, we need to know that both arguments to the predicate are [Cons]es. Informally, this is trivial, but [simpl] is not able to help us. *)\n*)\n (** <<\nProof completed.\n>>\n\n 残念なことに,証明終了のウイニングランでは失望が待っています.\n [[\nQed.\n]]\n\n<<\nError:\nRecursive definition of ones_eq is ill-formed.\n\nIn environment\nones_eq : stream_eq ones ones'\n\nunguarded recursive call in \"ones_eq\"\n>>\n\nカリー・ハワード同型対応を考慮すれば,余帰納的データ構造に対するガード条件は余帰納的証明にも適用されるはずです.\n上記の証明が受け入れられないのはむしろ歓迎すべきことです.\nなぜなら,仮にこの証明が通ってしまうとしたら,\n同じような証明手順によってあらゆる余帰納的な定理が証明できてしまうからです.\n\nこの証明手順からどのように証明項が生成されるかを考えてみれば,\nガード条件に違反しようとしていることが問題であることがわかります.\nCoqでは,証明の途中に,ガード条件に反するようなおかしな証明をしていないかどうか検査する機能が提供されています.\n[[Guarded]]コマンドを使うことで,\n適切にガードされた証明項を作るように証明を終えることができるかどうかを\nいつでも確認することができます%\\index{Vernacular commands!Guarded}%.\n\n [[\nGuarded.\n]]\n\nここで [Guarded] を使うと [Qed] で証明を終えようとしたときと同じエラーメッセージが得られます. もっと大きな証明をするときには [Guarded] コマンドは有用で,\n[Qed] で証明が終えられる状態であるかを考える前に問題を検出できます.\n\nこの証明では,まず [stream_eq] 構成子の規則を適用することによって余帰納的証明を始める必要があります.そのためには,[stream_eq]の2つの引数が[Cons]の形であること知っておかないといけません.それは直感的には当たり前のことですが,[simpl]タクティクは何の役にも立ちません.\n*)\n\n Undo.\n simpl.\n(*\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq ones ones'\n \n ]]\n\n It turns out that we are best served by proving an auxiliary lemma. *)\n*)\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq ones ones'\n \n ]]\n\n これを解決するために,あらかじめ補題を1つ証明しておくのが最善の方法であることがわかります.\n*)\n\nAbort.\n\n(*\n(** First, we need to define a function that seems pointless at first glance. *)\n*)\n(**\nまず,一見何の意味もない関数の定義が必要です.\n*)\n\nDefinition frob A (s : stream A) : stream A :=\n match s with\n | Cons h t => Cons h t\n end.\n\n(*\n(** Next, we need to prove a theorem that seems equally pointless. *)\n*)\n(** \n次に,同じくらい意味のなさそうな定理を証明する必要があります.\n*)\n\nTheorem frob_eq : forall A (s : stream A), s = frob s.\n destruct s; reflexivity.\nQed.\n\n(*\n(** But, miraculously, this theorem turns out to be just what we needed. *)\n*)\n(**\nしかしながら,奇跡的なことに,この定理が紛れもなく求めていたものであることがわかります.\n*)\n\nTheorem ones_eq : stream_eq ones ones'.\n cofix ones_eq.\n\n(*\n (** We can use the theorem to rewrite the two streams. *)\n*)\n (**\nこの定理を使うことで2つのストリームを書き換えることができます.\n*)\n\n rewrite (frob_eq ones).\n rewrite (frob_eq ones').\n(*\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq (frob ones) (frob ones')\n \n ]]\n\n Now [simpl] is able to reduce the streams. *)\n*)\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq (frob ones) (frob ones')\n \n ]]\n\n 今なら [simpl] を使って2つのストリームの式を簡約することができます.\n*)\n\n simpl.\n(*\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq (Cons 1 ones)\n (Cons 1\n ((cofix map (s : stream nat) : stream nat :=\n match s with\n | Cons h t => Cons (S h) (map t)\n end) zeroes))\n \n ]]\n\n Note the [cofix] notation for anonymous co-recursion, which is analogous to the [fix] notation we have already seen for recursion. Since we have exposed the [Cons] structure of each stream, we can apply the constructor of [stream_eq]. *)\n*)\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq (Cons 1 ones)\n (Cons 1\n ((cofix map (s : stream nat) : stream nat :=\n match s with\n | Cons h t => Cons (S h) (map t)\n end) zeroes))\n \n ]]\n\n この[cofix]記法は無名余再帰を表していますが,すでに見た再帰を表すための[fix]記法とよく似ています. 今それぞれのストリーム式が [Cons] の形になったので,[stream_eq] 構成子の規則を適用することができます.*)\n\n constructor.\n(*\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq ones\n ((cofix map (s : stream nat) : stream nat :=\n match s with\n | Cons h t => Cons (S h) (map t)\n end) zeroes)\n \n ]]\n\n Now, modulo unfolding of the definition of [map], we have matched our assumption. *)\n*)\n (** [[\n ones_eq : stream_eq ones ones'\n ============================\n stream_eq ones\n ((cofix map (s : stream nat) : stream nat :=\n match s with\n | Cons h t => Cons (S h) (map t)\n end) zeroes)\n \n ]]\n\n ここで,[map]の定義が展開されているかいないかを無視すれば,この帰結は仮定と一致します.\n*)\n\n assumption.\nQed.\n\n(*\n(** Why did this silly-looking trick help? The answer has to do with the constraints placed on Coq's evaluation rules by the need for termination. The [cofix]-related restriction that foiled our first attempt at using [simpl] is dual to a restriction for [fix]. In particular, an application of an anonymous [fix] only reduces when the top-level structure of the recursive argument is known. Otherwise, we would be unfolding the recursive definition ad infinitum.\n\n Fixpoints only reduce when enough is known about the _definitions_ of their arguments. Dually, co-fixpoints only reduce when enough is known about _how their results will be used_. In particular, a [cofix] is only expanded when it is the discriminee of a [match]. Rewriting with our superficially silly lemma wrapped new [match]es around the two [cofix]es, triggering reduction.\n\n If [cofix]es reduced haphazardly, it would be easy to run into infinite loops in evaluation, since we are, after all, building infinite objects.\n\n One common source of difficulty with co-inductive proofs is bad interaction with standard Coq automation machinery. If we try to prove [ones_eq'] with automation, like we have in previous inductive proofs, we get an invalid proof. *)\n*)\n(** \nこんな無意味に見える小技が役に立つのはなぜでしょうか.\nその答えは,停止性のためにCoqの評価規則に課された制約と関係しています.\n上の例で最初に[simpl]タクティクが働かなかったときの[cofix]の制約は,\n[fix]に対する制約と双対の関係になっています.\n[fix]で表される無名関数の適用が評価されるのは,\n再帰呼び出しの引数の最も外側の構成子がわかったときだけです.\nそうしないと再帰的な定義が無限に展開されてしまいます.\n\n[fix]による不動点は「引数の定義」が必要なだけわかったときだけ評価されます.\nそれとは双対に,\n[cofix]による余不動点は「結果がどう使われるか」が必要なだけわかったときだけ評価されます.\n[cofix]で表される無名関数が展開されるのは,[match]式の引数として与えられたときだけです.\n先ほどの表面的で自明な補題を使って新たな[match]式で2つの[cofix]式を包むことにより,簡約を進めることができます.\n\n最終的に無限の大きさをもつ対象を構成しようとしているので,\nもし[cofix]式が行き当たりばったりに簡約されるとしたら,\nすぐに無限ループに陥ってしまうことでしょう.\n\n余帰納的証明の難しさの原因としてよく挙げられるのは,\n標準のCoqの自動証明機構と相性が悪いという点です.\nこれまでの帰納的定理の証明と同じような自動証明を[ones'_eq]に対して試みると,\nガードされていない不適切な証明が得られてしまいます.\n*)\n\nTheorem ones_eq' : stream_eq ones ones'.\n cofix one_eq'; crush.\n (** %\\vspace{-.25in}%[[\n Guarded.\n ]]\n %\\vspace{-.25in}%\n *)\nAbort.\n\n(*\n(** The standard [auto] machinery sees that our goal matches an assumption and so applies that assumption, even though this violates guardedness. A correct proof strategy for a theorem like this usually starts by [destruct]ing some parameter and running a custom tactic to figure out the first proof rule to apply for each case. Alternatively, there are tricks that can be played with \"hiding\" the co-inductive hypothesis.\n\n %\\medskip%\n\n Must we always be cautious with automation in proofs by co-induction? Induction seems to have dual versions of the same pitfalls inherent in it, and yet we avoid those pitfalls by encapsulating safe Curry-Howard recursion schemes inside named induction principles. It turns out that we can usually do the same with%\\index{co-induction principles}% _co-induction principles_. Let us take that tack here, so that we can arrive at an [induction x; crush]-style proof for [ones_eq'].\n\n An induction principle is parameterized over a predicate characterizing what we mean to prove, _as a function of the inductive fact that we already know_. Dually, a co-induction principle ought to be parameterized over a predicate characterizing what we mean to prove, _as a function of the arguments to the co-inductive predicate that we are trying to prove_.\n\n To state a useful principle for [stream_eq], it will be useful first to define the stream head function. *)\n*)\n(** \n標準的な[auto]タクティクは,帰結に一致する仮定があれば,ガード条件に違反するかどうかに関係なく,その仮定を適用してしまいます.\nこのような定理を証明する正しい戦略は,まず引数のどれかを[destruct]して場合分けを行い,それぞれの場合について最初に適用できる規則を知るための適切なタクティクを使うことです.あるいは,余帰納的仮定を「隠す」ことで自動証明を進めるという方法もいくつかあります.\n\n %\\medskip%\n\n余帰納法で証明する場合には常に自動証明に注意を払わなければならないのでしょうか.\n帰納法でも双対になる同じような罠が存在すると思われますが,\nいわゆる帰納法の原理の中に安全なカリー・ハワード再帰スキームを内包することで,その罠を避けています.大抵の場合は「余帰納法の原理」%\\index{余帰納法の原理}%を用いて同じことができることがわかります.それでは,[ones_eq']に対して[induction x; crush]形式で証明する方法を考えてみましょう.\n\n帰納的原理は,証明すべき命題を表す述語をパラメータ化した\n「すでにわかっている帰納的事実を受け取る関数」として与えられます.\nそれとは双対に,\n余帰納的原理は,\n証明すべき命題を表す述語をパラメータ化した\n「証明しようとしている余帰納的述語の引数を受け取る関数」として与えられるべきです.\n\n[stream_eq]に対する証明に有用な原理を示すために,ストリームの先頭を取り出す関数を用意しておくと便利です.\n*)\n\nDefinition hd A (s : stream A) : A :=\n match s with\n | Cons x _ => x\n end.\n\n(*\n(** Now we enter a section for the co-induction principle, based on %\\index{Park's principle}%Park's principle as introduced in a tutorial by Gim%\\'%enez%~\\cite{IT}%. *)\n*)\n(**\nいよいよ余帰納法の原理を示す[Section]に入ります.\nこれは,Gim%\\'%enezによるチュートリアル%~\\cite{IT}%で紹介されている%\\index{Parkの原理}%Parkの原理を基にしています.\n*)\n\nSection stream_eq_coind.\n Variable A : Type.\n Variable R : stream A -> stream A -> Prop.\n\n(*\n (** This relation generalizes the theorem we want to prove, defining a set of pairs of streams that we must eventually prove contains the particular pair we care about. *)\n*)\n (**\nこの関係 [R] は証明したい定理を一般化したものを表し,\n注目している特定のストリーム対が最終的に含まれるように対の集合を定義していきます.\n*)\n\n Hypothesis Cons_case_hd : forall s1 s2, R s1 s2 -> hd s1 = hd s2.\n Hypothesis Cons_case_tl : forall s1 s2, R s1 s2 -> R (tl s1) (tl s2).\n\n(*\n (** Two hypotheses characterize what makes a good choice of [R]: it enforces equality of stream heads, and it is %``%##hereditary##%''% in the sense that an [R] stream pair passes on \"[R]-ness\" to its tails. An established technical term for such a relation is%\\index{bisimulation}% _bisimulation_. *)\n*)\n (** \nこの2つの仮定は関係[R]が適切に定義されていることを表します.\n1つめの仮定では,ストリームの先頭が互いに等しいことを強制し,\n2つめの仮定では,ストリーム同士の[R]という関係が後続のストリームに%``%##遺伝##%''%することを表しています.\n専門用語では,このような関係は%\\index{bisimulation}%「双模倣」と呼ばれます.\n*)\n\n(*\n (** Now it is straightforward to prove the principle, which says that any stream pair in [R] is equal. The reader may wish to step through the proof script to see what is going on. *)\n*)\n (** \n余帰納法の原理を示すのは簡単です.\nその原理の主張は,[R] で関係付けられるストリーム対は必ず [stream_eq] の意味で等しい,というものです.\nこの証明スクリプトを順に追いながら何が起こっているかを見てみましょう.\n*)\n\n Theorem stream_eq_coind : forall s1 s2, R s1 s2 -> stream_eq s1 s2.\n cofix stream_eq_coind; destruct s1; destruct s2; intro.\n generalize (Cons_case_hd H); intro Heq; simpl in Heq; rewrite Heq.\n constructor.\n apply stream_eq_coind.\n apply (Cons_case_tl H).\n Qed.\nEnd stream_eq_coind.\n\n(*\n(** To see why this proof is guarded, we can print it and verify that the one co-recursive call is an immediate argument to a constructor. *)\n*)\n(**\nこの証明がガード条件を満たしていることは,\nその証明項を表示し,\n余再帰呼出しが構成子の直接の引数になっていることを確認すればわかります.\n*)\n\nPrint stream_eq_coind.\n\n(*\n(** We omit the output and proceed to proving [ones_eq''] again. The only bit of ingenuity is in choosing [R], and in this case the most restrictive predicate works. *)\n*)\n(**\n出力は省略することとして,先ほどの定理を [ones_eq''] として証明してみましょう.\n適切な [R] を選ぶのにちょっとした工夫が必要ですが,\nこの場合はもっとも制限された述語を選べばうまく証明ができます.\n*)\n\nTheorem ones_eq'' : stream_eq ones ones'.\n apply (stream_eq_coind (fun s1 s2 => s1 = ones /\\ s2 = ones')); crush.\nQed.\n\n(*\n(** Note that this proof achieves the proper reduction behavior via [hd] and [tl], rather than [frob] as in the last proof. All three functions pattern match on their arguments, catalyzing computation steps.\n\n Compared to the inductive proofs that we are used to, it still seems unsatisfactory that we had to write out a choice of [R] in the last proof. An alternate is to capture a common pattern of co-recursion in a more specialized co-induction principle. For the current example, that pattern is: prove [stream_eq s1 s2] where [s1] and [s2] are defined as their own tails. *)\n*)\n(**\nこの証明では,以前の証明で使った[frob]の代わりに[hd]と[tl]を通じて適切な簡約を実現しています.これらの3つの関数は,いずれも引数に対してパターンマッチすることにより,計算を進める触媒の役割を果たしています.\n\nこれまでの帰納法による証明と比べると,この余帰納法による証明では関係[R]をわざわざ書き下さなければならず,依然として不満があるかもしれません.\nそこで,別の手段として,\n余帰納法の原理の特別な場合として余再帰に共通するパターンを見つけることを考えます.\n今の例では,そのパターンは「自分自身が後続することで定義されているような[s1]と[s2]に対して[stream_eq s1 s2]を証明する」というものです.\n*)\n\nSection stream_eq_loop.\n Variable A : Type.\n Variables s1 s2 : stream A.\n\n Hypothesis Cons_case_hd : hd s1 = hd s2.\n Hypothesis loop1 : tl s1 = s1.\n Hypothesis loop2 : tl s2 = s2.\n\n(*\n (** The proof of the principle includes a choice of [R], so that we no longer need to make such choices thereafter. *)\n*)\n (**\nこの帰納法の原理では,関係[R]を特別な場合に限定しているため,\n使う際にはその関係を指定する必要がありません.\n*)\n\n Theorem stream_eq_loop : stream_eq s1 s2.\n apply (stream_eq_coind (fun s1' s2' => s1' = s1 /\\ s2' = s2)); crush.\n Qed.\nEnd stream_eq_loop.\n\nTheorem ones_eq''' : stream_eq ones ones'.\n apply stream_eq_loop; crush.\nQed.\n(* end thide *)\n\n(*\n(** Let us put [stream_eq_coind] through its paces a bit more, considering two different ways to compute infinite streams of all factorial values. First, we import the [fact] factorial function from the standard library. *)\n*)\n(**\n[stream_eq_coind]より一歩先に進んだ余帰納法の原理を理解するために,\n自然数の階乗を無限に並べたストリーム(階乗ストリーム)を計算する2つの方法を考えましょう.\nまず,階乗を計算する関数[fact]を標準ライブラリから読み込みます.\n*)\n\nRequire Import Arith.\nPrint fact.\n(** %\\vspace{-.15in}%[[\nfact = \nfix fact (n : nat) : nat :=\n match n with\n | 0 => 1\n | S n0 => S n0 * fact n0\n end\n : nat -> nat\n]]\n*)\n\n(*\n(** The simplest way to compute the factorial stream involves calling [fact] afresh at each position. *)\n*)\n(**\n階乗ストリームを計算するもっとも単純な方法は,\n要素ごとに[fact]関数を呼ぶことです.\n*)\n\nCoFixpoint fact_slow' (n : nat) := Cons (fact n) (fact_slow' (S n)).\nDefinition fact_slow := fact_slow' 1.\n\n(*\n(** A more clever, optimized method maintains an accumulator of the previous factorial, so that each new entry can be computed with a single multiplication. *)\n*)\n(**\n最適化されたより賢い方法は,\n直前の階乗の値を記憶しつつ,要素ごとに1度の掛け算だけで計算する方法です.\n*)\n\nCoFixpoint fact_iter' (cur acc : nat) := Cons acc (fact_iter' (S cur) (acc * cur)).\nDefinition fact_iter := fact_iter' 2 1.\n\n(*\n(** We can verify that the streams are equal up to particular finite bounds. *)\n*)\n(**\n2つのストリームが有限個までは等しいことを確認してみましょう.\n*)\n\nEval simpl in approx fact_iter 5.\n(** %\\vspace{-.15in}%[[\n = 1 :: 2 :: 6 :: 24 :: 120 :: nil\n : list nat\n]]\n*)\nEval simpl in approx fact_slow 5.\n(*\n(** %\\vspace{-.15in}%[[\n = 1 :: 2 :: 6 :: 24 :: 120 :: nil\n : list nat\n]]\n\nNow, to prove that the two versions are equivalent, it is helpful to prove (and add as a proof hint) a quick lemma about the computational behavior of [fact]. (I intentionally skip explaining its proof at this point.) *)\n*)\n(** %\\vspace{-.15in}%[[\n = 1 :: 2 :: 6 :: 24 :: 120 :: nil\n : list nat\n]]\n\n2つのストリームが完全に等しいことを証明するために,\n[fact]関数による計算についての簡単な補題を証明してヒントとして追加します.\n(ここでは敢えて証明の解説はしません.)\n*)\n\n(* begin thide *)\nLemma fact_def : forall x n,\n fact_iter' x (fact n * S n) = fact_iter' x (fact (S n)).\n simpl; intros; f_equal; ring.\nQed.\n\nHint Resolve fact_def.\n\n(*\n(** With the hint added, it is easy to prove an auxiliary lemma relating [fact_iter'] and [fact_slow']. The key bit of ingenuity is introduction of an existential quantifier for the shared parameter [n]. *)\n*)\n(**\nこのヒントを加えると,\n[fact_iter']と[fact_slow']を関連づける補題の証明がしやすくなります.\n存在量化子で導入された共通の変数[n]を使うのがミソです.\n*)\n\nLemma fact_eq' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n intro; apply (stream_eq_coind (fun s1 s2 => exists n, s1 = fact_iter' (S n) (fact n)\n /\\ s2 = fact_slow' n)); crush; eauto.\nQed.\n\n(*\n(** The final theorem is a direct corollary of [fact_eq']. *)\n*)\n(**\n最終的な定理は[fact_eq']の系として簡単に得られます.\n*)\n\nTheorem fact_eq : stream_eq fact_iter fact_slow.\n apply fact_eq'.\nQed.\n\n(*\n(** As in the case of [ones_eq'], we may be unsatisfied that we needed to write down a choice of [R] that seems to duplicate information already present in a lemma statement. We can facilitate a simpler proof by defining a co-induction principle specialized to goals that begin with single universal quantifiers, and the strategy can be extended in a straightforward way to principles for other counts of quantifiers. (Our [stream_eq_loop] principle is effectively the instantiation of this technique to zero quantifiers.) *)\n*)\n(**\n[ones_eq']の場合には,\nすでに補題の記述にあるものをわざわざ改めて[R]として書き下さなければならないことが不満だったかもしれません.\n一般的な場合でより簡潔に証明できるように,\n一つの全称量化子で始まる帰結に特化した余帰納法の原理を定義してみましょう.\nこの原理から複数個の量化子を含む余帰納法の原理へ拡張することも簡単です.\n(先ほどの[stream_eq_loop]という余帰納法の原理は,量化子が0個の特殊な場合においてこの手法を適用したものです.)\n*)\n\n\nSection stream_eq_onequant.\n Variables A B : Type.\n(*\n (** We have the types [A], the domain of the one quantifier; and [B], the type of data found in the streams. *)\n*)\n (**\n量化子で束縛される変数の型を[A],ストリームの要素の型を[B]とします.\n*)\n\n Variables f g : A -> stream B.\n(*\n (** The two streams we compare must be of the forms [f x] and [g x], for some shared [x]. Note that this falls out naturally when [x] is a shared universally quantified variable in a lemma statement. *)\n*)\n (**\n比較しようとしている2つのストリームは,変数[x]を共有して[f x]や[g x]という形で表されるはずです.拡張された余帰納法の原理を使う補題では,この変数[x]が全称量化子として現れることになります.\n*)\n\n Hypothesis Cons_case_hd : forall x, hd (f x) = hd (g x).\n Hypothesis Cons_case_tl : forall x, exists y, tl (f x) = f y /\\ tl (g x) = g y.\n(*\n (** These conditions are inspired by the bisimulation requirements, with a more general version of the [R] choice we made for [fact_eq'] inlined into the hypotheses of [stream_eq_coind]. *)\n*)\n (**\nこれらの条件は双模倣の定義に触発されたもので,[fact_eq']を証明するために使った[R]を一般化し,[stream_eq_coind]の仮定の部分に展開することで得られます.\n*)\n\n Theorem stream_eq_onequant : forall x, stream_eq (f x) (g x).\n intro; apply (stream_eq_coind (fun s1 s2 => exists x, s1 = f x /\\ s2 = g x)); crush; eauto.\n Qed.\nEnd stream_eq_onequant.\n\nLemma fact_eq'' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n apply stream_eq_onequant; crush; eauto.\nQed.\n\n(*\n(** We have arrived at one of our customary automated proofs, thanks to the new principle. *)\n*)\n(** \n新しい余帰納法の原理のおかげで,これまで行ってきたような通常の自動証明にたどり着きました.\n*)\n(* end thide *)\n\n\n(** * Simple Modeling of Non-Terminating Programs *)\n\n(*\n(** We close the chapter with a quick motivating example for more complex uses of co-inductive types. We will define a co-inductive semantics for a simple imperative programming language and use that semantics to prove the correctness of a trivial optimization that removes spurious additions by 0. We follow the technique of%\\index{co-inductive big-step operational semantics}% _co-inductive big-step operational semantics_ %\\cite{BigStep}%.\n\n We define a suggestive synonym for [nat], as we will consider programs over infinitely many variables, represented as [nat]s. *)\n*)\n(** \n最後に,役に立ちそうな例を通じて余帰納的型の複雑な使い方を紹介します.\nここでは,単純な手続き型プログラミング言語の余帰納的意味論を定義し,\nその意味論の下で,\n0を加算するという無駄な処理を取り除く自明な最適化の正当性を証明してみましょう.\n%\\index{余帰納的ビッグステップ操作的意味論}% 「余帰納的ビッグステップ操作的意味論」 %\\cite{BigStep}% に従って進めていきます.\n\nまず,この言語におけるプログラムでは,無限個の変数を扱えるようにする必要があるので,それを[nat]のわかりやすい別名として用意します.\n*)\n\nDefinition var := nat.\n\n(**\n次に,変数から値への写像の型[vars]を定義します.\nある変数から値への対応を写像に上書きする関数[set]を定義するには,\n自然数同士を比較する標準ライブラリ関数[beg_nat]を使います.\n*)\n\nDefinition vars := var -> nat.\nDefinition set (vs : vars) (v : var) (n : nat) : vars :=\n fun v' => if beq_nat v v' then n else vs v'.\n\n(*\n(** We define a simple arithmetic expression language with variables, and we give it a semantics via an interpreter. *)\n*)\n(**\n変数を含む算術式を表す言語を定義して,インタプリタ関数によってその意味論を与えます.\n*)\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : var -> exp\n| Plus : exp -> exp -> exp.\n\nFixpoint evalExp (vs : vars) (e : exp) : nat :=\n match e with\n | Const n => n\n | Var v => vs v\n | Plus e1 e2 => evalExp vs e1 + evalExp vs e2\n end.\n\n(*\n(** Finally, we define a language of commands. It includes variable assignment, sequencing, and a <> form that repeats as long as its test expression evaluates to a nonzero value. *)\n*)\n(** \n最後に,命令言語を定義します.\n命令の構文として,変数への代入,命令の連結,\n条件式が0でない値をもつ限り繰り返す<>文があります.\n*)\n\nInductive cmd : Set :=\n| Assign : var -> exp -> cmd\n| Seq : cmd -> cmd -> cmd\n| While : exp -> cmd -> cmd.\n\n(*\n(** We could define an inductive relation to characterize the results of command evaluation. However, such a relation would not capture _nonterminating_ executions. With a co-inductive relation, we can capture both cases. The parameters of the relation are an initial state, a command, and a final state. A program that does not terminate in a particular initial state is related to _any_ final state. For more realistic languages than this one, it is often possible for programs to _crash_, in which case a semantics would generally relate their executions to no final states; so relating safely non-terminating programs to all final states provides a crucial distinction. *)\n*)\n(**\n命令に対する実行結果を帰納的関係によって特徴づけることもできるかもしれません.\nしかしながら,そのように定義された関係では「停止しない実行」を表現することはできません.\n余帰納的関係を使えば,停止する場合もしない場合も両方表現することができます.\nその関係は,初期状態と命令と最終状態の三項関係によって与えられます.\nある初期状態から停止しないプログラムは「あらゆる」最終状態に関係づけられるように定義します.\nこの言語より現実的な言語では,プログラムが予期せず停止することもよくあるでしょう.\n一般的に,そういったプログラムについてはどんな最終状態にも関係づけられないように意味論を定義します.\n予期しない停止と明確に区別するためには,安全で停止しないプログラムにすべての最終状態を関連づけることはとても重要なことです.\n*)\n\nCoInductive evalCmd : vars -> cmd -> vars -> Prop :=\n| EvalAssign : forall vs v e, evalCmd vs (Assign v e) (set vs v (evalExp vs e))\n| EvalSeq : forall vs1 vs2 vs3 c1 c2, evalCmd vs1 c1 vs2\n -> evalCmd vs2 c2 vs3\n -> evalCmd vs1 (Seq c1 c2) vs3\n| EvalWhileFalse : forall vs e c, evalExp vs e = 0\n -> evalCmd vs (While e c) vs\n| EvalWhileTrue : forall vs1 vs2 vs3 e c, evalExp vs1 e <> 0\n -> evalCmd vs1 c vs2\n -> evalCmd vs2 (While e c) vs3\n -> evalCmd vs1 (While e c) vs3.\n\n(*\n(** Having learned our lesson in the last section, before proceeding, we build a co-induction principle for [evalCmd]. *)\n*)\n(**\n先に進む前に,前節で学習したように [evalCmd] に対する余帰納法の原理を準備します.\n*)\n\nSection evalCmd_coind.\n Variable R : vars -> cmd -> vars -> Prop.\n\n Hypothesis AssignCase : forall vs1 vs2 v e, R vs1 (Assign v e) vs2\n -> vs2 = set vs1 v (evalExp vs1 e).\n\n Hypothesis SeqCase : forall vs1 vs3 c1 c2, R vs1 (Seq c1 c2) vs3\n -> exists vs2, R vs1 c1 vs2 /\\ R vs2 c2 vs3.\n\n Hypothesis WhileCase : forall vs1 vs3 e c, R vs1 (While e c) vs3\n -> (evalExp vs1 e = 0 /\\ vs3 = vs1)\n \\/ exists vs2, evalExp vs1 e <> 0 /\\ R vs1 c vs2 /\\ R vs2 (While e c) vs3.\n\n(*\n (** The proof is routine. We make use of a form of %\\index{tactics!destruct}%[destruct] that takes an%\\index{intro pattern}% _intro pattern_ in an [as] clause. These patterns control how deeply we break apart the components of an inductive value, and we refer the reader to the Coq manual for more details. *)\n*)\n (** \n証明は簡単です.\n[as]句として%\\index{イントロパターン}%イントロパターンを用いた[destruct]タクティクを利用します.\nこのパターンを使うと帰納的な値を深いところまで分解することができます.\n詳しくはCoqのマニュアルをご覧ください.\n*)\n\n Theorem evalCmd_coind : forall vs1 c vs2, R vs1 c vs2 -> evalCmd vs1 c vs2.\n cofix evalCmd_coind; intros; destruct c.\n rewrite (AssignCase H); constructor.\n destruct (SeqCase H) as [? [? ?]]; econstructor; eauto.\n destruct (WhileCase H) as [[? ?] | [? [? [? ?]]]]; subst; econstructor; eauto.\n Qed.\nEnd evalCmd_coind.\n\n(*\n(** Now that we have a co-induction principle, we should use it to prove something! Our example is a trivial program optimizer that finds places to replace [0 + e] with [e]. *)\n*)\n(**\n余帰納法の原理を得たからには,これを使って何か証明したいですよね!\n今回は例として[0 + e]を見つけて[e]に置き換える自明なプログラム最適化器を考えます.\n*)\n\nFixpoint optExp (e : exp) : exp :=\n match e with\n | Plus (Const 0) e => optExp e\n | Plus e1 e2 => Plus (optExp e1) (optExp e2)\n | _ => e\n end.\n\nFixpoint optCmd (c : cmd) : cmd :=\n match c with\n | Assign v e => Assign v (optExp e)\n | Seq c1 c2 => Seq (optCmd c1) (optCmd c2)\n | While e c => While (optExp e) (optCmd c)\n end.\n\n(*\n(** Before proving correctness of [optCmd], we prove a lemma about [optExp]. This is where we have to do the most work, choosing pattern match opportunities automatically. *)\n*)\n(** \n[optCmd]関数の正当性を証明する前に,[optExp]に関する補題を証明しましょう.\nこの部分はパターンマッチを自動的に選ぶというすべきことが最も多いところです.\n*)\n\n(* begin thide *)\nLemma optExp_correct : forall vs e, evalExp vs (optExp e) = evalExp vs e.\n induction e; crush;\n repeat (match goal with\n | [ |- context[match ?E with Const _ => _ | _ => _ end] ] => destruct E\n | [ |- context[match ?E with O => _ | S _ => _ end] ] => destruct E\n end; crush).\nQed.\n\nHint Rewrite optExp_correct.\n\n(*\n(** The final theorem is easy to establish, using our co-induction principle and a bit of Ltac smarts that we leave unexplained for now. Curious readers can consult the Coq manual, or wait for the later chapters of this book about proof automation. At a high level, we show inclusions between behaviors, going in both directions between original and optimized programs. *)\n*)\n(**\n最後の定理は簡単に証明できますが,余帰納法の原理に加えてこれまで説明してこなかったLtacによる賢い方法を使います.興味があればCoqのマニュアルを調べてもよいですし,この本の後ろの方の自動証明に関する章まで待ってもよいでしょう.\nざっくり言えば,元のプログラムと最適化されたプログラムの振舞いについて互いの包含関係を証明しています.\n*)\n\nLtac finisher := match goal with\n | [ H : evalCmd _ _ _ |- _ ] => ((inversion H; [])\n || (inversion H; [|])); subst\n end; crush; eauto 10.\n\nLemma optCmd_correct1 : forall vs1 c vs2, evalCmd vs1 c vs2\n -> evalCmd vs1 (optCmd c) vs2.\n intros; apply (evalCmd_coind (fun vs1 c' vs2 => exists c, evalCmd vs1 c vs2\n /\\ c' = optCmd c)); eauto; crush;\n match goal with\n | [ H : _ = optCmd ?E |- _ ] => destruct E; simpl in *; discriminate\n || injection H; intros; subst\n end; finisher.\nQed.\n\nLemma optCmd_correct2 : forall vs1 c vs2, evalCmd vs1 (optCmd c) vs2\n -> evalCmd vs1 c vs2.\n intros; apply (evalCmd_coind (fun vs1 c vs2 => evalCmd vs1 (optCmd c) vs2));\n crush; finisher.\nQed.\n\nTheorem optCmd_correct : forall vs1 c vs2, evalCmd vs1 (optCmd c) vs2\n <-> evalCmd vs1 c vs2.\n intuition; apply optCmd_correct1 || apply optCmd_correct2; assumption.\nQed.\n(* end thide *)\n\n(*\n(** In this form, the theorem tells us that the optimizer preserves observable behavior of both terminating and nonterminating programs, but we did not have to do more work than for the case of terminating programs alone. We merely took the natural inductive definition for terminating executions, made it co-inductive, and applied the appropriate co-induction principle. Curious readers might experiment with adding command constructs like <>; the same proof script should continue working, after the co-induction principle is extended to the new evaluation rules. *)\n*)\n(**\nこうして,停止するプログラムでも停止しないプログラムでも最適化によって振舞いが変わらないことを示す定理が得られましたが,\n停止するプログラムだけを考える場合と比較しても証明すべきことは多くなかったでしょう.\n今回やったことは,\n停止するプログラムに対する自然な帰納的定義を採用してそれを余帰納的にし,\n適切な余帰納法の原理を適用しただけです.\n興味があれば<>のような命令構成子も追加して証明してみてください.\n余帰納法の原理を新しい評価規則にも対応させれば,\n同じ証明スクリプトが使えるはずです.\n*)\n", "meta": {"author": "cpdt-japanese", "repo": "cpdt-japanese", "sha": "b9209279f75d85b844e7c7278d6b663bd700e801", "save_path": "github-repos/coq/cpdt-japanese-cpdt-japanese", "path": "github-repos/coq/cpdt-japanese-cpdt-japanese/cpdt-japanese-b9209279f75d85b844e7c7278d6b663bd700e801/src/Coinductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.12765261702501562, "lm_q1q2_score": 0.05296292531368448}} {"text": "(** * VSU_stdlib2: Malloc/free/exit programmed in C *)\n\n(** In contrast to [VSU_stdlib] which axiomatized malloc, free,\n and exit as external functions, in this chapter we construct them as\n ordinary C functions, and prove them correct. This chapter shows\n how to manage global variables that are private to a module.\n\n In the C code, there is a [stdlib.h] interface, with alternative\n implementations [stdlib.c] and [stdlib2.c] that are quite\n independent of each other.\n\n The the proofs, there is a specification [Spec_stdlib.MallocFreeASI]\n (that is, the \"malloc-free Abstract Specification Interface\")\n with two alternative implementations-with-proofs,\n [VSU_stdlib.MallocFreeVSU] and [VSU_stdlib2.MallocFreeVSU].\n\n That second VSU is the one we build in this chapter.\n*)\n\n(* ################################################################# *)\n(** * The C program *)\n\n(** Here is our C program. Notice the variables [pool, pool_index, freelist] \nthat are global to the module, but meant to be private--not to be\ndirectly manipulated by clients of the module. Furthermore, these\nvariables have initial values ([pool_index=0, freelist=NULL],\nand [pool] zero-initialized implicitly) that \nrepresent a meaningful initial state.\n\n/* stdlib2.c */\n#include \n#include \"stdlib.h\"\n\nstruct cell {struct cell *a, *b, *c, *d;};\n\n#define N 80000\n\nstruct cell pool[N];\nint pool_index = 0;\nstruct cell *freelist=NULL;\n\nvoid *malloc (size_t n) {\n struct cell *p;\n if (n>sizeof(struct cell)) return NULL;\n if (freelist) {\n p = freelist;\n freelist = p->a;\n } else if (pool_index < N) {\n p = pool+pool_index++;\n } else p=NULL;\n return (void* ) p;\n}\n\nvoid free (void *p) {\n struct cell *pp = p;\n if (pp==NULL) return;\n pp->a = freelist;\n freelist=pp;\n}\n\nvoid exit (int n) {\n while (1) ;\n}\n\nAs you can see, malloc can allocate blocks whose size ranges from\n 0 to sizeof(struct cell), that is, up to four words long. Any malloc\n request larger than that will return NULL, which is legal behavior\n for malloc. Furthermore, the maximum size of the pool is N=80000,\n beyond which malloc will return NULL.\n\n The exit() function infinite-loops, so that it satisfies its postcondition\n of False in our Hoare logic of partial correctness.\n*)\n \n(* ################################################################# *)\n(** * The normal boilerplate *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\nRequire Import VC.stdlib2.\nRequire Import VC.Spec_stdlib.\nInstance CompSpecs : compspecs. make_compspecs stdlib2.prog. Defined.\n\n(** As usual, we define representation relations. First, for the free list,\n which is just a linked list much as in [VSU_stack].*)\n\nDefinition tcell := Tstruct _cell noattr.\n\nFixpoint freelistrep (n: nat) (p: val) : mpred :=\n match n with\n | S n' => EX y: val, \n !! malloc_compatible (sizeof tcell) p && \n data_at Ews tcell (y, (Vundef, (Vundef, Vundef))) p *\n freelistrep n' y\n | O => !! (p = nullval) && emp\n end.\n\nArguments freelistrep n p : simpl never.\n\nLemma freelistrep_local_prop: forall n p, \n freelistrep n p |-- !! (is_pointer_or_null p /\\ (n=0<->p=nullval) /\\ (n>0<->isptr p))%nat.\n(* FILL IN HERE *) Admitted.\n#[export] Hint Resolve freelistrep_local_prop : saturate_local.\n\nLemma freelistrep_valid_pointer:\n forall n p,\n freelistrep n p |-- valid_pointer p.\n(* FILL IN HERE *) Admitted.\n#[export] Hint Resolve freelistrep_valid_pointer : valid_pointer.\n(** [] *)\n\n(* ################################################################# *)\n(** * malloc_token *)\n\n(** Suppose the user does [p = malloc(7);]. Then [p] points to\n a newly allocated block of 7 bytes. What does [malloc_token(p)]\n represent?\n - Normally, there must be some way for [free(p)] to figure out\n the size of the block. This can be done by having a header word,\n just before address p, that gives the size (though there are other\n ways to do it). Normally, this header word is part of what \n malloc_token represents. But in this implementation, all blocks\n are the same size, so there's no need for such a header.\n - The memory-manager's free list contains blocks all of size\n sizeof(tcell), which is 16 bytes when [sizeof(size_t)=4] or \n 32 bytes when [sizeof(size_t)=8]. When [malloc(7)] splits a\n block into two pieces, the malloc_token represents the\n second piece, the portion of the block between offset 7 and the end.\n That is the [memory_block] shown in the definition below.\n - In addition, the malloc_token has three propositional facts about\n address [p], that will assist the [free()] function in reconstituting\n the two parts of the split block. *)\n \nDefinition malloc_token_sz (sh: share) (n: Z) (p: val) : mpred := \n !! (field_compatible tcell [] p \n /\\ malloc_compatible (sizeof tcell) p\n /\\ 0 <= n <= sizeof tcell) \n && memory_block Ews (sizeof tcell - n) (offset_val n p).\n\n(** **** Exercise: 2 stars, standard (malloc_token_properties) *)\nLemma malloc_token_sz_valid_pointer:\n forall (sh : share) (sz : Z) (p : val),\n sz <= 0 ->\n malloc_token_sz sh sz p |-- valid_pointer p.\n(* FILL IN HERE *) Admitted.\n\nLemma malloc_token_sz_local_facts : \n forall (sh : share) (sz : Z) (p : val),\n malloc_token_sz sh sz p |-- !! malloc_compatible sz p.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The next three lines define an opaque constant that, nevertheless,\n rep_lia can unfold. See VC.pdf, chapter 65 \"Opaque Constants\". *)\nDefinition N : Z := proj1_sig (opaque_constant 80000).\nDefinition N_eq : N=_ := proj2_sig (opaque_constant _).\nHint Rewrite N_eq : rep_lia.\n\n(* ----------------------------------------------------------------- *)\n(** *** Digression (feel free to skip this) *)\n\nModule Digression.\n(** Suppose someone changes the source program stdlib2.c, putting a\n different constant than 80000. You would like your verification \n script to automatically adjust. We will revise the line,\n [Definition N : Z := ...] to find the constant automagically.\n\n Step one is to find the constant. You can look in stdlib2.v, which\n is produced by CompCert clightgen from stdlib2.c, for the variable\n definition v_pool. And now look where the number 80000 appears\n in [gvar_info(v_pool)]: *)\nCompute gvar_info (stdlib2.v_pool).\n (* = Tarray\n (Tstruct 57 {| attr_volatile := false; attr_alignas := None |})\n 80000\n {| attr_volatile := false; attr_alignas := None |}\n : type *)\n\n(** It's easy to extract that number automatically: *)\n\nCompute match gvar_info (stdlib2.v_pool) with Tarray _ n _ => n | _ => 0 end.\n (* = 80000: Z *)\n\n(** The following definition of [N] won't work well, because N will \n not be a constant, it'll be a match expression: *)\nDefinition N' := match gvar_info (stdlib2.v_pool) with Tarray _ n _ => n | _ => 0 end.\nPrint N'. (* N' = match gvar_info v_pool with Tarray _ n _ => n | _ => 0 end *)\n\n(** So instead, use this Coq trick: *)\n\nDefinition N'' := \n ltac:(let x := constr:(match gvar_info (stdlib2.v_pool) with\n | Tarray _ n _ => n\n\t\t\t | _ => 0 end)\n in let x := eval compute in x in exact x).\nPrint N''. (* N'' = 80000 : Z *)\n\n(** Now, throw away N'' and we'll combine the two tricks together:\n - [opaque_constant] to define a constant that won't unfold except \n by explicit rewriting; and\n - extract the value of the constant from the program itself. *)\nDefinition N := proj1_sig (opaque_constant \n (ltac:(let x := constr:(match gvar_info (stdlib2.v_pool) with\n Tarray _ n _ => n | _ => 0 end)\n in let x := eval compute in x in exact x))).\nDefinition N_eq : N=_ := proj2_sig (opaque_constant _).\nHint Rewrite N_eq : rep_lia.\nCheck N_eq. (* : N = 80000 *)\n\nEnd Digression.\n\n(* ----------------------------------------------------------------- *)\n(** *** End of digression. Aren't you glad you skipped it? *)\n\n(* ################################################################# *)\n(** * Defining the mem_mgr APD *)\n\n(** This [mem_mgr] predicate is the client-view abstract predicate\n that characterizes the contents of this module's global state variables,\n [pool], [pool_index], and [freelist]. *)\n\nDefinition mem_mgr (gv: globals) : mpred :=\n EX i: Z, EX p: val, EX frees: nat,\n !! (0 <= i <= N) &&\n data_at Ews tint (Vint (Int.repr i)) (gv _pool_index) *\n data_at_ Ews (tarray tcell (N-i))\n (field_address0 (tarray tcell N) [ArraySubsc i] (gv _pool)) *\n data_at Ews (tptr tcell) p (gv _freelist) *\n freelistrep frees p.\n\nDefinition M : MallocFreeAPD := \n Build_MallocFreeAPD mem_mgr malloc_token_sz\n malloc_token_sz_valid_pointer malloc_token_sz_local_facts.\n\n(* ################################################################# *)\n(** * Constructing Vprog and Gprog *)\n\n Definition MF_ASI: funspecs := MallocFreeASI M.\n Definition MF_imported_specs:funspecs := nil.\n Definition MF_internal_specs: funspecs := MF_ASI.\n Definition MF_globals gv : mpred:= Spec_stdlib.mem_mgr M gv.\n Definition MFVprog : varspecs. mk_varspecs stdlib2.prog. Defined.\n Definition MFGprog: funspecs := MF_imported_specs ++ MF_internal_specs.\n\n(** **** Exercise: 3 stars, standard (stdlib2_body_malloc) *)\n\nLemma body_malloc: semax_body MFVprog MFGprog f_malloc (malloc_spec_sz M).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (stdlib2_body_free) *)\nLemma body_free: semax_body MFVprog MFGprog f_free (free_spec_sz M).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (stdlib2_body_exit) *)\nLemma body_exit: semax_body MFVprog MFGprog f_exit exit_spec.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Initializers for global data *)\n\nCheck @Comp_MkInitPred.\n(** Each VSU may have private global variables that constitute its\n \"local state\". The client of the VSU should not access these\n directly; and in separation logic all these variables should be\n abstracted as a single abstract predicate. Since these variables\n may have initial values that concretely represent some abstract\n state, we need an axiom in the VSU interface (proved as a lemma\n in the VSU implementation), saying that the initial values\n properly represent a proper state of the abstract predicate. *)\n\n(** **** Exercise: 2 stars, standard (stdlib2_initialize) *)\nLemma initialize: VSU_initializer prog MF_globals.\nProof.\nInitGPred_tac.\nunfold MF_globals.\n(* FILL IN HERE *) Admitted.\n\n(* ================================================================= *)\n(** ** Defining the pieces of a VSU\n\n And now, in the usual way, we can put totether the pieces: *)\n\n(* ################################################################# *)\n(** * Constructing the Component and the VSU *)\n\n Definition MF_Externs : funspecs := nil.\n\nDefinition MallocFreeVSU: @VSU NullExtension.Espec\n MF_Externs MF_imported_specs ltac:(QPprog prog) MF_ASI MF_globals.\n Proof. \n mkVSU prog MF_internal_specs.\n - solve_SF_internal body_malloc.\n - solve_SF_internal body_free.\n - solve_SF_internal body_exit.\n - apply initialize; auto.\nQed.\n\n(* ================================================================= *)\n(** ** Next Chapter: [VSU_main2] *)\n\n(* 2022-09-05 15:05 *)\n", "meta": {"author": "Tgist1024", "repo": "SoftwareFoundationBackup", "sha": "0252d4109f0b58cc4a037c3aeaaad6f3154213ca", "save_path": "github-repos/coq/Tgist1024-SoftwareFoundationBackup", "path": "github-repos/coq/Tgist1024-SoftwareFoundationBackup/SoftwareFoundationBackup-0252d4109f0b58cc4a037c3aeaaad6f3154213ca/vc/VSU_stdlib2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10669059820623797, "lm_q1q2_score": 0.052928547432675804}} {"text": "(*|\n###############################################\nDealing with let-in expressions in current goal\n###############################################\n\n:Link: https://stackoverflow.com/q/48278491\n|*)\n\n(*|\nQuestion\n********\n\nI got stuck while doing some coq proofs around the ``state`` monad.\nConcretely, I've simplified the situation to this proof:\n|*)\n\nDefinition my_call {A B C} (f : A -> B * C) (a : A) : B * C :=\n let (b, c) := f a in (b, c).\n\nLemma mycall_is_call : forall {A B C} (f : A -> B * C) (a : A),\n my_call f a = f a.\nProof.\n intros A B C f a. unfold my_call.\n (* stuck! *)\n\n(*| The resulting goal after invoking ``unfold`` is |*)\n\n Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nIf I'm not wrong, both sides of the equality should be exactly the\nsame, but I don't know how to show it from here. Any help?\n\n----\n\nAs a side note, I've seen that coq automatically applies the\nsimplification when no product types are involved in the result of the\nfunction:\n|*)\n\nDefinition my_call' {A B : Type} (f : A -> B) (a : A) : B :=\n let b := f a in b.\n\nLemma my_call_is_call' : forall A B (f : A -> B) (a : A),\n my_call' f a = f a.\nProof.\n intros A B f a. unfold my_call'. reflexivity.\nQed.\n\n(*|\nAnswer\n******\n\nIt's easy to see what you need to do next, once you recall that\n\n.. code-block:: coq\n\n let (b, c) := f a in (b, c)\n\nis syntactic sugar for\n\n.. code-block:: coq\n\n match f a with (b, c) => (b, c) end\n\nThis means you need to destruct on ``f a`` to finish the proof:\n|*)\n\nLemma mycall_is_call {A B C} (f : A -> B * C) a :\n my_call f a = f a.\nProof.\n unfold my_call. now destruct (f a).\nQed.\n\n(*|\n----\n\n**A:** Note that you can ``Set Printing All`` to make the syntactic\nsugar go away.\n\n**A:** With pairs defined with primitive projections (as `here\n`__), we can prove\n``mycall_is_call`` lemma using just ``reflexivity``.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/dealing-with-let-in-expressions-in-current-goal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.11124121240045179, "lm_q1q2_score": 0.052581883020917555}} {"text": "(** * Finite Modular Maps: bool and list utilities *)\n\n(** Author: Pierre Letouzey (Université de Paris - INRIA),\n License: LGPL-2.1-only, see file LICENSE. *)\n\nFrom Coq Require Import List SetoidList.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nLemma eq_bool_alt b b' : b=b' <-> (b=true <-> b'=true).\nProof.\n destruct b, b'; intuition.\nQed.\n\nLemma eq_option_alt {A}(o o':option A) :\n o=o' <-> (forall x, o=Some x <-> o'=Some x).\nProof.\nsplit; intros.\n- now subst.\n- destruct o, o'; rewrite ?H; auto.\n symmetry; now apply H.\nQed.\n\nLemma option_map_some {A B}(f:A->B) o :\n option_map f o <> None <-> o <> None.\nProof.\n destruct o; simpl. now split. split; now destruct 1.\nQed.\n\nDefinition option_bind {A B} o (f:A->option B) :=\n match o with\n | None => None\n | Some a => f a\n end.\n\n(** An hybrid of [map] and [filter] *)\n\nFixpoint mapfilter {A B} (f:A->option B) l :=\n match l with\n | [] => []\n | a::l => match f a with\n | Some b => b::mapfilter f l\n | None => mapfilter f l\n end\n end.\n\nLemma mapfilter_app {A B} (f:A->option B) l l' :\n mapfilter f (l++l') = mapfilter f l ++ mapfilter f l'.\nProof.\ninduction l; simpl; auto.\ndestruct f; simpl; auto; f_equal; auto.\nQed.\n\n#[export] Instance mapfilter_ext {A B} :\n Proper ((eq ==> eq) ==> eq ==> eq) (@mapfilter A B).\nProof.\n intros f f' E l l' <-.\n induction l; simpl; auto.\n rewrite <- (E a); auto. destruct f; auto. f_equal; auto.\nQed.\n\nLemma map_as_mapfilter {A B} (f:A->B) l :\n map f l = mapfilter (fun a => Some (f a)) l.\nProof.\ninduction l; simpl; f_equal; auto.\nQed.\n\nLemma filter_as_mapfilter {A} (f:A->bool) l :\n filter f l = mapfilter (fun a => if f a then Some a else None) l.\nProof.\ninduction l; simpl; auto. destruct f; simpl; auto. f_equal; auto.\nQed.\n\nLemma mapfilter_comp {A B C}(f:A->option B)(g:B->option C) l :\n mapfilter g (mapfilter f l) = mapfilter (fun a => option_bind (f a) g) l.\nProof.\ninduction l; simpl; auto.\ndestruct f; simpl; auto. destruct g; simpl; auto. f_equal; auto.\nQed.\n\nLemma mapfilter_map {A B C} (f:A->B)(g:B->option C) l :\n mapfilter g (map f l) = mapfilter (fun a => g (f a)) l.\nProof.\nnow rewrite map_as_mapfilter, mapfilter_comp.\nQed.\n\nLemma map_mapfilter {A B C} (f:A->option B)(g:B->C) l :\n map g (mapfilter f l) = mapfilter (fun a => option_map g (f a)) l.\nProof.\nrewrite map_as_mapfilter, mapfilter_comp. f_equiv.\nQed.\n\n(** Properties of [List.filter] *)\n\nLemma filter_app {A} (f:A->bool) l l' :\n filter f (l++l') = filter f l ++ filter f l'.\nProof.\ninduction l; simpl; auto. destruct (f a); simpl; f_equal; auto.\nQed.\n\nLemma filter_map {A B} (f:A->B)(h:B->bool) l :\n filter h (map f l) = map f (filter (fun x => h (f x)) l).\nProof.\ninduction l; simpl; auto. destruct (h (f a)); simpl; f_equal; auto.\nQed.\n\n#[export] Instance filter_ext {A} : Proper ((eq==>eq)==>eq==>eq) (@filter A).\nProof.\nintros f f' E l l' <-.\ninduction l; simpl; auto. rewrite <- (E a); auto.\ndestruct f; simpl; auto. f_equal; auto.\nQed.\n\nLemma filter_rev {A} (f:A->bool) l :\n rev (filter f l) = filter f (rev l).\nProof.\ninduction l; simpl; auto.\nrewrite filter_app, <- IHl. simpl.\ndestruct (f a); simpl; auto using app_nil_r.\nQed.\n\nLemma NoDupA_filter {A} (eq:relation A) (f:A->bool) l :\n NoDupA eq l -> NoDupA eq (filter f l).\nProof.\n induction 1; simpl; auto.\n destruct f; auto. constructor; auto.\n rewrite InA_alt in *. setoid_rewrite filter_In. firstorder.\nQed.\n\n(** [List.partition] via [List.filter] *)\n\nLemma partition_filter {A} (f:A->bool) l :\n partition f l = (filter f l, filter (fun a => negb (f a)) l).\nProof.\ninduction l; simpl; auto. rewrite IHl. now destruct f.\nQed.\n\n(** More results about [List.forallb] and [List.existsb] *)\n\nLemma forallb_map {A B} (f:A->B)(h:B->bool) l:\n forallb h (map f l) = forallb (fun a => h (f a)) l.\nProof.\ninduction l; simpl; auto. destruct h; simpl; auto.\nQed.\n\nLemma existsb_map {A B} (f:A->B)(h:B->bool) l:\n existsb h (map f l) = existsb (fun a => h (f a)) l.\nProof.\ninduction l; simpl; auto. destruct h; simpl; auto.\nQed.\n\n#[export] Instance forallb_ext {A} : Proper ((eq==>eq)==>eq==>eq) (@forallb A).\nProof.\nintros f f' E l l' <-.\ninduction l; simpl; auto. rewrite <- (E a); auto.\ndestruct f; simpl; auto.\nQed.\n\n#[export] Instance existsb_ext {A} : Proper ((eq==>eq)==>eq==>eq) (@existsb A).\nProof.\nintros f f' E l l' <-.\ninduction l; simpl; auto. rewrite <- (E a); auto.\ndestruct f; simpl; auto.\nQed.\n\nLemma forallb_rev {A} (f:A->bool) l :\n forallb f (rev l) = forallb f l.\nProof.\n apply eq_bool_alt. rewrite !forallb_forall.\n now setoid_rewrite <- in_rev.\nQed.\n\nLemma existsb_rev {A} (f:A->bool) l :\n existsb f (rev l) = existsb f l.\nProof.\n apply eq_bool_alt. rewrite !existsb_exists.\n now setoid_rewrite <- in_rev.\nQed.\n\n(** [SetoidList.SortA_app] written via a [iff] *)\n\nSection MoreOnSortA.\nContext {A} eqA `{Equivalence A eqA}.\nContext ltA `{StrictOrder A ltA} `{!Proper (eqA==>eqA==>iff) ltA}.\n\nLemma SortA_app_iff (l1 l2 : list A) :\n sort ltA (l1++l2) <->\n sort ltA l1 /\\ sort ltA l2 /\\\n forall a1 a2, In a1 l1 -> In a2 l2 -> ltA a1 a2.\nProof.\n split.\n { induction l1 as [|a1 l1 IHl1].\n - easy.\n - simpl. inversion_clear 1 as [ | ? ? Hs Hhd ].\n destruct (IHl1 Hs) as (H1 & H2 & H3); clear IHl1.\n repeat split.\n * constructor; auto.\n destruct l1; simpl in *; auto; inversion_clear Hhd; auto.\n * trivial.\n * intros b1 b2 [->|Hb1] Hb2; eauto.\n eapply SortA_InfA_InA with (eqA:=eqA)(l:=l1++l2); auto.\n rewrite InA_app_iff. right. apply In_InA; auto with *. }\n { intros (U & V & W); eapply SortA_app; eauto.\n intros x y. rewrite !InA_alt.\n intros (x' & -> & Hx) (y' & -> & Hy); auto. }\nQed.\n\nEnd MoreOnSortA.\n", "meta": {"author": "coq-community", "repo": "coq-mmaps", "sha": "2af826d7d50776d82a131d7912145e4ac40393cd", "save_path": "github-repos/coq/coq-community-coq-mmaps", "path": "github-repos/coq/coq-community-coq-mmaps/coq-mmaps-2af826d7d50776d82a131d7912145e4ac40393cd/theories/Utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.11124119766818046, "lm_q1q2_score": 0.05258187770989172}} {"text": "(*|\n######################################################\nHow do I provide implicit arguments explicitly in Coq?\n######################################################\n\n:Link: https://stackoverflow.com/q/47874422\n|*)\n\n(*|\nQuestion\n********\n\nSuppose I have a definition ``f : x -> y -> z`` where ``x`` can be\neasily inferred. I therefore choose to make ``x`` an implicit argument\nusing ``Arguments``.\n\nConsider the following example:\n|*)\n\nDefinition id : forall (S : Set), S -> S := fun S s => s.\n\nArguments id {_} s.\n\nCheck (id 1).\n\n(*|\nClearly ``S = nat`` can be and is inferred by Coq, and Coq replies:\n|*)\n\nCheck (id 1). (* .unfold .messages *)\n\n(*|\nHowever, at a later time, I want to make the implicit argument\nexplicit, say, for readability.\n\nIn other words, I would like something like:\n|*)\n\n(* We want to make it clear that the 2nd argument is nat *)\nFail Definition foo := id {nat} 1. (* .fails *)\n\n(*|\nIs this possible at all? If so, what is the appropriate syntax?\n|*)\n\n(*|\nAnswer\n******\n\nYou can prepend the name with ``@`` to remove all implicits and\nprovide them explicitly:\n|*)\n\nCheck @id nat 1.\n\n(*|\nYou can also use ``(a:=v)`` to pass an implicit argument by name. This\ncan both clarify what argument is being passed and also allows you to\npass some implicits without passing ``_`` for the others:\n|*)\n\nCheck id (S:=nat) 1.\n\nDefinition third {A B C : Type} (a : A) (b : B) (c : C) := c.\nCheck third (B:=nat) (A:=unit) tt 1 2.\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-do-i-provide-implicit-arguments-explicitly-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.11596071367124151, "lm_q1q2_score": 0.052560565662959205}} {"text": "(**************************************************************)\n(** * Coq for POPL Folk *)\n(**************************************************************)\n\n(** A streamlined interactive tutorial on fundamentals of Coq,\n focusing on a minimal set of features needed for developing\n programming language metatheory.\n\n Mostly developed by Aaron Bohannon, with help from Benjamin\n Pierce, Dimitrios Vytiniotis, and Steve Zdancewic.\n*)\n\n(**************************************************************)\n(** * Contents\n - Getting Started\n - Definitions\n - Proofs\n -- Working with Implication and Universal Quantification\n -- Working with Definitions\n -- Working with Conjunction and Disjunction\n -- Reasoning by Cases and Induction\n -- Working with Existential Quantification\n -- Working with Negation\n -- Working with Equality\n -- Reasoning by Inversion\n -- Additional Important Tactics\n -- Basic Automation\n -- Functions and Conversion\n - Solutions to Exercises\n*)\n(**************************************************************)\n\n(**************************************************************)\n(** * Getting Started *)\n(**************************************************************)\n\n(** To get started...\n\n - Install Coq (from the Download page of the main Coq web\n site)\n\n - Install an IDE: either CoqIDE (from the same page) or\n Proof General (use Google to find it).\n\n - Which should you choose? Their command sets are similar,\n so basically the trade-offs are simple:\n -- Proof General is an extension of Emacs (or XEmacs,\n if you prefer), while CoqIDE uses a simpler\n point-and-click model of editing.\n -- PG is pretty easy to install; CoqIDE is very easy\n to install if you can find a pre-built version for\n the OS you are running on but can be a little tricky\n to build from scratch because it has lots of\n dependencies.\n\n - Familiarize yourself with the most important commands\n\n -- If you are using PG, try this:\n --- Open this file and check that the mode line says\n something like \"coq Holes Scripting\"\n --- Go down a few pages and do C-C C-return. Notice\n that the part of the file above the cursor\n changes color (and becomes read-only),\n indicating that it has been sent to Coq.\n --- Come back here and do C-C C-return again\n --- You now know all you really need to navigate in\n this file and send parts of it to Coq, but there\n are some other navigation commands that are\n sometimes more convenient. To see a couple\n more, do C-C C-n several times and observe the\n result; then do C-C C-u a couple of times and\n observe the result.\n\n -- If you are using CoqIDE, try this:\n --- Open this file.\n --- Scroll down a few pages.\n --- Hover the mouse over each the buttons at the top\n of the window; this will make the \"tool tips\"\n appear so you can see which is which.\n --- Press the \"Go to cursor\" button. Observe what\n happens.\n --- Press the forward and backward buttons a few\n times. Observe.\n --- Scroll back to here again and start reading.\n\n - Open the Coq reference manual (from the Documentation\n page of the Coq web site) in a web browser. Spend 30\n seconds looking over the table of contents to get an idea\n what's there. (There is no need to actually read\n anything now.)\n*)\n\n(**************************************************************)\n(** * Definitions *)\n(**************************************************************)\n\n(** In this file, we will be working with a very simple language\n of expressions over natural numbers and booleans. First we\n need to define the datatype of terms.\n\n The [Inductive] keyword defines a new inductive type. We\n name our new type [tm] and declare that [tm] lives in the\n sort [Set]. Types in [Set] are datatypes, which can be used\n just like those in standard programming languages. After\n the inductive definition, the global environment contains\n the name of the newly defined type, along with the names of\n all of the constructors. Coq also automatically defines a\n few operators for eliminating values of the new type\n ([tm_rec], [tm_ind], etc.); we can ignore these for the time\n being, since we will not need to use them directly.\n*)\n\nInductive tm : Set :=\n| tm_true : tm\n| tm_false : tm\n| tm_if : tm -> tm -> tm -> tm\n| tm_zero : tm\n| tm_succ : tm -> tm\n| tm_pred : tm -> tm\n| tm_iszero : tm -> tm.\n\n(** Next, we want to designate some of our [tm] expressions as\n \"values\" in our object language. Mathematically, the\n property of being a value is a unary relation over [tm]s.\n The definition of the unary relation [value] will be built\n from the definition of two auxiliary relations: [bvalue] for\n the set of boolean values and [nvalue] for the set of\n numerical values.\n\n We define n-ary relations in Coq much as we do on paper --\n by giving a set of inference rules that can be used to\n justify the membership of a tuple in the relation. The\n definition of such an inference system also uses the keyword\n [Inductive]. Although this is exactly the same device we\n used to build the set [tm], in this case we want to do\n something slightly different: we will be using it to\n inductively defining the structures (derivation trees) that\n justify the membership of a tuple in a relation, rather than\n directly defining a set inductively. These derivation trees\n will need to be given a dependent type in order to ensure\n that only correct derivation trees can be built. It is\n possible to view their type as a datatype such as [tm];\n however, it is more natural to interpret it as a\n proposition, so it will be declared to live in [Prop]\n instead of [Set]. [Prop] is parallel to [Set] in the sort\n hierarchy, but types in [Prop] can be thought of as logical\n propositions rather than datatypes. The inhabitants of\n types in [Prop] can be thought of as proofs rather than\n programs.\n\n The unary relations [bvalue] and [nvalue] are defined by\n very simple inference systems, each having just two rules.\n After defining these inference systems, [bvalue] and\n [nvalue] will each be a family of types indexed by elements\n of [tm]. We can build inhabitants of some (but not all) of\n the types in these families with the constructors from our\n inductive definition. Semantically, we consider the\n proposition [bvalue t] to be true if it is inhabited and\n false if it is not. (It is worth noting at this point that,\n by default, Coq's logic is constructive and [P \\/ not P] is\n provable for some [P] but not for others. However, it is\n sound to add the law of the excluded middle as an axiom, if\n desired.)\n*)\n\nInductive bvalue : tm -> Prop :=\n| b_true : bvalue tm_true\n| b_false : bvalue tm_false.\n\nInductive nvalue : tm -> Prop :=\n| n_zero : nvalue tm_zero\n| n_succ : forall t,\n nvalue t ->\n nvalue (tm_succ t).\n\n(** The [Definition] keyword is used for defining non-recursive\n functions (including 0-ary functions, i.e., constants).\n Here we define the unary predicate [value] using disjunction\n on propositions (written [\\/]).\n\n Note: It is not actually necessary to provide the types of\n the arguments nor the return type when they can easily be\n inferred; for example, the annotations [: tm] and [: Prop]\n are optional here.\n*)\n\nDefinition value (t : tm) : Prop :=\n bvalue t \\/ nvalue t.\n\n(** Having defined [tm]s and [value]s, we can define a\n call-by-value operational semantics of our language by\n giving a definition of the single-step evaluation of one\n term to another. We give this as an inductively defined\n binary relation.\n*)\n\nInductive eval : tm -> tm -> Prop :=\n| e_iftrue : forall t2 t3,\n eval (tm_if tm_true t2 t3) t2\n| e_iffalse : forall t2 t3,\n eval (tm_if tm_false t2 t3) t3\n| e_if : forall t1 t1' t2 t3,\n eval t1 t1' ->\n eval (tm_if t1 t2 t3) (tm_if t1' t2 t3)\n| e_succ : forall t t',\n eval t t' ->\n eval (tm_succ t) (tm_succ t')\n| e_predzero :\n eval (tm_pred tm_zero) tm_zero\n| e_predsucc : forall t,\n nvalue t ->\n eval (tm_pred (tm_succ t)) t\n| e_pred : forall t t',\n eval t t' ->\n eval (tm_pred t) (tm_pred t')\n| e_iszerozero :\n eval (tm_iszero tm_zero) tm_true\n| e_iszerosucc : forall t,\n nvalue t ->\n eval (tm_iszero (tm_succ t)) tm_false\n| e_iszero : forall t t',\n eval t t' ->\n eval (tm_iszero t) (tm_iszero t').\n\n(** We define multi-step evaluation with the relation\n [eval_many]. This relation includes all of the pairs of\n terms that are connected by sequences of evaluation steps.\n*)\n\nInductive eval_many : tm -> tm -> Prop :=\n| m_refl : forall t,\n eval_many t t\n| m_step : forall t t' u,\n eval t t' ->\n eval_many t' u ->\n eval_many t u.\n\n(** *** Exercise\n Multi-step evaluation is often defined as the \"reflexive,\n transitive closure\" of single-step evaluation. Write an\n inductively defined relation [eval_rtc] that corresponds to\n that verbal description.\n\n In case you get stuck or need a hint, you can find solutions\n to all the exercises near the bottom of the file.\n*)\n\n(** A term is a [normal_form] if there is no term to which it\n can step. Note the concrete syntax for negation and\n existential quantification in the definition below.\n*)\n\nDefinition normal_form (t : tm) : Prop :=\n ~ exists t', eval t t'.\n\n(** *** Exercise\n Sometimes it is more convenient to use a big-step semantics\n for a language. Add the remaining constructors to finish\n the inductive definition [full_eval] for the big-step\n semantics that corresponds to the small-step semantics\n defined by [eval]. Build the inference rules so that\n [full_eval t v] logically implies both [eval_many t v] and\n [value v]. In order to do this, you may need to add the\n premise [nvalue v] to the appropriate cases.\n\n Hint: You should end up with a total of 8 cases.\n\n<<\nInductive full_eval : tm -> tm -> Prop :=\n| f_value : forall v,\n value v ->\n full_eval v v\n| f_iftrue : forall t1 t2 t3 v,\n full_eval t1 tm_true ->\n full_eval t2 v ->\n full_eval (tm_if t1 t2 t3) v\n| f_succ : forall t v,\n nvalue v ->\n full_eval t v ->\n full_eval (tm_succ t) (tm_succ v).\n>>\n*)\n\n(** *** Tip\n If you want to see the type of an identifier [x], you can\n use the command [Check x.] If you want to see the\n definition of an identifier [x], you can use the command\n [Print x.]\n*)\nCheck tm_if.\nCheck m_step.\nCheck value.\nPrint value.\n\n(**************************************************************)\n(** * Proofs *)\n(**************************************************************)\n\n(** A proposition and its proof are both represented as terms in\n the calculus of inductive constructions, which is\n syntactically very small.\n\n Proof terms are most easily built interactively, using\n tactics to manipulate a proof state. A proof state consists\n of a set of goals (propositions or types for which you must\n produce an inhabitant), each with a context of hypotheses\n (inhabitants of propositions or types you are allowed to\n use). A proof state begins initially with one goal (the\n statement of the lemma you are tying to prove) and no\n hypotheses. A goal can be solved, and thereby eliminated,\n when it exactly matches one of hypotheses in the context. A\n proof is completed when all goals are solved.\n\n Tactics can be used for forward reasoning (which, roughly\n speaking, means modifying the hypotheses of a context while\n leaving the goal unchanged) or backward reasoning (replacing\n the current goal with one or more new goals in simpler\n contexts). Given the level of detail required in a formal\n proof, it would be ridiculously impractical to complete a\n proof using forward reasoning alone. However it is usually\n both possible and practical to complete a proof using\n backward reasoning alone. Therefore, we focus almost\n exclusively on backward reasoning in this tutorial. Of\n course, most people naturally use a significant amount of\n forward reasoning in their thinking process, so it may take\n you a while to become accustomed to getting by without it.\n\n We use the keyword [Lemma] to state a new proposition we\n wish to prove. ([Theorem] and [Fact] are exact synonyms for\n [Lemma].) The keyword [Proof], immediately following the\n statement of the proposition, indicates the beginning of a\n proof script. A proof script is a sequence of tactic\n expressions, each concluding with a \"[.]\". Once all of the\n goals are solved, we use the keyword [Qed] to record the\n completed proof. If the proof is incomplete, we may tell\n Coq to accept the lemma on faith by using [Admitted] instead\n of [Qed].\n\n We now proceed to introduce the specific proof tactics.\n*)\n\n(**************************************************************)\n(** ** Working with Implication and Universal Quantification\n - [intros]\n - [apply]\n - [apply with (x := ...)]\n*)\n\n(** *** Example\n The tactic [intros x1 ... xn] moves antecedents and\n universally quantified variables from the goal into the\n context as hypotheses. The tactic [apply] is complementary\n to [intros]. If the conclusion (the part following the\n rightmost arrow) of a constructor, hypothesis, or lemma [e]\n matches our current goal, then [apply e] will replace the\n goal with a new goal for each premise/antecedent of [e]. If\n [e] has no premises, then the current goal is solved. Using\n [apply] allows us to build a proof tree from the bottom up.\n In the following example, our proof script will effectively\n build the following proof tree:\n\n<<\n nvalue t\n ---------------------------- (e_predsucc)\n eval (tm_pred (tm_succ t)) t\n ------------------------------------------------ (e_succ)\n eval (tm_succ (tm_pred (tm_succ t))) (tm_succ t)\n>>\n\n Step through the proof to see how this tree is constructed.\n For each tactic, we give the corresponding statement in a\n written proof. (The uses of [Check] are inessential.)\n*)\nLemma e_succ_pred_succ : forall t,\n nvalue t ->\n eval (tm_succ (tm_pred (tm_succ t))) (tm_succ t).\nProof.\n (** Let [t] be a [tm]. *)\n intros t.\n\n (** Assume that [t] is an [nvalue] (and let's call that\n assumption [Hn] for future reference). *)\n intros Hn.\n\n (** By [e_succ], in order to prove our conclusion, it suffices\n to prove that [eval (tm_pred (tm_succ t)) t]. *)\n Check e_succ.\n apply e_succ.\n\n (** That, in turn, can be shown by [e_predsucc], if we are\n able to show that [nvalue t]. *)\n Check e_predsucc.\n apply e_predsucc.\n\n (** But, in fact, we assumed [nvalue t]. *)\n apply Hn.\nQed.\n\n(** *** Hint for PG users\n If you place the cursor after [Proof.] and do C-c C-return,\n you'll notice that the window displaying Coq's responses is\n (annoyingly) empty, instead of showing what is to be proved.\n The reason for this is that, actually, a different buffer is\n being displayed! (To see this, do C-c C-n and C-c C-u a few\n times and notice that the buffer name in the mode line\n changes.) You can use C-c C-p to switch the display back\n from the *response* buffer to the *goals* buffer.\n*)\n\n(** *** Example\n Now consider, for a moment, the rule [m_step]:\n\n<<\n eval t t' eval_many t' u\n ------------------------- (m_step)\n eval_many t u\n>>\n\n If we have a goal such as [eval_many e1 e2], we should be\n able to use [apply m_step] in order to replace it with the\n goals [eval e1 t'] and [eval_many t' e2]. But what exactly\n is [t'] here? When and how is it chosen? It stands to\n reason the conclusion is justified if we can come up with\n any [t'] for which the premises can be justified.\n\n Now we note that, in the Coq syntax for the type of\n [m_step], all three variables [t], [t'], and [u] are\n universally quantified. The tactic [apply m_step] will use\n pattern matching between our goal and the conclusion of\n [m_step] to find the only possible instantiation of [t] and\n [u]. However, [apply m_step] will raise an error since it\n does not know how it should instantiate [t']. In this case,\n the [apply] tactic takes a [with] clause that allows us to\n provide this instantiation. This is demonstrated in the\n proof below. (Note that the use of this feature means that\n our proof scripts are not invariant under alpha-equivalence\n on the types of our constructors and lemmas. If this is a\n concern, there are other means of achieving the same result\n in a way that is compatible with alpha-conversion. See the\n next example.)\n\n Observe how this works in the proof script below. The proof\n tree here gives a visual representation of the proof term we\n are going to construct and the proof script has again been\n annotated with the steps in English.\n\n<<\n Letting s = tm_succ\n p = tm_pred\n lem = e_succ_pred_succ,\n\n nvalue t\n - - - - - - - - - - - - (lem) --------------------- (m_refl)\n eval (s (p (s t))) (s t) eval_many (s t) (s t)\n --------------------------------------------------- (m_step)\n eval_many (s (p (s t))) (s t)\n>>\n*)\n\nLemma m_succ_pred_succ : forall t,\n nvalue t ->\n eval_many (tm_succ (tm_pred (tm_succ t))) (tm_succ t).\nProof.\n (** Let [t] be a [tm], and assume [nvalue t]. *)\n intros t Hn.\n\n (** By [m_step], to show our conclusion, it suffices to find\n some [t'] for which\n [eval (tm_succ (tm_pred (tm_succ t))) t']\n and\n [eval t' (tm_succ t)].\n Let us choose [t'] to be [tm_succ t]. *)\n Check m_step.\n apply m_step with (t' := tm_succ t).\n\n (** By the lemma [e_succ_pred_succ], to show\n [eval (tm_succ (tm_pred (tm_succ t))) (tm_succ t)],\n it suffices to show [nvalue t]. *)\n Check e_succ_pred_succ.\n apply e_succ_pred_succ.\n\n (** And, in fact, we assumed [nvalue t]. *)\n apply Hn.\n\n (** Moreover, by the rule [m_refl], we also may conclude\n [eval (tm_succ t) (tm_succ t)]. *)\n Check m_refl.\n apply m_refl.\nQed.\n\n(** *** Example\n Coq is built around the Curry-Howard correspondence.\n Proofs of universally quantified propositions are functions\n that take the witness of the quantifier as an argument.\n Similarly, proofs of implications are functions that take\n one proof as an argument and return another proof. Observe\n the types of the following terms.\n*)\n\nCheck (e_succ_pred_succ).\nCheck (e_succ_pred_succ tm_zero).\nCheck (n_zero).\nCheck (e_succ_pred_succ tm_zero n_zero).\n\n(** *** Example\n Any tactic like [apply] that takes the name of a constructor\n or lemma as an argument can just as easily be given a more\n complicated expression as an argument. Thus, we may use\n function application to construct proof objects on the fly\n in these cases. Observe how this technique can be used to\n rewrite the proof of the previous lemma.\n\n Although, we have eliminated one use of [apply], this is not\n necessarily an improvement over the previous proof.\n However, there are cases where this technique is quite\n valuable.\n*)\n\nLemma m_succ_pred_succ_alt : forall t,\n nvalue t ->\n eval_many (tm_succ (tm_pred (tm_succ t))) (tm_succ t).\nProof.\n intros t Hn.\n\n Check m_step.\n apply (m_step\n (tm_succ (tm_pred (tm_succ t)))\n (tm_succ t)\n (tm_succ t)\n ).\n\n Check e_succ_pred_succ.\n apply (e_succ_pred_succ t Hn).\n\n Check m_refl.\n apply (m_refl (tm_succ t)).\nQed.\n\n(** *** Hint for PG users\n By default, the \".\" key is \"electric\" -- it inserts a period\n _and_ causes the material up to the cursor to be sent to\n Coq. If you find this behavior annoying, it can be toggled\n by doing \"C-c .\".\n*)\n\n(*\n LAB 1: (10 minutes)\n Work on the following three exercises.\n*)\n\n(** *** Exercise\n Write a proof script to prove the following lemma, based\n upon the proof given in English.\n\n Note: The lemma and the next should be useful in later\n proofs.\n*)\nLemma m_one : forall t1 t2,\n eval t1 t2 ->\n eval_many t1 t2.\nProof.\n (** Let [t1] and [t2] be terms, and assume [eval t1 t2]. We\n may conclude [eval_many t1 t2] by [m_step] if we can find\n a term [t'] such that [eval t1 t'] and [eval_many t' t2].\n We will choose [t'] to be [t2]. Now we can show\n [eval t1 t2] by our assumption, and we can show\n [eval_many t2 t2] by [m_refl]. *)\n\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma m_two : forall t1 t2 t3,\n eval t1 t2 ->\n eval t2 t3 ->\n eval_many t1 t3.\nProof.\n (** Let [t1], [t2], and [t3] be terms. Assume [eval t1 t2]\n and [eval t2 t3]. By [m_step], we may conclude that\n [eval_many t1 t3] if we can find a term [t'] such that\n [eval t1 t'] and [eval_many t' t3]. Let's choose [t'] to\n be [t2]. We know [eval t1 t2] holds by assumption. In\n the other case, by the lemma [m_one], to show [eval_many\n t2 t3], it suffices to show [eval t2 t3], which is one of\n our assumptions. *)\n\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma m_iftrue_step : forall t t1 t2 u,\n eval t tm_true ->\n eval_many t1 u ->\n eval_many (tm_if t t1 t2) u.\nProof.\n (** Let [t], [t1], [t2], and [u] be terms. Assume that\n [eval t tm_true] and [eval_many t1 u]. To show\n [eval_many (tm_if t t1 t2) u], by [m_step], it suffices to\n find a [t'] for which [eval (tm_if t t1 t2) t'] and\n [eval_many t' u]. Let us choose [t'] to be\n [tm_if tm_true t1 t2]. Now we can use [e_if] to show that\n [eval (tm_if t t1 t2) (tm_if tm_true t1 t2)] if we can\n show [eval t tm_true], which is actually one of our\n assumptions. Moreover, using [m_step] once more, we can\n show [eval_many (tm_if tm_true t1 t2) u] where [t'] is\n chosen to be [t1]. Doing so leaves us to show\n [eval (tm_if tm_true t1 t2) t1] and [eval_many t1 u]. The\n former holds by [e_iftrue] and the latter holds by\n assumption. *)\n\n (* to finish *)\nAdmitted.\n\n(**************************************************************)\n(** ** Working with Definitions\n - [unfold]\n*)\n\n(** *** Example\n There is a notion of equivalence on Coq terms that arises\n from the conversion rules of the underlying calculus of\n constructions. It is sometimes useful to be able to replace\n one term in a proof with an equivalent one. For instance,\n we may want to replace a defined name with its definition.\n This sort of replacement can be done the tactic [unfold].\n This tactic can be used to manipulate the goal or the\n hypotheses.\n*)\n\nDefinition strongly_diverges t :=\n forall u, eval_many t u -> ~ normal_form u.\n\nLemma unfold_example : forall t t',\n strongly_diverges t ->\n eval t t' ->\n strongly_diverges t'.\nProof.\n intros t t' Hd He.\n unfold strongly_diverges. intros u Hm.\n unfold strongly_diverges in Hd.\n apply Hd. apply m_step with (t' := t').\n apply He.\n apply Hm.\nQed.\n\n(** *** Exercise\n In reality, many tactics will perform conversion\n automatically as necessary. Try removing the uses of\n [unfold] from the above proof to check which ones were\n necessary.\n*)\n\n(**************************************************************)\n(** ** Working with Conjunction and Disjunction\n - [split]\n - [left]\n - [right]\n - [destruct] (for conjunction and disjunction)\n*)\n\n(** *** Example\n If [H] is the name of a conjunctive hypothesis, then\n [destruct H as p] will replace the hypothesis [H] with its\n components using the names in the pattern [p]. Observe the\n pattern in the example below.\n*)\nLemma m_two_conj : forall t t' t'',\n eval t t' /\\ eval t' t'' ->\n eval_many t t''.\nProof.\n intros t t' t'' H.\n destruct H as [ He1 He2 ].\n apply m_two with (t2 := t').\n apply He1.\n apply He2.\nQed.\n\n(** *** Example\n Patterns may be nested to break apart nested structures.\n Note that infix conjunction is right-associative, which is\n significant when trying to write nested patterns. We will\n later see how to use [destruct] on many different sorts of\n hypotheses.\n*)\nLemma m_three_conj : forall t t' t'' t''',\n eval t t' /\\ eval t' t'' /\\ eval t'' t''' ->\n eval_many t t'''.\nProof.\n intros t t' t'' t''' H.\n destruct H as [ He1 [ He2 He3 ] ].\n apply m_step with (t' := t').\n apply He1.\n apply m_two with (t2 := t'').\n apply He2.\n apply He3.\nQed.\n\n(** *** Example\n If your goal is a conjunction, use [split] to break it apart\n into two separate subgoals.\n*)\nLemma m_three : forall t t' t'' t''',\n eval t t' ->\n eval t' t'' ->\n eval t'' t''' ->\n eval_many t t'''.\nProof.\n intros t t' t'' t''' He1 He2 He3.\n apply m_three_conj with (t' := t') (t'' := t'').\n split.\n apply He1.\n split.\n apply He2.\n apply He3.\nQed.\n\n(** *** Exercise\n Hint: You might find lemma [m_three] useful here.\n*)\nLemma m_if_iszero_conj : forall v t2 t2' t3 t3',\n nvalue v /\\ eval t2 t2' /\\ eval t3 t3' ->\n eval_many (tm_if (tm_iszero tm_zero) t2 t3) t2' /\\\n eval_many (tm_if (tm_iszero (tm_succ v)) t2 t3) t3'.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Example\n If the goal is a disjunction, we can use the [left] or\n [right] tactics to solve it by proving the left or right\n side of the conclusion.\n*)\nLemma true_and_succ_zero_values :\n value tm_true /\\ value (tm_succ tm_zero).\nProof.\n unfold value. split.\n left. apply b_true.\n right. apply n_succ. apply n_zero.\nQed.\n\n(** *** Example\n If we have a disjunction in the context, we can use\n [destruct] to reason by cases on the hypothesis. Note the\n syntax of the associated pattern.\n*)\nLemma e_if_true_or_false : forall t1 t2,\n eval t1 tm_true \\/ eval t1 tm_false ->\n eval_many (tm_if t1 t2 t2) t2.\nProof.\n intros t1 t2 H. destruct H as [ He1 | He2 ].\n apply m_two with (t2 := tm_if tm_true t2 t2).\n apply e_if. apply He1.\n apply e_iftrue.\n apply m_two with (t2 := tm_if tm_false t2 t2).\n apply e_if. apply He2.\n apply e_iffalse.\nQed.\n\n(*\n LAB 2: (10 minutes)\n Work on the following exercise.\n*)\n\n(** *** Exercise *)\nLemma two_values : forall t u,\n value t /\\ value u ->\n bvalue t \\/\n bvalue u \\/\n (nvalue t /\\ nvalue u).\nProof.\n (** We know [value t] and [value u], which means either\n [bvalue t] or [nvalue t], and either [bvalue u] or\n [nvalue u]. Consider the case in which\n [bvalue t] holds. Then one of the disjuncts of our\n conclusion is proved. Next, consider the case in which\n [nvalue t] holds. Now consider the subcase where\n [bvalue u] holds. ... *)\n\n (* to finish *)\nAdmitted.\n\n(** *** Example\n [destruct] can be used on propositions with implications.\n This will have the effect of performing [destruct] on the\n conclusion of the implication, while leaving the hypotheses\n of the implication as additional subgoals.\n*)\nLemma destruct_example : forall bv t t' t'',\n bvalue bv ->\n (value bv -> eval t t' /\\ eval t' t'') ->\n eval_many t t''.\nProof.\n intros bv t t' t'' Hbv H. destruct H as [ H1 H2 ].\n Show 2.\n unfold value. left. apply Hbv.\n apply m_two with (t2 := t').\n apply H1.\n apply H2.\nQed.\n\n(** *** Tip\n After applying a tactic that introduces multiple subgoals,\n it is sometimes useful to see not only the subgoals\n themselves but also their hypotheses. Adding the command\n [Show n.] to your proof script to cause Coq to display the\n nth subgoal in full.\n*)\n\n\n(**************************************************************)\n(** ** Reasoning by Cases and Induction\n - [destruct] (for inductively defined propositions)\n - [induction]\n*)\n\n(** *** Example\n Use [destruct] to reason by cases on an inductively defined\n datatype or proposition.\n\n Note: It is possible to supply [destruct] with a pattern in\n these instances also. However, the patterns become\n increasingly complex for bigger inductive definitions; so it\n is often more practical to omit the pattern (thereby letting\n Coq choose the names of the terms and hypotheses in each\n case), in spite of the fact that this adds an element of\n fragility to the proof script (since the proof script will\n mention names that were system-generated).\n*)\nLemma e_iszero_nvalue : forall v,\n nvalue v ->\n eval (tm_iszero v) tm_true \\/\n eval (tm_iszero v) tm_false.\nProof.\n intros v Hn. destruct Hn.\n (* Case [n_zero].\n Note how [v] becomes [tm_zero] in the goal. *)\n left. apply e_iszerozero.\n (* Case [n_succ].\n Note how [v] becomes [tm_succ v] in the goal. *)\n right. apply e_iszerosucc. apply Hn.\nQed.\n\n(** *** Example\n You can use [induction] to reason by induction on an\n inductively defined datatype or proposition. This is the\n same as [destruct], except that it also introduces an\n induction hypothesis in the inductive cases.\n*)\nLemma m_iszero : forall t u,\n eval_many t u ->\n eval_many (tm_iszero t) (tm_iszero u).\nProof.\n intros t u Hm. induction Hm.\n apply m_refl.\n apply m_step with (t' := tm_iszero t').\n apply e_iszero. apply H.\n apply IHHm.\nQed.\n\n(*\n LAB 3: (5 minutes)\n Work on the following exercise.\n*)\n\n(** *** Exercise *)\nLemma m_trans : forall t t' u,\n eval_many t t' ->\n eval_many t' u ->\n eval_many t u.\nProof.\n (** We proceed by induction on the derivation of\n [eval_many t t'].\n Case [m_refl]: Since [t] and [t'] must be the same, our\n conclusion holds by assumption.\n Case [m_step]: Now let's rename the [t'] from the lemma\n statement to [u0] (as Coq likely will) and observe that\n there must be some [t'] (from above the line of the\n [m_step] rule) such that [eval t t'] and\n [eval_many t' u0]. Our conclusion follows from from\n an application of [m_step] with our new [t'] and our\n induction hypothesis, which allows us to piece together\n [eval_many t' u0] and [eval_many u0 u] to get\n [eval_many t' u]. *)\n\n (* to finish *)\nAdmitted.\n\n(** *** Exercise\n It is possible to use [destruct] not just on hypotheses but\n on any lemma we have proved. If we have a lemma\n<<\n lemma1 : P /\\ Q\n>>\n then we can use the tactic\n<<\n destruct lemma1 as [ H1 H2 ].\n>>\n to continue our proof with [H1 : P] and [H2 : Q] in our\n context. This works even if the lemma has antecedents (they\n become new subgoals); however it fail if the lemma has a\n universal quantifier, such as this:\n<<\n lemma2 : forall x, P(x) /\\ Q(x)\n>>\n However, remember that we can build a proof of\n [P(e) /\\ Q(e)] (which can be destructed) using the Coq\n expression [lemma2 e]. So we need to phrase our tactic as\n<<\n destruct (lemma2 e) as [ H1 H2 ].\n>>\n An example of this technique is below.\n*)\nLemma m_iszero_nvalue : forall t v,\n nvalue v ->\n eval_many t v ->\n eval_many (tm_iszero t) tm_true \\/\n eval_many (tm_iszero t) tm_false.\nProof.\n intros t v Hnv Hm.\n destruct (e_iszero_nvalue v) as [ H1 | H2 ].\n apply Hnv.\n left. apply m_trans with (t' := tm_iszero v).\n apply m_iszero. apply Hm.\n apply m_one. apply H1.\n right. apply m_trans with (t' := tm_iszero v).\n apply m_iszero. apply Hm.\n apply m_one. apply H2.\nQed.\n\n(** *** Exercise\n Prove the following lemma.\n\n Hint: You may be interested in some previously proved\n lemmas, such as [m_one] and [m_trans].\n\n Note: Even though this lemma is in a comment, its solution\n is also at the bottom. (Coq will give an error if we leave\n it uncommented since it mentions the [eval_rtc] relation,\n which was the solution to another exercise.)\n<<\nLemma eval_rtc_many : forall t u,\n eval_rtc t u ->\n eval_many t u.\n>>\n*)\n\n(** *** Exercise\n Prove the following lemma.\n<<\nLemma eval_many_rtc : forall t u,\n eval_many t u ->\n eval_rtc t u.\n>>\n*)\n\n(** *** Exercise\n Prove the following lemma.\n<<\nLemma full_eval_to_value : forall t v,\n full_eval t v ->\n value v.\n>>\n*)\n\n(**************************************************************)\n(** ** Working with Existential Quantification\n - [exists]\n - [destruct] (for existential propositions)\n*)\n\n(** *** Example\n Use [exists] to give the witness for an existential\n quantifier in your goal.\n*)\nLemma if_bvalue : forall t1 t2 t3,\n bvalue t1 ->\n exists u, eval (tm_if t1 t2 t3) u.\nProof.\n intros t1 t2 t3 Hb. destruct Hb.\n exists t2. apply e_iftrue.\n exists t3. apply e_iffalse.\nQed.\n\n(** *** Example\n You may use [destruct] to break open an existential\n hypothesis.\n*)\nLemma m_two_exists : forall t u,\n (exists w, eval t w /\\ eval w u) ->\n eval_many t u.\nProof.\n intros t u H.\n destruct H as [ w He ].\n destruct He as [ He1 He2 ].\n apply m_two with (t2 := w).\n apply He1.\n apply He2.\nQed.\n\n(** *** Example\n Tip: We can combine patterns that destruct existentials with\n patterns that destruct other logical connectives.\n\n Here is the same proof with just one use of [destruct].\n*)\nLemma m_two_exists' : forall t u,\n (exists w, eval t w /\\ eval w u) ->\n eval_many t u.\nProof.\n intros t u H. destruct H as [ w [ He1 He2 ] ].\n apply m_two with (t2 := w).\n apply He1.\n apply He2.\nQed.\n\n(** *** Example\n Tip: We give patterns to the [intros] tactic to destruct\n hypotheses as we introduce them.\n\n Here is the same proof again without any uses of [destruct].\n*)\nLemma m_two_exists'' : forall t u,\n (exists w, eval t w /\\ eval w u) ->\n eval_many t u.\nProof.\n intros t u [ w [ He1 He2 ] ].\n apply m_two with (t2 := w).\n apply He1.\n apply He2.\nQed.\n\n(** *** Exercise *)\nLemma value_can_expand : forall v,\n value v ->\n exists u, eval u v.\nProof.\n (* to finish *)\nAdmitted.\n\n(*\n LAB 4: (10 minutes)\n Work on the following exercise.\n*)\n\n(** *** Exercise\n Tip: You should find the lemma [m_iszero] useful. Use\n [Check m_iszero.] if you've forgotten its statement.\n*)\nLemma exists_iszero_nvalue : forall t,\n (exists nv, nvalue nv /\\ eval_many t nv) ->\n exists bv, eval_many (tm_iszero t) bv.\nProof.\n (** There exists some [nv] such that [nvalue nv]. Consider\n the case where [nv] is [tm_zero]. Then choose [bv] to\n be [tm_true]. By [m_trans], we can show that\n [eval_many (tm_iszero t) tm_true] by showing\n [eval_many (tm_iszero t) (tm_iszero tm_zero)] and\n [eval_many (tm_iszero tm_zero) tm_true]. The former\n follows from [m_iszero] and our assumption. The latter\n follows from [m_one] and the rule [e_iszerozero]. On the\n other hand, in the case where [nv] is built from\n [tm_succ], we choose [bv] to be [tm_false] and the proof\n follows similarly. *)\n\n (* to finish *)\nAdmitted.\n\n\n(**************************************************************)\n(** ** Working with Negation\n - [unfold not]\n - [destruct] (for negation)\n*)\n\n(** *** Example\n The standard library defines an uninhabited type [False] and\n defines [not P] to stand for [P -> False]. Furthermore, Coq\n defines the notation [~ P] to stand for [not P]. (Such\n notations only affect parsing and printing -- Coq views [not\n P] and [~ P] as being syntactically equal.)\n\n The most basic way to work with negated statements is to\n unfold [not] and treat [False] just as any other\n proposition.\n\n (Note how multiple definitions can be unfolded with one use\n of [unfold]. Also, as noted earlier, many uses of [unfold]\n are not strictly necessary. You can try deleting the uses\n from the proof below to check that the proof script still\n works.)\n*)\nLemma normal_form_succ : forall t,\n normal_form (tm_succ t) ->\n normal_form t.\nProof.\n intros t Hnf.\n unfold normal_form. unfold not.\n unfold normal_form, not in Hnf.\n intros [ t' H' ]. apply Hnf.\n exists (tm_succ t'). apply e_succ. apply H'.\nQed.\n\n(** *** Exercise *)\nLemma normal_form_to_forall : forall t,\n normal_form t ->\n forall u, ~ eval t u.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma normal_form_from_forall : forall t,\n (forall u, ~ eval t u) ->\n normal_form t.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Example\n If you happen to have [False] as a hypothesis, you may use\n [destruct] on that hypothesis to solve your goal.\n*)\nLemma False_hypothesis : forall v,\n False ->\n value v.\nProof.\n intros v H. destruct H.\nQed.\n\n(** *** Example\n Recalling that [destruct] can be used on propositions with\n antecedents and that negation is simply an abbreviation for\n an implication, using [destruct] on a negated hypothesis has\n the derived behavior of replacing our goal with the\n proposition that was negated in our context.\n\n Tip: We actually don't even need to do the unfolding below\n because [destruct] would have done it for us.\n*)\nLemma destruct_negation_example : forall t v,\n value v ->\n eval t tm_zero ->\n (value v -> normal_form t) ->\n eval tm_true tm_false.\nProof.\n intros t v Hnv He Hnf.\n unfold normal_form, not in Hnf.\n (* As usual, unfolding was optional here. *)\n destruct Hnf.\n apply Hnv.\n exists tm_zero. apply He.\nQed.\n\n(** *** Exercise\n This one may be a bit tricky. Start by using [destruct] on\n one of your hypotheses.\n*)\nLemma negation_exercise : forall v1 v2,\n ~ (value v1 \\/ value v2) ->\n ~ (~ bvalue v1 /\\ ~ bvalue v2) ->\n eval tm_true tm_false.\nProof.\n (* to finish *)\nAdmitted.\n\n(**************************************************************)\n(** ** Working with Equality\n - [reflexivity]\n - [subst]\n - [rewrite]\n - [inversion] (on equalities)\n*)\n\n(** *** Example\n If you have an equality in your context, there are several\n ways to substitute one side of the equality for the other in\n your goal or in other hypotheses.\n\n If one side of the equality is a variable [x], then the\n tactic [subst x] will replace all occurrences of [x] in the\n context and goal with the other side of the quality and will\n remove [x] from your context.\n\n Use [reflexivity] to solve a goal of the form [e = e].\n*)\nLemma equality_example_1 : forall t1 t2 t3 u1 u2,\n t1 = tm_iszero u1 ->\n t2 = tm_succ u2 ->\n t3 = tm_succ t2 ->\n tm_if t1 t2 t3 =\n tm_if (tm_iszero u1) (tm_succ u2) (tm_succ (tm_succ u2)).\nProof.\n intros t1 t2 t3 u1 u2 Heq1 Heq2 Heq3.\n subst t1. subst t2. subst t3. reflexivity.\nQed.\n\n(** *** Example\n If neither side of the equality in your context is a\n variable (or if you don't want to discard the hypothesis),\n you can use the [rewrite] tactic to perform a substitution.\n The arrow after [rewrite] indicates the direction of the\n substitution. As demonstrated, you may perform rewriting in\n the goal or in a hypothesis.\n*)\nLemma equality_example_2a : forall t u v,\n tm_succ t = tm_succ u ->\n eval (tm_succ u) v ->\n eval (tm_succ t) v.\nProof.\n intros t u v Heq He. rewrite -> Heq. apply He.\nQed.\n\nLemma equality_example_2b : forall t u v,\n tm_succ t = tm_succ u ->\n eval (tm_succ u) v ->\n eval (tm_succ t) v.\nProof.\n intros t u v Heq He. rewrite <- Heq in He. apply He.\nQed.\n\n(** *** Example\n We also note that, analogously with [destruct], we may use\n [rewrite] even with a hypothesis (or lemma) that has\n antecedents.\n*)\nLemma equality_example_2c : forall t u v,\n nvalue v ->\n (nvalue v -> tm_succ t = tm_succ u) ->\n eval (tm_succ u) v ->\n eval (tm_succ t) v.\nProof.\n intros t u v Hnv Heq He. rewrite <- Heq in He.\n apply He.\n apply Hnv.\nQed.\n\n(** *** Example\n If you need to derive additional equalities implied by an\n equality in your context (e.g., by the principle of\n constructor injectivity), you may use [inversion].\n [inversion] is a powerful tactic that uses unification to\n introduce more equalities into your context. (You will\n observe that it also performs some substitutions in your\n goal.)\n*)\nLemma equality_example_3 : forall t u,\n tm_succ t = tm_succ u ->\n t = u.\nProof.\n intros t u Heq. inversion Heq. reflexivity.\nQed.\n\n(** *** Exercise *)\nLemma equality_exercise : forall t1 t2 t3 u1 u2 u3 u4,\n tm_if t1 t2 t3 = tm_if u1 u2 u2 ->\n tm_if t1 t2 t3 = tm_if u3 u3 u4 ->\n t1 = u4.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Example\n [inversion] will also solve a goal when unification fails on\n a hypothesis. (Internally, Coq can construct a proof of\n [False] from contradictory equalities.)\n*)\nLemma equality_example_4 :\n tm_zero = tm_true ->\n eval tm_true tm_false.\nProof.\n intros Heq. inversion Heq.\nQed.\n\n(*\n LAB 5: (10 minutes)\n Work on [equality_exercise] above and [succ_not_circular]\n below.\n*)\n\n(** *** Exercise\n Note: [e1 <> e2] is a notation for [~ e1 = e2], i.e., the\n two are treated as syntactically equal.\n\n Note: This is fairly trivial to prove if we have a size\n function on terms and some automation. With just the tools\n we have described so far, it requires just a little bit of\n work.\n\n Hint: The proof requires induction on [t]. (This is the\n first example of induction on datatypes, but it is even more\n straightforward than induction on propositions.) In each\n case, unfold the negation, pull the equality into the\n context, and use [inversion] to eliminate contradictory\n equalities.\n*)\n\nLemma succ_not_circular : forall t,\n t <> tm_succ t.\nProof.\n (* to finish *)\nAdmitted.\n\n(**************************************************************)\n(** ** Reasoning by Inversion\n - [inversion] (on propositions)\n*)\n\n(** *** Example\n The [inversion] tactic also allows you to reason by\n inversion on an inductively defined proposition as in paper\n proofs: we try to match some proposition with the conclusion\n of each inference rule and only consider the cases (possibly\n none) where there is a successful unification. In those\n cases, we may use the premises of the inference rule in our\n reasoning.\n\n Since [inversion] may generate many equalities between\n variables, it is useful to know that using [subst] without\n an argument will perform all possible substitutions for\n variables. It is a little difficult to predict which\n variables will be eliminated and which will be kept by this\n tactic, but this is a typical sort of trade-off when using\n powerful tactics.\n\n (The use of [subst] in this proof is superfluous, but you\n can observe that it simplifies the context.)\n*)\nLemma value_succ_nvalue : forall t,\n value (tm_succ t) ->\n nvalue t.\nProof.\n intros t H. unfold value in H. destruct H as [ H1 | H2 ].\n (* No unification is possible -- [inversion] solves goal. *)\n inversion H1.\n (* Just the [n_succ] cases unifies with H2. *)\n inversion H2. subst. apply H0.\nQed.\n\n(*\n LAB 6: (10 minutes)\n Work on the exercise below.\n*)\n\n(** *** Exercise *)\nLemma inversion_exercise : forall t,\n normal_form t ->\n eval_many (tm_pred t) tm_zero ->\n nvalue t.\nProof.\n (** By inversion on the [eval_many] relation, then conclusion\n [eval_many (tm_pred t) tm_zero] must have been derived by\n the rule [m_step], which means there is some [t'] for\n which [eval (tm_pred t) t'] and [eval_many t' tm_zero].\n Now, by inversion on the [eval] relation, there are only\n three ways that [eval (tm_pred t) t'] could have been\n derived:\n * By [e_predzero], with [t] and [t'] both being equal to\n [tm_zero]. Our conclusion follows from [n_zero].\n * By [e_predsucc], with [t] being [tm_succ t0] where we\n have [nvalue t0]. In this case, our conclusion is\n provable with [n_succ].\n * By [e_pred], with [t] taking an evaluation step. This\n contradicts our assumption that [t] is a normal form\n (which can be shown by using [destruct] on that\n assumption). *)\n\n (* to finish *)\nAdmitted.\n\n(** *** Exercise\n Tip: Nested patterns will be useful here.\n*)\nLemma contradictory_equalities_exercise :\n (exists t, exists u, exists v,\n value t /\\\n t = tm_succ u /\\\n u = tm_pred v) ->\n eval tm_true tm_false.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma eval_fact_exercise : forall t1 t2,\n eval (tm_iszero (tm_pred t1)) t2 ->\n eval t2 tm_false ->\n exists u, t1 = tm_succ u.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma normal_form_if : forall t1 t2 t3,\n normal_form (tm_if t1 t2 t3) ->\n t1 <> tm_true /\\ t1 <> tm_false /\\ normal_form t1.\nProof.\n (* to finish *)\nAdmitted.\n\n\n(**************************************************************)\n(** ** Additional Important Tactics\n - [generalize dependent]\n - [assert]\n - [;]\n - [clear]\n*)\n\n(** *** Example\n Sometimes we need to have a tactic that moves hypotheses\n from our context back into our goal. Often this is\n because we want to perform induction in the middle of a\n proof and will not get a sufficiently general induction\n hypothesis without a goal of the correct form. (To be\n specific, if we need to have an induction hypothesis with a\n [forall] quantifier in front, then we must make sure our\n goal has a [forall] quantifier in front at the time we\n invoke the [induction] tactic.) Observe how [generalize\n dependent] achieves this in the proof below, moving the\n variable [t] and all dependent hypotheses back into the\n goal. You may want to remove the use of [generalize\n dependent] to convince yourself that it is performing an\n essential role here.\n*)\n\nLemma value_is_normal_form : forall v,\n value v ->\n normal_form v.\nProof.\n intros v [ Hb | Hn ] [ t He ].\n destruct Hb.\n inversion He.\n inversion He.\n generalize dependent t. induction Hn.\n intros t He. inversion He.\n intros u He. inversion He. subst. destruct (IHHn t').\n apply H0.\nQed.\n\n(** *** Exercise\n Coq has many operations (called \"tacticals\") to combine\n smaller tactics into larger ones.\n\n If [t1] and [t2] are tactics, then [t1; t2] is a tactic that\n executes [t1], and then executes [t2] on subgoals left by or\n newly generated by [t1]. This can help to eliminate\n repetitious use of tactics. Two idiomatic uses are\n performing [subst] after [inversion] and performing [intros]\n after [induction]. More opportunities to use this tactical\n can usually be discovered after writing a proof. (It is\n worth noting that some uses of this tactical can make proofs\n less readable or more difficult to maintain. Alternatively,\n some uses can make proofs more readable or easier to\n maintain. It is always good to think about your priorities\n when writing a proof script.)\n\n Revise the proof for [value_is_normal_form] to include uses\n of the [;] tactical.\n*)\n\n(** *** Example\n Sometimes it is helpful to be able to use forward reasoning\n in a proof. One form of forward reasoning can be done with\n the tactic [assert]. [assert] adds a new hypothesis to the\n context but asks us to first justify it.\n*)\nLemma nvalue_is_normal_form : forall v,\n nvalue v ->\n normal_form v.\nProof.\n intros v Hnv.\n assert (value v) as Hv. right. apply Hnv.\n apply value_is_normal_form. apply Hv.\nQed.\n\n(** *** Example\n [assert] can also be supplied with a tactic that proves the\n assertion. We rewrite the above proof using this form.\n*)\nLemma nvalue_is_normal_form' : forall v,\n nvalue v ->\n normal_form v.\nProof.\n intros v Hnv.\n assert (value v) as Hv by (right; apply Hnv).\n apply value_is_normal_form. apply Hv.\nQed.\n\n(** *** Example\n The proof below introduces two new, simple tactics. First,\n the tactic [replace e1 with e2] performs a substitution in\n the goal and then requires that you prove [e2 = e1] as a new\n subgoal. This often allows us to avoid more cumbersome\n forms of forward reasoning. Second, the [clear] tactic\n discards a hypothesis from the context. Of course, this\n tactic is never needed, but it can be nice to use when there\n are complicated, irrelevant hypotheses in the context.\n*)\nLemma single_step_to_multi_step_determinacy :\n (forall t u1 u2, eval t u1 -> eval t u2 -> u1 = u2) ->\n forall t v1 v2,\n eval_many t v1 -> normal_form v1 ->\n eval_many t v2 -> normal_form v2 ->\n v1 = v2.\nProof.\n intros H t v1 v2 Hm1 Hnf1 Hm2 Hnf2. induction Hm1.\n clear H. destruct Hm2.\n reflexivity.\n destruct Hnf1. exists t'. apply H.\n destruct Hm2.\n destruct Hnf2. exists t'. apply H0.\n apply IHHm1; clear IHHm1.\n apply Hnf1.\n replace t' with t'0.\n apply Hm2.\n apply H with (t := t).\n apply H1.\n apply H0.\nQed.\n\n(** *** Exercise\n This proof is lengthy and thus somewhat challenging. All of\n the techniques from this section will be useful; some will\n be essential. In particular, you will need to use\n [generalize dependent] at the beginning of the proof. You\n will find [assert] helpful in the cases where your\n assumptions are contradictory but none of them are in a\n negative form. In that situation, you can assert a negative\n statement that follows from your hypotheses (recall that\n [normal_form] is a negative statement). Finally, you will\n want to use the above lemma [nvalue_is_normal_form]. Good\n luck!\n*)\n\nTheorem eval_deterministic : forall t t' t'',\n eval t t' ->\n eval t t'' ->\n t' = t''.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise\n Prove the following lemmas. The last is quite long, and you\n may wish to wait until you know more about automation.\n<<\nLemma full_eval_from_value : forall v w,\n value v ->\n full_eval v w ->\n v = w.\n\nLemma eval_full_eval : forall t t' v,\n eval t t' ->\n full_eval t' v ->\n full_eval t v.\n\nLemma full_eval_complete : forall t v,\n value v ->\n eval_many t v ->\n full_eval t v.\n>>\n*)\n\n(**************************************************************)\n(** ** Basic Automation\n - [eapply], [esplit]\n - [auto], [eauto]\n*)\n\n(** *** Example\n You can use [eapply e] instead of [apply e with (x := e1)].\n This will generate subgoals containing unification variables\n that will get unified during subsequent uses of [apply].\n*)\nLemma m_if : forall t1 u1 t2 t3,\n eval_many t1 u1 ->\n eval_many (tm_if t1 t2 t3) (tm_if u1 t2 t3).\nProof.\n intros t1 u1 t2 t3 Hm. induction Hm.\n apply m_refl.\n eapply m_step.\n apply e_if. apply H.\n apply IHHm.\nQed.\n\n(** *** Example\n You can use [esplit] to turn an existentially quantified\n variable in your goal into a unification variable.\n*)\nLemma exists_pred_zero :\n exists u, eval (tm_pred tm_zero) u.\nProof.\n esplit. apply e_predzero.\nQed.\n\n(** *** Example\n The [auto] tactic solves goals that are solvable by any\n combination of\n - [intros]\n - [apply] (used on some local hypothesis)\n - [split], [left], [right]\n - [reflexivity]\n\n If [auto] cannot solve the goal, it will leave the proof\n state completely unchanged (without generating any errors).\n\n The lemma below is a proposition that has been contrived for\n the sake of demonstrating the scope of the [auto] tactic and\n does not say anything of practical interest. So instead of\n thinking about what it means, you should think about the\n operations that [auto] had to perform to solve the goal.\n\n Note: It is important to remember that [auto] does not\n destruct hypotheses! There are more advanced forms of\n automation available that do destruct hypotheses in some\n specific ways.\n*)\nLemma auto_example : forall t t' t'',\n eval t t' ->\n eval t' t'' ->\n (forall u, eval t t' -> eval t' u -> eval_many t u) ->\n eval t' t \\/ t = t /\\ eval_many t t''.\nProof.\n auto.\nQed.\n\n(** *** Example\n The [eauto] tactic solves goals that are solvable by some\n combination of\n - [intros]\n - [eapply] (used on some local hypothesis)\n - [split], [left], [right]\n - [esplit]\n - [reflexivity]\n\n This lemma has two significantly differences from the\n previous one, both of which render [auto] useless.\n*)\nLemma eauto_example : forall t t' t'',\n eval t t' ->\n eval t' t'' ->\n (forall u, eval t u -> eval u t'' -> eval_many t t'') ->\n eval t' t \\/ (exists u, t = u) /\\ eval_many t t''.\nProof.\n eauto.\nQed.\n\n(** *** Example\n You can enhance [auto] (or [eauto]) by appending [using x_1,\n ..., x_n], where each [x_i] is the name of some constructor\n or lemma. Then [auto] will attempt to apply those\n constructors or lemmas in addition to the assumptions in\n the local context.\n*)\nLemma eauto_using_example : forall t t' t'',\n eval t t' ->\n eval t' t'' ->\n eval t' t \\/ t = t /\\ eval_many t t''.\nProof.\n eauto using m_step, m_one.\nQed.\n\n(*\n LAB 7: (5 minutes)\n Work on the following exercise.\n*)\n\n(** *** Exercise\n Go back and rewrite your proofs for [m_one], [m_two], and\n [m_iftrue_step]. You should be able to make them very\n succinct given what you know now.\n*)\n\n(** *** Exercise\n See how short you can make these proofs.\n\n Note: This is an exercise. We are not making the claim that\n shorter proofs are necessarily better!\n\n Hint: Remember that we can connect tactics in sequence with\n [;]. However, as you can imagine, figuring out the best\n thing to write after a [;] usually involves some trial and\n error.\n*)\nLemma pred_not_circular : forall t,\n t <> tm_pred t.\nProof.\n (* to finish *)\nAdmitted.\n\nLemma m_succ : forall t u,\n eval_many t u ->\n eval_many (tm_succ t) (tm_succ u).\nProof.\n (* to finish *)\nAdmitted.\n\nLemma m_pred : forall t u,\n eval_many t u ->\n eval_many (tm_pred t) (tm_pred u).\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise\n Go back and rewrite your proofs for [m_trans] and\n [two_values]. Pulling together several tricks you've\n learned, you should be able to prove [two_values] in one\n (short) line.\n*)\n\n(** *** Note\n Sometimes there are lemmas or constructors that are so\n frequently needed by [auto] that we don't want to have to\n add them to our [using] clause each time. Coq allows us to\n request that certain propositions that always be\n considered by [auto] and [eauto].\n\n The following command adds four lemmas to the default search\n procedure of [auto].\n*)\n\nHint Resolve m_if m_succ m_pred m_iszero.\n\n(** Constructors of inductively defined propositions are some of\n the most frequently needed by [auto]. Instead of writing\n<<\n Hint Resolve b_true b_false.\n>>\n we may simply write\n<<\n Hint Constructors bvalue.\n>>\n Let's add all our constructors to [auto].\n*)\n\nHint Constructors bvalue nvalue eval eval_many.\n\n(** By default [auto] will never try to unfold definitions to\n see if a lemma or constructor can be applied. With the\n [Hint Unfold] command, we can instruct [auto] to try unfold\n definitions in the goal as it is working.\n*)\n\nHint Unfold value normal_form.\n\n(** There are a few more variants on the [Hint] command that can\n be used to further customize [auto]. You can learn about\n them in the Coq reference manual.\n*)\n\n(**************************************************************)\n(** ** Functions and Conversion\n - [Fixpoint/struct]\n - [match ... end]\n - [if ... then ... else ...]\n - [simpl]\n - [remember]\n\n In this section we start to use Coq as a programming\n language and learn how to reason about programs defined\n within Coq.\n*)\n\n(** *** Example\n Coq defines many datatypes in its standard libraries. Have\n a quick look now through the library [Datatypes] to see some\n of the basic ones, in particular [bool] and [nat]. (Note\n that constructors of the datatype [nat] are the letter [O]\n and the letter [S]. However, Coq will parse and print\n [nat]s using a standard decimal representation.)\n\n We define two more datatypes here that will be useful later.\n*)\nInductive bool_option : Set :=\n| some_bool : bool -> bool_option\n| no_bool : bool_option.\n\nInductive nat_option : Set :=\n| some_nat : nat -> nat_option\n| no_nat : nat_option.\n\n(** *** Example\n We can define simple (non-recursive) functions from one\n datatype to another using the [Definition] keyword. The\n [match] construct allows us to do case analysis on a\n datatype. The [match] expression has a first-match\n semantics and allows nested patterns; however, Coq's type\n checker demands that pattern-matching be exhaustive.\n\n We define functions below for converting between Coq [bool]s\n and boolean values in our object language.\n*)\nDefinition tm_to_bool (t : tm) : bool_option :=\n match t with\n | tm_true => some_bool true\n | tm_false => some_bool false\n | _ => no_bool\n end.\n\nDefinition bool_to_tm (b : bool) : tm :=\n match b with\n | true => tm_true\n | false => tm_false\n end.\n\n(** *** Example\n Coq also has an [if/then/else] expression. It can be used,\n not just with the type [bool] but, in fact, with any\n datatype having exactly two constructors (the first\n constructor corresponding to the [then] branch and the\n second to the [else] branch). Thus, we can define a\n function [is_bool] as below.\n*)\nDefinition is_bool (t : tm) : bool :=\n if tm_to_bool t then true else false.\n\n(** *** Example\n To define a recursive function, use [Fixpoint] instead of\n [Definition].\n\n The type system will only allow us to write functions that\n terminate. The annotation [{struct t}] here informs the\n type-checker that termination is guaranteed because the\n function is being defined by structural recursion on [t].\n*)\nFixpoint tm_to_nat (t : tm) {struct t} : nat_option :=\n match t with\n | tm_zero => some_nat O\n | tm_succ t1 =>\n match tm_to_nat t1 with\n | some_nat n => some_nat (S n)\n | no_nat => no_nat\n end\n | _ => no_nat\n end.\n\nFixpoint nat_to_tm (n : nat) {struct n} : tm :=\n match n with\n | O => tm_zero\n | S m => tm_succ (nat_to_tm m)\n end.\n\n(** *** Exercise\n Write a function [interp : tm -> tm] that returns the\n normal form of its argument according to the small-step\n semantics given by [eval].\n\n Hint: You will want to use [tm_to_nat] (or another auxiliary\n function) to prevent stuck terms from stepping in the cases\n [e_predsucc] and [e_iszerosucc].\n*)\n\n(** *** Example\n The tactic [simpl] (recursively) reduces the application of\n a function defined by pattern-matching to an argument with a\n constructor at its head. You can supply [simpl] with a\n particular expression if you want to prevent it from\n simplifying elsewhere.\n*)\nLemma bool_tm_bool : forall b,\n tm_to_bool (bool_to_tm b) = some_bool b.\nProof.\n intros b. destruct b.\n simpl (bool_to_tm true). simpl. reflexivity.\n (* It turns out that [simpl] is unnecessary above, since\n [reflexivity] can automatically check that two terms are\n convertible. *)\n reflexivity.\nQed.\n\n(** *** Example\n We can also apply the tactic [simpl] in our hypotheses.\n*)\nLemma tm_bool_tm :forall t b,\n tm_to_bool t = some_bool b ->\n bool_to_tm b = t.\nProof.\n intros t b Heq. destruct t.\n simpl in Heq. inversion Heq.\n simpl. reflexivity.\n (* As with [reflexivity], [inversion] can automatically\n perform reduction on terms as necessary, so the above use\n of [simpl] was optional. *)\n inversion Heq. reflexivity.\n simpl in Heq. inversion Heq.\n (* Again, the above use of [simpl] was optional. *)\n inversion Heq.\n inversion Heq.\n inversion Heq.\n inversion Heq.\nQed.\n\n(** *** Exercise *)\nLemma tm_to_bool_dom_includes_bvalue : forall bv,\n bvalue bv -> exists b, tm_to_bool bv = some_bool b.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma tm_to_bool_dom_only_bvalue : forall bv b,\n tm_to_bool bv = some_bool b -> bvalue bv.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Example\n Not all uses of [simpl] are optional. Sometimes they are\n necessary so that we can use the [rewrite] tactic. Observe,\n also, how using [rewrite] can automatically trigger a\n reduction if it creates a redex.\n*)\nLemma nat_tm_nat : forall n,\n tm_to_nat (nat_to_tm n) = some_nat n.\nProof.\n intros n. induction n.\n reflexivity.\n simpl. rewrite -> IHn. reflexivity.\nQed.\n\n(** *** Example\n Here's an example where it is necessary to use [simpl] on a\n hypothesis. To trigger a reduction of a [match] expression\n in a hypothesis, we use the [destruct] tactic on the\n expression being matched.\n*)\nLemma tm_nat_tm : forall t n,\n tm_to_nat t = some_nat n ->\n nat_to_tm n = t.\nProof.\n intros t. induction t; intros n Heq.\n inversion Heq.\n inversion Heq.\n inversion Heq.\n inversion Heq. reflexivity.\n simpl in Heq. destruct (tm_to_nat t).\n inversion Heq. simpl. rewrite -> IHt.\n (* Note how we may use [rewrite] even on an equation\n that is preceded by some other hypotheses. *)\n reflexivity.\n reflexivity.\n inversion Heq.\n inversion Heq.\n inversion Heq.\nQed.\n\n(** *** Exercise *)\nLemma tm_to_nat_dom_includes_nvalue : forall v,\n nvalue v -> exists n, tm_to_nat v = some_nat n.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Exercise *)\nLemma tm_to_nat_dom_only_nvalue : forall v n,\n tm_to_nat v = some_nat n -> nvalue v.\nProof.\n (* to finish *)\nAdmitted.\n\n(** *** Example\n Using the tactic [destruct] (or [induction]) on a complex\n expression (i.e., one that is not simply a variable) may not\n leave you with enough information for you to finish the\n proof. The tactic [remember] can help in these cases. Its\n usage is demonstrated below. If you are curious, try to\n finish the proof without [remember] to see what goes wrong.\n*)\nLemma remember_example : forall v,\n eval_many\n (tm_pred (tm_succ v))\n (match tm_to_nat v with\n | some_nat _ => v\n | no_nat => tm_pred (tm_succ v)\n end).\nProof.\n intros v. remember (tm_to_nat v) as x. destruct x.\n apply m_one. apply e_predsucc.\n eapply tm_to_nat_dom_only_nvalue.\n rewrite <- Heqx. reflexivity.\n apply m_refl.\nQed.\n\n(** *** Exercise\n Prove the following lemmas involving the function [interp]\n from a previous exercise:\n<<\nLemma interp_reduces : forall t,\n eval_many t (interp t).\n\nLemma interp_fully_reduces : forall t,\n normal_form (interp t).\n>>\n*)\n\n\n(**************************************************************)\n(** * Solutions to Exercises *)\n(**************************************************************)\n\nInductive eval_rtc : tm -> tm -> Prop :=\n| r_eval : forall t t',\n eval t t' ->\n eval_rtc t t'\n| r_refl : forall t,\n eval_rtc t t\n| r_trans : forall t u v,\n eval_rtc t u ->\n eval_rtc u v ->\n eval_rtc t v.\n\nInductive full_eval : tm -> tm -> Prop :=\n| f_value : forall v,\n value v ->\n full_eval v v\n| f_iftrue : forall t1 t2 t3 v,\n full_eval t1 tm_true ->\n full_eval t2 v ->\n full_eval (tm_if t1 t2 t3) v\n| f_iffalse : forall t1 t2 t3 v,\n full_eval t1 tm_false ->\n full_eval t3 v ->\n full_eval (tm_if t1 t2 t3) v\n| f_succ : forall t v,\n nvalue v ->\n full_eval t v ->\n full_eval (tm_succ t) (tm_succ v)\n| f_predzero : forall t,\n full_eval t tm_zero ->\n full_eval (tm_pred t) tm_zero\n| f_predsucc : forall t v,\n nvalue v ->\n full_eval t (tm_succ v) ->\n full_eval (tm_pred t) v\n| f_iszerozero : forall t,\n full_eval t tm_zero ->\n full_eval (tm_iszero t) tm_true\n| f_iszerosucc : forall t v,\n nvalue v ->\n full_eval t (tm_succ v) ->\n full_eval (tm_iszero t) tm_false.\n\nLemma m_one_sol : forall t t',\n eval t t' ->\n eval_many t t'.\nProof.\n intros t t' He. apply m_step with (t' := t').\n apply He.\n apply m_refl.\nQed.\n\nLemma m_two_sol : forall t t' t'',\n eval t t' ->\n eval t' t'' ->\n eval_many t t''.\nProof.\n intros t t' t'' He1 He2. apply m_step with (t' := t').\n apply He1.\n apply m_one. apply He2.\nQed.\n\nLemma m_iftrue_step_sol : forall t t1 t2 u,\n eval t tm_true ->\n eval_many t1 u ->\n eval_many (tm_if t t1 t2) u.\nProof.\n intros t t1 t2 u He Hm.\n apply m_step with (t' := tm_if tm_true t1 t2).\n apply e_if. apply He.\n apply m_step with (t' := t1).\n apply e_iftrue.\n apply Hm.\nQed.\n\nLemma m_if_iszero_conj_sol : forall v t2 t2' t3 t3',\n nvalue v /\\ eval t2 t2' /\\ eval t3 t3' ->\n eval_many (tm_if (tm_iszero tm_zero) t2 t3) t2' /\\\n eval_many (tm_if (tm_iszero (tm_succ v)) t2 t3) t3'.\nProof.\n intros v t2 t2' t3 t3' H.\n destruct H as [ Hn [ He1 He2 ] ]. split.\n apply m_three with\n (t' := tm_if tm_true t2 t3) (t'' := t2).\n apply e_if. apply e_iszerozero.\n apply e_iftrue.\n apply He1.\n apply m_three with\n (t' := tm_if tm_false t2 t3) (t'' := t3).\n apply e_if. apply e_iszerosucc. apply Hn.\n apply e_iffalse.\n apply He2.\nQed.\n\nLemma two_values_sol : forall t u,\n value t /\\ value u ->\n bvalue t \\/\n bvalue u \\/\n (nvalue t /\\ nvalue u).\nProof.\n unfold value. intros t u H.\n destruct H as [ [ Hb1 | Hn1 ] H2 ].\n left. apply Hb1.\n destruct H2 as [ Hb2 | Hn2 ].\n right. left. apply Hb2.\n right. right. split.\n apply Hn1.\n apply Hn2.\nQed.\n\nLemma m_trans_sol : forall t u v,\n eval_many t u ->\n eval_many u v ->\n eval_many t v.\nProof.\n intros t u v Hm1 Hm2. induction Hm1.\n apply Hm2.\n apply m_step with (t' := t').\n apply H.\n apply IHHm1. apply Hm2.\nQed.\n\nLemma eval_rtc_many_sol : forall t u,\n eval_rtc t u ->\n eval_many t u.\nProof.\n intros t u Hr. induction Hr.\n apply m_one. apply H.\n apply m_refl.\n apply m_trans with (t' := u).\n apply IHHr1.\n apply IHHr2.\nQed.\n\nLemma eval_many_rtc_sol : forall t u,\n eval_many t u ->\n eval_rtc t u.\nProof.\n intros t u Hm. induction Hm.\n apply r_refl.\n apply r_trans with (u := t').\n apply r_eval. apply H.\n apply IHHm.\nQed.\n\nLemma full_eval_to_value_sol : forall t v,\n full_eval t v ->\n value v.\nProof.\n intros t v Hf. induction Hf.\n apply H.\n apply IHHf2.\n apply IHHf2.\n right. apply n_succ. apply H.\n right. apply n_zero.\n right. apply H.\n left. apply b_true.\n left. apply b_false.\nQed.\n\nLemma value_can_expand_sol : forall v,\n value v ->\n exists u, eval u v.\nProof.\n intros v Hv. exists (tm_if tm_true v v). apply e_iftrue.\nQed.\n\nLemma exists_iszero_nvalue_sol : forall t,\n (exists nv, nvalue nv /\\ eval_many t nv) ->\n exists bv, eval_many (tm_iszero t) bv.\nProof.\n intros t [ nv [ Hnv Hm ]]. destruct Hnv.\n exists tm_true.\n apply m_trans with (t' := tm_iszero tm_zero).\n apply m_iszero. apply Hm.\n apply m_one. apply e_iszerozero.\n exists tm_false.\n apply m_trans with (t' := tm_iszero (tm_succ t0)).\n apply m_iszero. apply Hm.\n apply m_one. apply e_iszerosucc. apply Hnv.\nQed.\n\nLemma normal_form_to_forall_sol : forall t,\n normal_form t ->\n forall u, ~ eval t u.\nProof.\n unfold normal_form, not. intros t H u He.\n apply H. exists u. apply He.\nQed.\n\nLemma normal_form_from_forall_sol : forall t,\n (forall u, ~ eval t u) ->\n normal_form t.\nProof.\n unfold normal_form, not. intros t H [ t' Het' ].\n apply H with (u := t'). apply Het'.\nQed.\n\nLemma negation_exercise_sol : forall v1 v2,\n ~ (value v1 \\/ value v2) ->\n ~ (~ bvalue v1 /\\ ~ bvalue v2) ->\n eval tm_true tm_false.\nProof.\n intros v1 v2 H1 H2. destruct H2.\n split.\n intros Hb. destruct H1. left. left. apply Hb.\n intros Hb. destruct H1. right. left. apply Hb.\nQed.\n\nLemma equality_exercise_sol : forall t1 t2 t3 u1 u2 u3 u4,\n tm_if t1 t2 t3 = tm_if u1 u2 u2 ->\n tm_if t1 t2 t3 = tm_if u3 u3 u4 ->\n t1 = u4.\nProof.\n intros t1 t2 t3 u1 u2 u3 u4 Heq1 Heq2.\n inversion Heq1. subst t1. subst t2. subst t3.\n inversion Heq2. reflexivity.\nQed.\n\nLemma succ_not_circular_sol : forall t,\n t <> tm_succ t.\nProof.\n intros t. induction t.\n intros Heq. inversion Heq.\n intros Heq. inversion Heq.\n intros Heq. inversion Heq.\n intros Heq. inversion Heq.\n intros Heq. inversion Heq. destruct IHt. apply H0.\n intros Heq. inversion Heq.\n intros Heq. inversion Heq.\nQed.\n\nLemma inversion_exercise_sol : forall t,\n normal_form t ->\n eval_many (tm_pred t) tm_zero ->\n nvalue t.\nProof.\n intros t Hnf Hm. inversion Hm. subst. inversion H.\n apply n_zero.\n apply n_succ. apply H2.\n destruct Hnf. exists t'0. apply H2.\nQed.\n\nLemma contradictory_equalities_exercise_sol :\n (exists t, exists u, exists v,\n value t /\\\n t = tm_succ u /\\\n u = tm_pred v) ->\n eval tm_true tm_false.\nProof.\n intros [ t [ u [ v [ [ Hb | Hn ] [ eq1 eq2 ] ] ] ] ].\n destruct Hb.\n inversion eq1.\n inversion eq1.\n destruct Hn.\n inversion eq1.\n inversion eq1. subst t. subst u. inversion Hn.\nQed.\n\nLemma eval_fact_exercise_sol : forall t1 t2,\n eval (tm_iszero (tm_pred t1)) t2 ->\n eval t2 tm_false ->\n exists u, t1 = tm_succ u.\nProof.\n intros t1 t2 He1 He2. inversion He1. subst t2.\n inversion He2. subst t'.\n inversion H0. exists (tm_succ t0). reflexivity.\nQed.\n\nLemma normal_form_if_sol : forall t1 t2 t3,\n normal_form (tm_if t1 t2 t3) ->\n t1 <> tm_true /\\ t1 <> tm_false /\\ normal_form t1.\nProof.\n intros t1 t2 t3 Hnf. destruct t1.\n destruct Hnf. exists t2. apply e_iftrue.\n destruct Hnf. exists t3. apply e_iffalse.\n split.\n intros Heq. inversion Heq.\n split.\n intros Heq. inversion Heq.\n intros [t' He]. destruct Hnf. exists (tm_if t' t2 t3).\n apply e_if. apply He.\n split.\n intros Heq. inversion Heq.\n split.\n intros Heq. inversion Heq.\n intros [t' He]. inversion He.\n split.\n intros Heq. inversion Heq.\n split.\n intros Heq. inversion Heq.\n intros [t' He]. destruct Hnf. exists (tm_if t' t2 t3).\n apply e_if. apply He.\n split.\n intros Heq. inversion Heq.\n split.\n intros Heq. inversion Heq.\n intros [t' He]. destruct Hnf. exists (tm_if t' t2 t3).\n apply e_if. apply He.\n split.\n intros Heq. inversion Heq.\n split.\n intros Heq. inversion Heq.\n intros [t' He]. destruct Hnf. exists (tm_if t' t2 t3).\n apply e_if. apply He.\nQed.\n\nLemma full_eval_from_value_sol : forall v w,\n value v ->\n full_eval v w ->\n v = w.\nProof.\n intros v w Hv Hf. induction Hf.\n reflexivity.\n destruct Hv as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n destruct Hv as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n rewrite -> IHHf.\n reflexivity.\n right. apply value_succ_nvalue. apply Hv.\n destruct Hv as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n destruct Hv as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n destruct Hv as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n destruct Hv as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\nQed.\n\nLemma value_is_normal_form_sol : forall v,\n value v ->\n normal_form v.\nProof.\n intros v [ Hb | Hn ] [ t He ].\n destruct Hb; inversion He.\n generalize dependent t.\n induction Hn; intros u He; inversion He; subst.\n destruct (IHHn t'). apply H0.\nQed.\n\nTheorem eval_deterministic_sol : forall t t' t'',\n eval t t' ->\n eval t t'' ->\n t' = t''.\nProof.\n intros t t' t'' He1. generalize dependent t''.\n induction He1; intros t'' He2; inversion He2; subst.\n reflexivity.\n inversion H3.\n reflexivity.\n inversion H3.\n inversion He1.\n inversion He1.\n rewrite -> (IHHe1 t1'0).\n reflexivity.\n apply H3.\n rewrite -> (IHHe1 t'0).\n reflexivity.\n apply H0.\n reflexivity.\n inversion H0.\n reflexivity.\n assert (normal_form (tm_succ t)) as Hnf.\n apply nvalue_is_normal_form. apply n_succ. apply H.\n destruct Hnf. exists t'. apply H1.\n inversion He1.\n assert (normal_form (tm_succ t'')) as Hnf.\n apply nvalue_is_normal_form. apply n_succ. apply H0.\n destruct Hnf. exists t'. apply He1.\n rewrite -> (IHHe1 t'0).\n reflexivity.\n apply H0.\n reflexivity.\n inversion H0.\n reflexivity.\n assert (normal_form (tm_succ t)) as Hnf.\n apply nvalue_is_normal_form. apply n_succ. apply H.\n destruct Hnf. exists t'. apply H1.\n inversion He1.\n assert (normal_form (tm_succ t0)) as Hnf.\n apply nvalue_is_normal_form. apply n_succ. apply H0.\n destruct Hnf. exists t'. apply He1.\n rewrite -> (IHHe1 t'0).\n reflexivity.\n apply H0.\nQed.\n\nLemma eval_full_eval_sol : forall t t' v,\n eval t t' ->\n full_eval t' v ->\n full_eval t v.\nProof.\n intros t t' v He. generalize dependent v. induction He.\n intros v Hf. apply f_iftrue.\n apply f_value. left. apply b_true.\n apply Hf.\n intros v Hf. apply f_iffalse.\n apply f_value. left. apply b_false.\n apply Hf.\n intros v Hf. inversion Hf.\n subst. inversion H.\n inversion H0.\n inversion H0.\n subst. apply f_iftrue.\n apply IHHe. apply H3.\n apply H4.\n subst. apply f_iffalse.\n apply IHHe. apply H3.\n apply H4.\n intros v Hf. inversion Hf.\n subst. apply f_succ.\n apply value_succ_nvalue. apply H.\n apply IHHe. apply f_value. right.\n apply value_succ_nvalue. apply H.\n subst. apply f_succ.\n apply H0.\n apply IHHe. apply H1.\n intros v Hf. inversion Hf. apply f_predzero.\n apply f_value. right. apply n_zero.\n intros v Hf. assert (t = v).\n apply full_eval_from_value_sol.\n right. apply H.\n apply Hf.\n subst v. apply f_predsucc.\n apply H.\n apply f_succ.\n apply H.\n apply Hf.\n intros v Hf. inversion Hf.\n subst. destruct H as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n subst. apply f_predzero. apply IHHe. apply H0.\n subst. apply f_predsucc.\n apply H0.\n apply IHHe. apply H1.\n intros v Hf. inversion Hf. apply f_iszerozero.\n apply f_value. right. apply n_zero.\n intros v Hf. inversion Hf.\n apply f_iszerosucc with (v := t).\n apply H.\n apply f_value. right. apply n_succ. apply H.\n intros v Hf. inversion Hf.\n subst. destruct H as [ Hb | Hn ].\n inversion Hb.\n inversion Hn.\n subst. apply f_iszerozero. apply IHHe. apply H0.\n subst. apply f_iszerosucc with (v := v0).\n apply H0.\n apply IHHe. apply H1.\nQed.\n\nLemma full_eval_complete_sol : forall t v,\n value v ->\n eval_many t v ->\n full_eval t v.\nProof.\n intros t v Hv Hm. induction Hm.\n apply f_value. apply Hv.\n apply eval_full_eval_sol with (t' := t').\n apply H.\n apply IHHm. apply Hv.\nQed.\n\nLemma pred_not_circular_sol : forall t,\n t <> tm_pred t.\nProof.\n intros t H. induction t; inversion H; auto.\nQed.\n\nLemma m_succ_sol : forall t u,\n eval_many t u ->\n eval_many (tm_succ t) (tm_succ u).\nProof.\n intros t u Hm.\n induction Hm; eauto using m_refl, m_step, e_succ.\nQed.\n\nLemma m_pred_sol : forall t u,\n eval_many t u ->\n eval_many (tm_pred t) (tm_pred u).\nProof.\n intros t u Hm.\n induction Hm; eauto using m_refl, m_step, e_pred.\nQed.\n\nFixpoint interp (t : tm) {struct t} : tm :=\n match t with\n | tm_true => tm_true\n | tm_false => tm_false\n | tm_if t1 t2 t3 =>\n match interp t1 with\n | tm_true => interp t2\n | tm_false => interp t3\n | t4 => tm_if t4 t2 t3\n end\n | tm_zero => tm_zero\n | tm_succ t1 => tm_succ (interp t1)\n | tm_pred t1 =>\n match interp t1 with\n | tm_zero => tm_zero\n | tm_succ t2 =>\n match tm_to_nat t2 with\n | some_nat _ => t2\n | no_nat => tm_pred (tm_succ t2)\n end\n | t2 => tm_pred t2\n end\n | tm_iszero t1 =>\n match interp t1 with\n | tm_zero => tm_true\n | tm_succ t2 =>\n match tm_to_nat t2 with\n | some_nat _ => tm_false\n | no_nat => tm_iszero (tm_succ t2)\n end\n | t2 => tm_iszero t2\n end\n end.\n\nLemma tm_to_bool_dom_includes_bvalue_sol : forall bv,\n bvalue bv -> exists b, tm_to_bool bv = some_bool b.\nProof.\n intros bv H. destruct H.\n exists true. reflexivity.\n exists false. reflexivity.\nQed.\n\nLemma tm_to_bool_dom_only_bvalue_sol : forall bv b,\n tm_to_bool bv = some_bool b -> bvalue bv.\nProof.\n intros bv b Heq. destruct bv.\n apply b_true.\n apply b_false.\n inversion Heq.\n inversion Heq.\n inversion Heq.\n inversion Heq.\n inversion Heq.\nQed.\n\nLemma tm_to_nat_dom_includes_nvalue_sol : forall v,\n nvalue v -> exists n, tm_to_nat v = some_nat n.\nProof.\n intros v Hnv. induction Hnv.\n exists O. reflexivity.\n destruct IHHnv as [ n Heq ]. exists (S n).\n simpl. rewrite -> Heq. reflexivity.\nQed.\n\nLemma tm_to_nat_dom_only_nvalue_sol : forall v n,\n tm_to_nat v = some_nat n -> nvalue v.\nProof.\n intros v. induction v; intros n Heq.\n inversion Heq.\n inversion Heq.\n inversion Heq.\n apply n_zero.\n apply n_succ.\n simpl in Heq. destruct (tm_to_nat v).\n inversion Heq. eapply IHv. reflexivity.\n inversion Heq.\n inversion Heq.\n inversion Heq.\nQed.\n\nLemma interp_reduces_sol : forall t,\n eval_many t (interp t).\nProof.\n intros t. induction t.\n apply m_refl.\n apply m_refl.\n simpl. destruct (interp t1).\n eapply m_trans.\n apply m_if. apply IHt1.\n eapply m_trans.\n eapply m_one. apply e_iftrue.\n apply IHt2.\n eapply m_trans.\n apply m_if. apply IHt1.\n eapply m_trans.\n eapply m_one. apply e_iffalse.\n apply IHt3.\n apply m_if. apply IHt1.\n apply m_if. apply IHt1.\n apply m_if. apply IHt1.\n apply m_if. apply IHt1.\n apply m_if. apply IHt1.\n apply m_refl.\n simpl. apply m_succ. apply IHt.\n simpl. destruct (interp t).\n apply m_pred. apply IHt.\n apply m_pred. apply IHt.\n apply m_pred. apply IHt.\n eapply m_trans.\n apply m_pred. apply IHt.\n apply m_one. apply e_predzero.\n remember (tm_to_nat t0) as x. destruct x.\n eapply m_trans.\n apply m_pred. apply IHt.\n apply m_one. apply e_predsucc.\n eapply tm_to_nat_dom_only_nvalue.\n rewrite <- Heqx. reflexivity.\n apply m_pred. apply IHt.\n apply m_pred. apply IHt.\n apply m_pred. apply IHt.\n simpl. destruct (interp t).\n apply m_iszero. apply IHt.\n apply m_iszero. apply IHt.\n apply m_iszero. apply IHt.\n eapply m_trans.\n apply m_iszero. apply IHt.\n apply m_one. apply e_iszerozero.\n remember (tm_to_nat t0) as x. destruct x.\n eapply m_trans.\n apply m_iszero. apply IHt.\n apply m_one. apply e_iszerosucc.\n eapply tm_to_nat_dom_only_nvalue.\n rewrite <- Heqx. reflexivity.\n apply m_iszero. apply IHt.\n apply m_iszero. apply IHt.\n apply m_iszero. apply IHt.\nQed.\n\nLemma interp_fully_reduces_sol : forall t,\n normal_form (interp t).\nProof.\n induction t; intros [t' H].\n inversion H.\n inversion H.\n simpl in H. destruct (interp t1).\n destruct IHt2. eauto.\n destruct IHt3. eauto.\n destruct IHt1. inversion H. eauto.\n destruct IHt1. inversion H. eauto.\n destruct IHt1. inversion H. eauto.\n destruct IHt1. inversion H. eauto.\n destruct IHt1. inversion H. eauto.\n inversion H.\n destruct IHt. inversion H. eauto.\n simpl in H. destruct (interp t).\n inversion H. inversion H1.\n inversion H. inversion H1.\n inversion H. destruct IHt. eauto.\n inversion H.\n remember (tm_to_nat t0) as x. destruct x.\n destruct IHt. exists (tm_succ t').\n apply e_succ. apply H.\n inversion H; subst.\n destruct (tm_to_nat_dom_includes_nvalue t')\n as [n Heq].\n apply H1.\n rewrite <- Heqx in Heq. inversion Heq.\n destruct IHt. eauto.\n inversion H. destruct IHt. eauto.\n inversion H. destruct IHt. eauto.\n simpl in H. destruct (interp t).\n inversion H. inversion H1.\n inversion H. inversion H1.\n inversion H. destruct IHt. eauto.\n inversion H.\n remember (tm_to_nat t0) as x. destruct x.\n inversion H.\n inversion H; subst.\n destruct (tm_to_nat_dom_includes_nvalue t0)\n as [n Heq].\n apply H1.\n rewrite <- Heqx in Heq. inversion Heq.\n inversion H. destruct IHt. eauto.\n inversion H. destruct IHt. eauto.\n inversion H. destruct IHt. eauto.\nQed.\n\n(* vi:set tw=64:\nLocal Variables:\nfill-column: 64\nEnd:\n*)\n", "meta": {"author": "spire", "repo": "replib", "sha": "f296898c5a7c89787935095e116890725d0d16f3", "save_path": "github-repos/coq/spire-replib", "path": "github-repos/coq/spire-replib/replib-f296898c5a7c89787935095e116890725d0d16f3/meta/metatheory/CoqIntro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.14033624409696624, "lm_q1q2_score": 0.05246832872644291}} {"text": "Require Import ZArith.\nRequire Import List.\nRequire Import Lia.\n\n(** * Useful tactics *)\nLtac inv H := inversion H; clear H; subst.\nLtac gdep x := generalize dependent x.\n\n(* inv by name of the Inductive relation *)\nLtac invh f :=\n match goal with\n [ id: f |- _ ] => inv id\n | [ id: f _ |- _ ] => inv id\n | [ id: f _ _ |- _ ] => inv id\n | [ id: f _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ _ _ _ _ _ |- _ ] => inv id\n | [ id: f _ _ _ _ _ _ _ _ _ _ _ _ _ _ |- _ ] => inv id\n end.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\n(* ---------------------------------------------------------------- *)\n(* Tactics for replacing definitional equality with provable equality *)\nModule EqualityTactics.\n(* NC: Using a module here to show where these equality related defs\nstart and end. It appears that [Ltac] defs don't escape from sections\n... *)\n\nLemma modusponens: forall (P Q: Prop), P -> (P -> Q) -> Q.\nProof.\nauto. Qed.\n\n(* Existentially instantiate a hypothesis. *)\nLtac exploit x :=\n refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _) _)\n || refine (modusponens _ _ (x _ _) _)\n || refine (modusponens _ _ (x _) _).\n\nLtac try_exploit l :=\n try (exploit l;\n try solve [eauto];\n let H := fresh \"H\" in intros H;\n repeat match goal with\n | [H : (exists _, _) |- _ ] => destruct H\n | [H : _ /\\ _ |- _ ] => destruct H\n end;\n subst).\n\n(* NC: need to change the order of the premises, versus [modusponens],\nso I can get at the implication [P -> Q] first; the proof of [P] may\ngenerate arbitrarily many subgoals. *)\nLemma cut': forall (P Q: Prop), (P -> Q) -> P -> Q.\nProof. auto. Qed.\n\n(* Like [exploit], but using [cut']. *)\nLtac ecut' x :=\n refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _ _))\n || refine (cut' _ _ _ (x _ _ _))\n || refine (cut' _ _ _ (x _ _))\n || refine (cut' _ _ _ (x _))\n || refine (cut' _ _ _ (x)).\n\n(* Like [exact H], but allow indexes to be definitionally different if\n they are provably equal.\n\n For example, a goal\n\n H : T a1 ... an\n ---------------\n T b1 ... bn\n\n is reduced to proving\n\n a1 = b1, ..., an = bn\n\n by [exact_f_equal H].\n*)\nLtac exact_f_equal h :=\n let h_eq := fresh \"h_eq\" in\n let t := type of h in\n match goal with\n | [ |- ?g ] =>\n cut (g = t); [ intro h_eq; rewrite h_eq; exact h | f_equal; auto ]\n end.\n\n(* A generalization of [exact_f_equal] to implications.\n\n This is like [applys_eq] from LibTactics.v, except you do not need\n to specify which vars you want equalities for. See Software\n Foundations for a description of [applys_eq]:\n http://www.cis.upenn.edu/~bcpierce/sf/UseTactics.html#lab869\n\n*)\nLtac apply_f_equal h :=\n let h_specialized := fresh \"h_specialized\" in\n let t := intro h_specialized; exact_f_equal h_specialized in\n (ecut' h; [t|..]).\n\n(* Solve sub goals with [tac], using [f_equal] to make progress when\n possible\n*)\nLtac rec_f_equal tac :=\n tac || (progress f_equal; rec_f_equal tac).\n\nSection Test.\n\nOpen Scope nat.\n\nLemma test_apply_f_equal:\n forall (n1 n2: nat) (P: nat -> list (list nat) -> nat -> Prop),\n (forall a, 0 = a -> a = 0 ->\n P a (((n1+1)::nil)::nil) (n1+n2)) ->\n forall b, P (b - b) (((1+n1)::nil)::nil) (n2+n1).\nProof.\n intros ? ? ? HP ?.\n apply_f_equal HP; rec_f_equal lia.\nQed.\n\n\nLemma test_exact_f_equal: forall (n1 n2: nat) (P: nat -> nat -> Prop),\n P (n1+1) (n1+n2) -> P (1+n1) (n2+n1).\nProof.\n intros ? ? ? HP. exact_f_equal HP; lia.\nQed.\n\nLemma test_rec_f_equal:\n forall (n1 n2: nat) (P: list (list nat) -> nat -> Prop),\n P (((n1+1)::nil)::nil) (n1+n2) -> P (((1+n1)::nil)::nil) (n2+n1).\nProof.\n intros ? ? ? HP. exact_f_equal HP; rec_f_equal lia.\nQed.\n\nEnd Test.\n\nEnd EqualityTactics.\nExport EqualityTactics.\n\n(* Borrowed from CPDT *)\n(* Instantiate a quantifier in a hypothesis [H] with value [v], or,\nif [v] doesn't have the right type, with a new unification variable.\nAlso prove the lefthand sides of any implications that this exposes,\nsimplifying [H] to leave out those implications. *)\n\nLtac guess v H :=\n repeat match type of H with\n | forall x : ?T, _ =>\n match type of T with\n | Prop =>\n (let H' := fresh \"H'\" in\n assert (H' : T); [\n solve [ eauto 6 ]\n | specialize (H H'); clear H' ])\n || fail 1\n | _ =>\n specialize (H v)\n || let x := fresh \"x\" in\n evar (x : T);\n let x' := eval unfold x in x in\n clear x; specialize (H x')\n end\n end.\n\n\nLtac eq_H_intros :=\n repeat\n (match goal with\n | [ |- _ = _ -> _ ] =>\n intros ?Heq\n end).\n\nLtac eq_H_getrid :=\n repeat\n (match goal with\n | [ |- _ = _ -> _ ] =>\n intros _\n end).\n\nLtac decEq :=\n match goal with\n | [ |- _ = _ ] => f_equal\n | [ |- (?X ?A <> ?X ?B) ] =>\n cut (A <> B); [intro; congruence | try discriminate]\n end.\n\nLtac allinv :=\n repeat\n match goal with\n | [ H: Some _ = Some _ |- _ ] => inv H\n | [ H: Some _ = None |- _ ] => inv H\n | [ H: None = Some _ |- _ ] => inv H\n | _ => idtac\n end.\n\nLtac allinv' :=\n allinv ;\n (match goal with\n | [ H1: ?f _ _ = _ ,\n H2: ?f _ _ = _ |- _ ] => rewrite H1 in H2 ; inv H2\n end).\n\n(* NC: Ltac is not exported from [Section]. This is for simplifying\nthe existential in [predicted_outcome]. *)\nLtac simpl_exists_tag :=\n match goal with\n | [ H: exists _, ?x = (_,_) |- _ ] => destruct H; subst x; simpl\n end.\n\n\n(* And basic lemmas *)\nLemma rev_nil_nil (A: Type) : forall (l: list A),\n rev l = nil ->\n l = nil.\nProof.\n induction l; intros ; auto.\n simpl in *.\n exploit app_eq_nil ; eauto.\n intros [Hcont1 Hcont2].\n inv Hcont2.\nQed.\n\n(* Useful functions on lists *)\n\nSet Implicit Arguments.\n\nFixpoint zip_with_keep_rests (A B C : Type) (f : A -> B -> C)\n (xs : list A) (ys : list B) : (list C * (list A * list B)) :=\n match xs, ys with\n | x::xs', y::ys' =>\n let (zs, rest) := zip_with_keep_rests f xs' ys' in\n (f x y :: zs, rest)\n | nil, _ => (nil, (nil, ys))\n | _, nil => (nil, (xs, nil))\n end.\n\n(*\nEval compute in zip_with_keep_rests plus (1 :: 2 :: 3 :: nil)\n (1 :: 1 :: nil).\n\nEval compute in zip_with_keep_rests plus (1 :: 1 :: nil)\n (1 :: 2 :: 3 :: nil).\n*)\n\nDefinition zip_with (A B C : Type) (f : A -> B -> C)\n (xs : list A) (ys : list B) : list C :=\n fst (zip_with_keep_rests f xs ys).\n\nFixpoint consecutive_with (A B : Type) (f : A -> A -> B) (xs : list A)\n : list B :=\n match xs with\n | nil => nil\n | x1 :: xs' =>\n match xs' with\n | nil => nil\n | x2 :: xs'' => f x1 x2 :: consecutive_with f xs'\n end\n end.\n\nDefinition consecutive (A : Type) := consecutive_with (@pair A A).\n\n(*\nEval compute in consecutive (1 :: 2 :: 3 :: 4 :: 5 :: nil).\n*)\n\nFixpoint last_with (A B : Type) (f : A -> B) (l : list A) (d : B) : B :=\n match l with\n | nil => d\n | a :: nil => f a\n | a :: l => last_with f l d\n end.\n\nDefinition last_opt (A : Type) xs := last_with (@Some A) xs None.\n\n(*\nEval compute in last_opt (1 :: 2 :: 3 :: nil).\nEval compute in last_opt (@nil nat).\n*)\n\nFixpoint snoc (A : Type) (xs : list A) (y : A) : list A :=\n match xs with\n | nil => y :: nil\n | x :: xs' => x :: (snoc xs' y)\n end.\n\nFixpoint init (X : Type) (xs : list X) : list X :=\n match xs with\n | nil => nil\n | x1 :: xs' =>\n match xs' with\n | nil => nil\n | x2 :: xs'' => x1 :: (init xs')\n end\n end.\n\n(*\nEval compute in init (1 :: 2 :: 3 :: nil).\nEval compute in init (1 :: nil).\nEval compute in init (@nil nat).\n*)\n(** * Finite and infinite lists *)\n\nCoInductive colist (A : Type) : Type :=\n | Nil : colist A\n | Cons : A -> colist A -> colist A.\n\nArguments Nil {A}.\n\nFixpoint list_to_colist (A : Type) (xs : list A) : colist A :=\n match xs with\n | nil => Nil\n | x :: xs' => Cons x (list_to_colist xs')\n end.\n\nCoFixpoint map_colist (A B: Type) (f: A -> B) (t: colist A) : colist B :=\n match t with\n | Nil => Nil\n | Cons a ta => Cons (f a) (map_colist f ta)\n end.\n\nDefinition frob A (t : colist A) : colist A :=\n match t with\n | Cons h t' => Cons h t'\n | Nil => Nil\n end.\n\nTheorem frob_eq : forall A (t : colist A), t = frob t.\n destruct t; reflexivity.\nQed.\n\n(* XXX: This could even be a function *)\nInductive list_prefix_colist {T} : list T -> colist T -> Prop :=\n | lpc_stop : forall c, list_prefix_colist nil c\n | lpc_equal : forall e l c,\n list_prefix_colist l c ->\n list_prefix_colist (e :: l) (Cons e c).\n\nHint Constructors list_prefix_colist : core.\n\nFixpoint index_list A n (xs : list A) : option A :=\n match xs, n with\n | nil, _ => None\n | x :: _, 0 => Some x\n | _ :: xs', S n' => index_list n' xs'\n end.\n\nLemma index_list_nil : forall A pc,\n index_list pc nil = @None A .\nProof.\n induction pc; auto.\nQed.\n\nDefinition index_list_Z A i (xs: list A) : option A :=\n if Z.ltb i 0 then\n None\n else\n index_list (Z.to_nat i) xs.\n\nLemma index_list_Z_nil : forall A i,\n index_list_Z i nil = @None A .\nProof.\n intros. unfold index_list_Z. destruct (i \n index_list (Z.to_nat i) l = Some v.\nProof.\n intros. unfold index_list_Z in *. destruct (i = 0)%Z ->\n index_list_Z i l1 = index_list_Z (i+1) (a::l1).\nProof.\n induction i; intros.\n auto.\n unfold index_list_Z. simpl.\n replace (Pos.to_nat (p + 1)) with ((Pos.to_nat p)+1)%nat by (zify; lia).\n eapply index_list_cons with (l:= l1) (a:= a) ; eauto.\n zify; lia.\nQed.\n\nLemma index_list_Z_app:\n forall (T : Type) (l1 l2: list T) (i : Z),\n i = Z.of_nat (length l1) -> index_list_Z i (l1 ++ l2) = index_list_Z 0 l2.\nProof.\n induction l1; intros.\n simpl in *. subst. auto.\n simpl (length (a::l1)) in H. zify.\n simpl.\n replace i with (i - 1 + 1)%Z by lia.\n erewrite <- index_list_Z_cons by try lia.\n eapply IHl1. lia.\nQed.\n\nLemma index_list_Z_eq (T: Type) : forall (l1 l2: list T),\n (forall i, index_list_Z i l1 = index_list_Z i l2) ->\n l1 = l2.\nProof.\n induction l1; intros.\n destruct l2 ; auto.\n assert (HCont:= H 0%Z). inv HCont.\n destruct l2.\n assert (HCont:= H 0%Z). inv HCont.\n assert (a = t).\n assert (Helper:= H 0%Z). inv Helper. auto.\n inv H0.\n erewrite IHl1 ; eauto.\n intros. destruct i.\n erewrite index_list_Z_cons with (a:= t); eauto; try lia.\n erewrite H ; eauto.\n erewrite index_list_Z_cons with (a:= t); eauto; try (zify ; lia).\n erewrite H ; eauto. symmetry. eapply index_list_Z_cons; eauto. zify; lia.\n destruct l1, l2 ; auto.\nQed.\n\nLemma index_list_valid (T:Type): forall n (l:list T) v,\n index_list n l = Some v -> n < length l.\nProof.\n induction n; intros; destruct l; simpl in H.\n inv H.\n inv H. simpl. lia.\n inv H.\n pose proof (IHn _ _ H). simpl. lia.\nQed.\n\nLemma index_list_Z_valid (T:Type): forall i (l:list T) v,\n index_list_Z i l = Some v -> (0 <= i)%Z /\\ (Z.to_nat i < length l)%nat.\nProof.\n intros.\n unfold index_list_Z in H. destruct ((i None\n | _ :: xs', 0 => Some (y :: xs')\n | a :: xs', S n' =>\n match update_list n' y xs' with\n | None => None\n | Some l => Some (a::l)\n end\n end.\n\nFixpoint update_list_list {A} (new : list A) (old : list A) : list A :=\n match new, old with\n | _, nil => new\n | nil, _ => old\n | n :: new', _ :: old' => n :: update_list_list new' old'\n end.\n\nLemma index_list_update_list_list (T:Type) :\n forall i (new old : list T),\n (i < length new)%nat ->\n index_list i (update_list_list new old) =\n index_list i new.\nProof.\n induction i as [|i IH];\n intros [|n new] [|o old]; simpl; trivial; try lia.\n intros H.\n apply IH.\n lia.\nQed.\n\nLemma index_list_Z_update_list_list (T:Type) :\n forall i (new old : list T),\n (i < Z_of_nat (length new))%Z ->\n index_list_Z i (update_list_list new old) =\n index_list_Z i new.\nProof.\n intros.\n unfold index_list_Z.\n generalize (Z.ltb_spec0 i 0).\n intros REFL.\n destruct (i \n l' = nil ->\n False.\nProof.\n destruct l; intros.\n destruct a ; simpl in * ; congruence.\n destruct a0 ; simpl in *. congruence.\n destruct update_list. inv H.\n congruence.\n congruence.\nQed.\n\n\nLemma index_list_map : forall (A B: Type) m x (e:A) (f: A -> B),\n index_list x m = Some e ->\n index_list x (map f m) = Some (f e).\nProof.\n induction m ; intros.\n - rewrite index_list_nil in *. inv H.\n - destruct x ; simpl in *.\n inv H; auto.\n eauto.\nQed.\n\nDefinition update_list_Z A i y (xs: list A) : option (list A) :=\n if Z.ltb i 0 then\n None\n else\n update_list (Z.to_nat i) y xs.\n\nLemma update_Z_some_not_nil : forall A (v:A) l i l',\n update_list_Z i v l = Some l' ->\n l' = nil ->\n False.\nProof.\n intros. unfold update_list_Z in *. destruct (i \n update_list (Z.to_nat i) v l = Some l'.\nProof.\n intros. unfold update_list_Z in *. destruct (i \n index_list a l' = Some v.\nProof.\n induction l ; intros.\n destruct a ; simpl in *; inv H.\n destruct a0 ; simpl in *; inv H; auto.\n case_eq (update_list a0 v l) ; intros ; rewrite H in * ; inv H1.\n auto.\nQed.\n\nLemma update_list_Z_spec (T: Type) : forall (v: T) l a l',\n update_list_Z a v l = Some l' ->\n index_list_Z a l' = Some v.\nProof.\n unfold update_list_Z, index_list_Z. intros.\n destruct (a \n n <> n' ->\n index_list n' l = index_list n' l'.\nProof.\n induction l; intros.\n destruct n; simpl in *; inv H.\n destruct n.\n destruct n'.\n exfalso; lia.\n destruct l'; inv H.\n simpl. auto.\n destruct n'.\n destruct l'; inv H.\n destruct (update_list n v l); inv H2.\n destruct (update_list n v l); inv H2.\n auto.\n destruct l'; inv H.\n destruct (update_list n v l); inv H2.\n simpl.\n destruct (update_list n v l) eqn:?; inv H2.\n eapply IHl; eauto.\nQed.\n\n\nLemma update_list_Z_spec2 (T:Type) : forall (v:T) l a a' l',\n update_list_Z a v l = Some l' ->\n a' <> a ->\n index_list_Z a' l = index_list_Z a' l'.\nProof.\n unfold update_list_Z, index_list_Z. intros.\n destruct (a \n exists l', update_list n v l = Some l'.\nProof.\n induction l; intros.\n - inv H.\n - destruct n.\n + simpl. eauto.\n + simpl. edestruct IHl as [l' E]. simpl in H. instantiate (1:= n). lia.\n eexists. rewrite E. eauto.\nQed.\n\nLemma filter_cons_inv_strong :\n forall X (l1 : list X) x2 l2\n (f : X -> bool),\n x2 :: l2 = filter f l1 ->\n exists l11 l12,\n l1 = l11 ++ l12 /\\\n filter f l11 = x2 :: nil /\\\n filter f l12 = l2.\nProof.\n intros X l1.\n induction l1 as [|x1 l1 IH]; simpl; try congruence.\n intros.\n destruct (f x1) eqn:E.\n - exists (x1 :: nil).\n exists l1.\n simpl.\n rewrite E.\n inv H.\n eauto.\n - exploit IH; eauto.\n clear IH.\n intros [l11 [l12 [H1 [H2 H3]]]].\n subst.\n exists (x1 :: l11).\n exists l12.\n simpl.\n rewrite E. eauto.\nQed.\n\nLemma filter_app :\n forall X (l1 l2 : list X) (f : X -> bool),\n filter f (l1 ++ l2) = filter f l1 ++ filter f l2.\nProof.\n induction l1 as [|x l1 IH]; simpl; intros. trivial.\n rewrite IH. destruct (f x); auto.\nQed.\n\nLemma update_list_Z_Some (T:Type): forall (v:T) l (i:Z),\n (0 <= i)%Z ->\n Z.to_nat i < length l ->\n exists l', update_list_Z i v l = Some l'.\nProof.\n intros. unfold update_list_Z.\n destruct (i \n length m' = length m.\nProof.\n induction a; intros.\n - destruct m; simpl in *.\n + inv H.\n + inversion H; subst; reflexivity.\n - destruct m; simpl in *.\n + inv H.\n + destruct (update_list a vl m) eqn:?.\n * exploit IHa; eauto.\n inversion H; subst.\n intros eq; rewrite <- eq; reflexivity.\n * inv H.\nQed.\n\nLemma app_same_length_eq (T: Type): forall (l1 l2 l3 l4: list T),\n l1++l2 = l3++l4 ->\n length l1 = length l3 ->\n l1 = l3.\nProof.\n induction l1; intros; simpl in *.\n destruct l3; auto. inv H0.\n destruct l3. inv H0. simpl in *.\n inv H. erewrite IHl1 ; eauto.\nQed.\n\nLemma app_same_length_eq_rest (T: Type): forall (l1 l2 l3 l4: list T),\n l1++l2 = l3++l4 ->\n length l1 = length l3 ->\n l2 = l4.\nProof.\n intros.\n exploit app_same_length_eq; eauto.\n intro Heq ; inv Heq.\n gdep l3. induction l3 ; intros; auto.\n simpl in *.\n inv H. eauto.\nQed.\n\nDefinition is_some T (o : option T) :=\n match o with\n | Some _ => true\n | None => false\n end.\n\nDefinition remove_none {T} (l : list (option T)) :=\n filter (@is_some _) l.\n\nInductive with_silent {T:Type} := | E (e:T) | Silent.\nNotation \"T +τ\" := (@with_silent T) (at level 1).\nNotation \" 'τ' \" := (Silent) (at level 1).\n\n(** Reflexive transitive closure. *)\nDefinition op_cons (E: Type) (oe: E+τ) (l: list E) :=\n match oe with\n | E e => e::l\n | Silent => l\n end.\n\n\nInductive star (S E: Type) (Rstep: S -> E+τ -> S -> Prop): S -> list E -> S -> Prop :=\n | star_refl: forall s,\n star Rstep s nil s\n | star_step: forall s1 s2 s3 e t t',\n Rstep s1 e s2 -> star Rstep s2 t s3 ->\n t' = (op_cons e t) ->\n star Rstep s1 t' s3.\nHint Constructors star : core.\n\nLemma op_cons_app : forall E (e: E+τ) t t', (op_cons e t)++t' = op_cons e (t++t').\nProof. intros. destruct e; reflexivity. Qed.\n\nLemma star_right : forall S E (Rstep: S -> E+τ -> S -> Prop) s1 s2 t,\n star Rstep s1 t s2 ->\n forall s3 e t',\n Rstep s2 e s3 ->\n t' = (t++(op_cons e nil)) ->\n star Rstep s1 t' s3.\nProof.\n induction 1; intros.\n eapply star_step; eauto.\n exploit IHstar; eauto. intros.\n inv H3. rewrite op_cons_app; eauto.\nQed.\n\nInductive plus (S E: Type) (Rstep: S -> E+τ -> S -> Prop): S -> list E -> S -> Prop :=\n | plus_step: forall s t s' e,\n Rstep s e s' ->\n t = (op_cons e nil) ->\n plus Rstep s t s'\n | plus_trans: forall s1 s2 s3 e t t',\n Rstep s1 e s2 -> plus Rstep s2 t s3 ->\n t' = (op_cons e t) ->\n plus Rstep s1 t' s3.\n\nHint Constructors star : core.\nHint Constructors plus : core.\n\nLemma plus_right : forall E S (Rstep: S -> E+τ -> S -> Prop) s1 s2 t,\n plus Rstep s1 t s2 ->\n forall s3 e t',\n t' = (t++(op_cons e nil)) ->\n Rstep s2 e s3 -> plus Rstep s1 t' s3.\nProof.\n induction 1; intros.\n inv H1.\n rewrite op_cons_app. simpl.\n eapply plus_trans; eauto.\n exploit IHplus; eauto.\n inv H2. rewrite op_cons_app. eauto.\nQed.\n\nLemma step_star_plus :\n forall (S E: Type)\n (Rstep: S -> E+τ -> S -> Prop) s1 t s2\n (STAR : star Rstep s1 t s2)\n (NEQ : s1 <> s2),\n plus Rstep s1 t s2.\nProof.\n intros. inv STAR. congruence.\n clear NEQ.\n gdep e. gdep s1.\n induction H0; subst; eauto.\nQed.\nHint Resolve step_star_plus : core.\n\nLemma star_trans: forall S E (Rstep: S -> E+τ -> S -> Prop) s0 t s1,\n star Rstep s0 t s1 ->\n forall t' s2,\n star Rstep s1 t' s2 ->\n star Rstep s0 (t++t') s2.\nProof.\n induction 1.\n - auto.\n - inversion 1.\n + rewrite app_nil_r.\n subst; econstructor; eauto.\n + subst; econstructor; eauto.\n rewrite op_cons_app; reflexivity.\nQed.\n\n\n\nFixpoint replicate T (a: T) n : list T :=\n match n with\n | O => nil\n | S n => a::(replicate a n)\n end.\n\nSection IfDec.\n\nVariables (P : Prop) (P_dec : {P} + {~P}) (T : Type) (e1 e2 : T).\n\nLemma if_dec_left : P -> (if P_dec then e1 else e2) = e1.\nProof. intros. destruct P_dec; tauto. Qed.\n\nLemma if_dec_right : ~P -> (if P_dec then e1 else e2) = e2.\nProof. intros. destruct P_dec; tauto. Qed.\n\nEnd IfDec.\n\nSection Arith.\nLocal Open Scope Z_scope.\n\nLemma basic_arithmetic:\n forall v1 v2, (v2 - v1 =? 0) = (v1 =? v2).\n Proof.\n intuition; destruct (v1 =? v2) eqn:E;\n try (rewrite Z.eqb_eq in *); try (rewrite Z.eqb_neq in *); lia.\n Qed.\n\nEnd Arith.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/basic_machines/Utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11279539882690351, "lm_q1q2_score": 0.052438758158315495}} {"text": "(** * Example_doc\n This is an example file\n\n----\n\n Here is a list :\n - With a first item\n - And a second\n*)\n\n(* Now we write some code ! *)\nDefinition id (n : nat) := n.\n\n(** This returns the _value 42_ *)\nEval compute in id 42.\n\n\n", "meta": {"author": "thethirdman", "repo": "rapport_stage", "sha": "6b00f31ec10b6f1a293b2e77b30782a3a6da4afc", "save_path": "github-repos/coq/thethirdman-rapport_stage", "path": "github-repos/coq/thethirdman-rapport_stage/rapport_stage-6b00f31ec10b6f1a293b2e77b30782a3a6da4afc/pres_pps/input.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.12592277631593438, "lm_q1q2_score": 0.05224521455300586}} {"text": "(* -*- coding: utf-8; coq-prog-args: (\"-coqlib\" \"../..\" \"-R\" \"..\" \"Coq\" \"-top\" \"Coq.Classes.Morphisms\") -*- *)\n(************************************************************************)\n(* * The Coq Proof Assistant / The Coq Development Team *)\n(* v * INRIA, CNRS and contributors - Copyright 1999-2018 *)\n(* B) _ _] goal, making proof-search much\n slower. A cleaner solution would be to be able to set different\n priorities in different hint bases and select a particular hint\n database for resolution of a type class constraint. *)\n\n Class ProperProxy (R : relation A) (m : A) : Prop :=\n proper_proxy : R m m.\n\n Lemma eq_proper_proxy (x : A) : ProperProxy (@eq A) x.\n Proof. firstorder. Qed.\n \n Lemma reflexive_proper_proxy `(Reflexive A R) (x : A) : ProperProxy R x.\n Proof. firstorder. Qed.\n\n Lemma proper_proper_proxy x `(Proper R x) : ProperProxy R x.\n Proof. firstorder. Qed.\n\n (** Respectful morphisms. *)\n \n (** The fully dependent version, not used yet. *)\n \n Definition respectful_hetero\n (A B : Type)\n (C : A -> Type) (D : B -> Type)\n (R : A -> B -> Prop)\n (R' : forall (x : A) (y : B), C x -> D y -> Prop) :\n (forall x : A, C x) -> (forall x : B, D x) -> Prop :=\n fun f g => forall x y, R x y -> R' x y (f x) (g y).\n\n (** The non-dependent version is an instance where we forget dependencies. *)\n \n Definition respectful (R : relation A) (R' : relation B) : relation (A -> B) :=\n Eval compute in @respectful_hetero A A (fun _ => B) (fun _ => B) R (fun _ _ => R').\n\nEnd Proper.\n\n(** We favor the use of Leibniz equality or a declared reflexive relation \n when resolving [ProperProxy], otherwise, if the relation is given (not an evar),\n we fall back to [Proper]. *)\nHint Extern 1 (ProperProxy _ _) => \n class_apply @eq_proper_proxy || class_apply @reflexive_proper_proxy : typeclass_instances.\n\nHint Extern 2 (ProperProxy ?R _) => \n not_evar R; class_apply @proper_proper_proxy : typeclass_instances.\n\n(** Notations reminiscent of the old syntax for declaring morphisms. *)\nDelimit Scope signature_scope with signature.\n\nModule ProperNotations.\n\n Notation \" R ++> R' \" := (@respectful _ _ (R%signature) (R'%signature))\n (right associativity, at level 55) : signature_scope.\n\n Notation \" R ==> R' \" := (@respectful _ _ (R%signature) (R'%signature))\n (right associativity, at level 55) : signature_scope.\n\n Notation \" R --> R' \" := (@respectful _ _ (flip (R%signature)) (R'%signature))\n (right associativity, at level 55) : signature_scope.\n\nEnd ProperNotations.\n\nArguments Proper {A}%type R%signature m.\nArguments respectful {A B}%type (R R')%signature _ _.\n\nExport ProperNotations.\n\nLocal Open Scope signature_scope.\n\n(** [solve_proper] try to solve the goal [Proper (?==> ... ==>?) f]\n by repeated introductions and setoid rewrites. It should work\n fine when [f] is a combination of already known morphisms and\n quantifiers. *)\n\nLtac solve_respectful t :=\n match goal with\n | |- respectful _ _ _ _ =>\n let H := fresh \"H\" in\n intros ? ? H; solve_respectful ltac:(setoid_rewrite H; t)\n | _ => t; reflexivity\n end.\n\nLtac solve_proper := unfold Proper; solve_respectful ltac:(idtac).\n\n(** [f_equiv] is a clone of [f_equal] that handles setoid equivalences.\n For example, if we know that [f] is a morphism for [E1==>E2==>E],\n then the goal [E (f x y) (f x' y')] will be transformed by [f_equiv]\n into the subgoals [E1 x x'] and [E2 y y'].\n*)\n\nLtac f_equiv :=\n match goal with\n | |- ?R (?f ?x) (?f' _) =>\n let T := type of x in\n let Rx := fresh \"R\" in\n evar (Rx : relation T);\n let H := fresh in\n assert (H : (Rx==>R)%signature f f');\n unfold Rx in *; clear Rx; [ f_equiv | apply H; clear H; try reflexivity ]\n | |- ?R ?f ?f' =>\n solve [change (Proper R f); eauto with typeclass_instances | reflexivity ]\n | _ => idtac\n end.\n\nSection Relations.\n Let U := Type.\n Context {A B : U} (P : A -> U).\n\n (** [forall_def] reifies the dependent product as a definition. *)\n \n Definition forall_def : Type := forall x : A, P x.\n \n (** Dependent pointwise lifting of a relation on the range. *)\n \n Definition forall_relation \n (sig : forall a, relation (P a)) : relation (forall x, P x) :=\n fun f g => forall a, sig a (f a) (g a).\n\n (** Non-dependent pointwise lifting *)\n Definition pointwise_relation (R : relation B) : relation (A -> B) :=\n fun f g => forall a, R (f a) (g a).\n\n Lemma pointwise_pointwise (R : relation B) :\n relation_equivalence (pointwise_relation R) (@eq A ==> R).\n Proof. intros. split; reduce; subst; firstorder. Qed.\n \n (** Subrelations induce a morphism on the identity. *)\n \n Global Instance subrelation_id_proper `(subrelation A RA RA') : Proper (RA ==> RA') id.\n Proof. firstorder. Qed.\n\n (** The subrelation property goes through products as usual. *)\n \n Lemma subrelation_respectful `(subl : subrelation A RA' RA, subr : subrelation B RB RB') :\n subrelation (RA ==> RB) (RA' ==> RB').\n Proof. unfold subrelation in *; firstorder. Qed.\n\n (** And of course it is reflexive. *)\n \n Lemma subrelation_refl R : @subrelation A R R.\n Proof. unfold subrelation; firstorder. Qed.\n\n (** [Proper] is itself a covariant morphism for [subrelation].\n We use an unconvertible premise to avoid looping.\n *)\n \n Lemma subrelation_proper `(mor : Proper A R' m) \n `(unc : Unconvertible (relation A) R R')\n `(sub : subrelation A R' R) : Proper R m.\n Proof.\n intros. apply sub. apply mor.\n Qed.\n\n Global Instance proper_subrelation_proper :\n Proper (subrelation ++> eq ==> impl) (@Proper A).\n Proof. reduce. subst. firstorder. Qed.\n\n Global Instance pointwise_subrelation `(sub : subrelation B R R') :\n subrelation (pointwise_relation R) (pointwise_relation R') | 4.\n Proof. reduce. unfold pointwise_relation in *. apply sub. apply H. Qed.\n \n (** For dependent function types. *)\n Lemma forall_subrelation (R S : forall x : A, relation (P x)) :\n (forall a, subrelation (R a) (S a)) -> subrelation (forall_relation R) (forall_relation S).\n Proof. reduce. apply H. apply H0. Qed.\nEnd Relations.\n\nTypeclasses Opaque respectful pointwise_relation forall_relation.\nArguments forall_relation {A P}%type sig%signature _ _.\nArguments pointwise_relation A%type {B}%type R%signature _ _.\n \nHint Unfold Reflexive : core.\nHint Unfold Symmetric : core.\nHint Unfold Transitive : core.\n\n(** Resolution with subrelation: favor decomposing products over applying reflexivity\n for unconstrained goals. *)\nLtac subrelation_tac T U :=\n (is_ground T ; is_ground U ; class_apply @subrelation_refl) ||\n class_apply @subrelation_respectful || class_apply @subrelation_refl.\n\nHint Extern 3 (@subrelation _ ?T ?U) => subrelation_tac T U : typeclass_instances.\n\nCoInductive apply_subrelation : Prop := do_subrelation.\n\nLtac proper_subrelation :=\n match goal with\n [ H : apply_subrelation |- _ ] => clear H ; class_apply @subrelation_proper\n end.\n\nHint Extern 5 (@Proper _ ?H _) => proper_subrelation : typeclass_instances.\n\n(** Essential subrelation instances for [iff], [impl] and [pointwise_relation]. *)\n\nInstance iff_impl_subrelation : subrelation iff impl | 2.\nProof. firstorder. Qed.\n\nInstance iff_flip_impl_subrelation : subrelation iff (flip impl) | 2.\nProof. firstorder. Qed.\n\n(** We use an extern hint to help unification. *)\n\nHint Extern 4 (subrelation (@forall_relation ?A ?B ?R) (@forall_relation _ _ ?S)) =>\n apply (@forall_subrelation A B R S) ; intro : typeclass_instances.\n\nSection GenericInstances.\n (* Share universes *)\n Let U := Type.\n Context {A B C : U}.\n\n (** We can build a PER on the Coq function space if we have PERs on the domain and\n codomain. *)\n \n Program Instance respectful_per `(PER A R, PER B R') : PER (R ==> R').\n\n Next Obligation.\n Proof with auto.\n assert(R x0 x0).\n transitivity y0... symmetry...\n transitivity (y x0)... \n Qed.\n\n (** The complement of a relation conserves its proper elements. *)\n \n Program Definition complement_proper\n `(mR : Proper (A -> A -> Prop) (RA ==> RA ==> iff) R) :\n Proper (RA ==> RA ==> iff) (complement R) := _.\n \n Next Obligation.\n Proof.\n unfold complement.\n pose (mR x y H x0 y0 H0).\n intuition.\n Qed.\n \n (** The [flip] too, actually the [flip] instance is a bit more general. *)\n\n Program Definition flip_proper\n `(mor : Proper (A -> B -> C) (RA ==> RB ==> RC) f) :\n Proper (RB ==> RA ==> RC) (flip f) := _.\n \n Next Obligation.\n Proof.\n apply mor ; auto.\n Qed.\n\n\n (** Every Transitive relation gives rise to a binary morphism on [impl],\n contravariant in the first argument, covariant in the second. *)\n \n Global Program \n Instance trans_contra_co_morphism\n `(Transitive A R) : Proper (R --> R ++> impl) R.\n \n Next Obligation.\n Proof with auto.\n transitivity x...\n transitivity x0...\n Qed.\n\n (** Proper declarations for partial applications. *)\n\n Global Program \n Instance trans_contra_inv_impl_morphism\n `(Transitive A R) : Proper (R --> flip impl) (R x) | 3.\n\n Next Obligation.\n Proof with auto.\n transitivity y...\n Qed.\n\n Global Program \n Instance trans_co_impl_morphism\n `(Transitive A R) : Proper (R ++> impl) (R x) | 3.\n\n Next Obligation.\n Proof with auto.\n transitivity x0...\n Qed.\n\n Global Program \n Instance trans_sym_co_inv_impl_morphism\n `(PER A R) : Proper (R ++> flip impl) (R x) | 3.\n\n Next Obligation.\n Proof with auto.\n transitivity y... symmetry...\n Qed.\n\n Global Program Instance trans_sym_contra_impl_morphism\n `(PER A R) : Proper (R --> impl) (R x) | 3.\n\n Next Obligation.\n Proof with auto.\n transitivity x0... symmetry...\n Qed.\n\n Global Program Instance per_partial_app_morphism\n `(PER A R) : Proper (R ==> iff) (R x) | 2.\n\n Next Obligation.\n Proof with auto.\n split. intros ; transitivity x0...\n intros.\n transitivity y...\n symmetry...\n Qed.\n\n (** Every Transitive relation induces a morphism by \"pushing\" an [R x y] on the left of an [R x z] proof to get an [R y z] goal. *)\n\n Global Program \n Instance trans_co_eq_inv_impl_morphism\n `(Transitive A R) : Proper (R ==> (@eq A) ==> flip impl) R | 2.\n\n Next Obligation.\n Proof with auto.\n transitivity y...\n Qed.\n\n (** Every Symmetric and Transitive relation gives rise to an equivariant morphism. *)\n\n Global Program \n Instance PER_morphism `(PER A R) : Proper (R ==> R ==> iff) R | 1.\n\n Next Obligation.\n Proof with auto.\n split ; intros.\n transitivity x0... transitivity x... symmetry...\n\n transitivity y... transitivity y0... symmetry...\n Qed.\n\n Lemma symmetric_equiv_flip `(Symmetric A R) : relation_equivalence R (flip R).\n Proof. firstorder. Qed.\n\n Global Program Instance compose_proper RA RB RC :\n Proper ((RB ==> RC) ==> (RA ==> RB) ==> (RA ==> RC)) (@compose A B C).\n\n Next Obligation.\n Proof.\n simpl_relation.\n unfold compose. apply H. apply H0. apply H1.\n Qed.\n\n (** Coq functions are morphisms for Leibniz equality,\n applied only if really needed. *)\n\n Global Instance reflexive_eq_dom_reflexive `(Reflexive B R') :\n Reflexive (@Logic.eq A ==> R').\n Proof. simpl_relation. Qed.\n\n (** [respectful] is a morphism for relation equivalence. *)\n \n Global Instance respectful_morphism :\n Proper (relation_equivalence ++> relation_equivalence ++> relation_equivalence) \n (@respectful A B).\n Proof.\n reduce.\n unfold respectful, relation_equivalence, predicate_equivalence in * ; simpl in *.\n split ; intros.\n \n rewrite <- H0.\n apply H1.\n rewrite H.\n assumption.\n \n rewrite H0.\n apply H1.\n rewrite <- H.\n assumption.\n Qed.\n\n (** [R] is Reflexive, hence we can build the needed proof. *)\n\n Lemma Reflexive_partial_app_morphism `(Proper (A -> B) (R ==> R') m, ProperProxy A R x) :\n Proper R' (m x).\n Proof. simpl_relation. Qed.\n \n Lemma flip_respectful (R : relation A) (R' : relation B) :\n relation_equivalence (flip (R ==> R')) (flip R ==> flip R').\n Proof.\n intros.\n unfold flip, respectful.\n split ; intros ; intuition.\n Qed.\n\n \n (** Treating flip: can't make them direct instances as we\n need at least a [flip] present in the goal. *)\n \n Lemma flip1 `(subrelation A R' R) : subrelation (flip (flip R')) R.\n Proof. firstorder. Qed.\n \n Lemma flip2 `(subrelation A R R') : subrelation R (flip (flip R')).\n Proof. firstorder. Qed.\n \n (** That's if and only if *)\n \n Lemma eq_subrelation `(Reflexive A R) : subrelation (@eq A) R.\n Proof. simpl_relation. Qed.\n\n (** Once we have normalized, we will apply this instance to simplify the problem. *)\n \n Definition proper_flip_proper `(mor : Proper A R m) : Proper (flip R) m := mor.\n \n (** Every reflexive relation gives rise to a morphism, \n only for immediately solving goals without variables. *)\n \n Lemma reflexive_proper `{Reflexive A R} (x : A) : Proper R x.\n Proof. firstorder. Qed.\n \n Lemma proper_eq (x : A) : Proper (@eq A) x.\n Proof. intros. apply reflexive_proper. Qed.\n \nEnd GenericInstances.\n\nClass PartialApplication.\n\nCoInductive normalization_done : Prop := did_normalization.\n\nClass Params {A : Type} (of : A) (arity : nat).\n\nLtac partial_application_tactic :=\n let rec do_partial_apps H m cont := \n match m with\n | ?m' ?x => class_apply @Reflexive_partial_app_morphism ; \n [(do_partial_apps H m' ltac:(idtac))|clear H]\n | _ => cont\n end\n in\n let rec do_partial H ar m := \n lazymatch ar with\n | 0%nat => do_partial_apps H m ltac:(fail 1)\n | S ?n' =>\n match m with\n ?m' ?x => do_partial H n' m'\n end\n end\n in\n let params m sk fk :=\n (let m' := fresh in head_of_constr m' m ;\n let n := fresh in evar (n:nat) ;\n let v := eval compute in n in clear n ;\n let H := fresh in\n assert(H:Params m' v) by (subst m'; once typeclasses eauto) ;\n let v' := eval compute in v in subst m';\n (sk H v' || fail 1))\n || fk\n in\n let on_morphism m cont :=\n params m ltac:(fun H n => do_partial H n m)\n ltac:(cont)\n in\n match goal with\n | [ _ : normalization_done |- _ ] => fail 1\n | [ _ : @Params _ _ _ |- _ ] => fail 1\n | [ |- @Proper ?T _ (?m ?x) ] =>\n match goal with\n | [ H : PartialApplication |- _ ] =>\n class_apply @Reflexive_partial_app_morphism; [|clear H]\n | _ => on_morphism (m x)\n ltac:(class_apply @Reflexive_partial_app_morphism)\n end\n end.\n\n(** Bootstrap !!! *)\n\nInstance proper_proper : Proper (relation_equivalence ==> eq ==> iff) (@Proper A).\nProof.\n simpl_relation.\n reduce in H.\n split ; red ; intros.\n setoid_rewrite <- H.\n apply H0.\n setoid_rewrite H.\n apply H0.\nQed.\n\nLtac proper_reflexive :=\n match goal with\n | [ _ : normalization_done |- _ ] => fail 1\n | _ => class_apply proper_eq || class_apply @reflexive_proper\n end.\n\n\nHint Extern 1 (subrelation (flip _) _) => class_apply @flip1 : typeclass_instances.\nHint Extern 1 (subrelation _ (flip _)) => class_apply @flip2 : typeclass_instances.\n\nHint Extern 1 (Proper _ (complement _)) => apply @complement_proper \n : typeclass_instances.\nHint Extern 1 (Proper _ (flip _)) => apply @flip_proper \n : typeclass_instances.\nHint Extern 2 (@Proper _ (flip _) _) => class_apply @proper_flip_proper \n : typeclass_instances.\nHint Extern 4 (@Proper _ _ _) => partial_application_tactic \n : typeclass_instances.\nHint Extern 7 (@Proper _ _ _) => proper_reflexive \n : typeclass_instances.\n\n(** Special-purpose class to do normalization of signatures w.r.t. flip. *)\n\nSection Normalize.\n Context (A : Type).\n\n Class Normalizes (m : relation A) (m' : relation A) : Prop :=\n normalizes : relation_equivalence m m'.\n \n (** Current strategy: add [flip] everywhere and reduce using [subrelation]\n afterwards. *)\n\n Lemma proper_normalizes_proper `(Normalizes R0 R1, Proper A R1 m) : Proper R0 m.\n Proof.\n red in H, H0.\n rewrite H.\n assumption.\n Qed.\n\n Lemma flip_atom R : Normalizes R (flip (flip R)).\n Proof.\n firstorder.\n Qed.\n\nEnd Normalize.\n\nLemma flip_arrow {A : Type} {B : Type}\n `(NA : Normalizes A R (flip R'''), NB : Normalizes B R' (flip R'')) :\n Normalizes (A -> B) (R ==> R') (flip (R''' ==> R'')%signature).\nProof. \n unfold Normalizes in *. intros.\n unfold relation_equivalence in *. \n unfold predicate_equivalence in *. simpl in *.\n unfold respectful. unfold flip in *. firstorder.\n apply NB. apply H. apply NA. apply H0.\n apply NB. apply H. apply NA. apply H0.\nQed.\n\nLtac normalizes :=\n match goal with\n | [ |- Normalizes _ (respectful _ _) _ ] => class_apply @flip_arrow\n | _ => class_apply @flip_atom\n end.\n\nLtac proper_normalization :=\n match goal with\n | [ _ : normalization_done |- _ ] => fail 1\n | [ _ : apply_subrelation |- @Proper _ ?R _ ] => \n let H := fresh \"H\" in\n set(H:=did_normalization) ; class_apply @proper_normalizes_proper\n end.\n\nHint Extern 1 (Normalizes _ _ _) => normalizes : typeclass_instances.\nHint Extern 6 (@Proper _ _ _) => proper_normalization \n : typeclass_instances.\n\n(** When the relation on the domain is symmetric, we can\n flip the relation on the codomain. Same for binary functions. *)\n\nLemma proper_sym_flip :\n forall `(Symmetric A R1)`(Proper (A->B) (R1==>R2) f),\n Proper (R1==>flip R2) f.\nProof.\nintros A R1 Sym B R2 f Hf.\nintros x x' Hxx'. apply Hf, Sym, Hxx'.\nQed.\n\nLemma proper_sym_flip_2 :\n forall `(Symmetric A R1)`(Symmetric B R2)`(Proper (A->B->C) (R1==>R2==>R3) f),\n Proper (R1==>R2==>flip R3) f.\nProof.\nintros A R1 Sym1 B R2 Sym2 C R3 f Hf.\nintros x x' Hxx' y y' Hyy'. apply Hf; auto.\nQed.\n\n(** When the relation on the domain is symmetric, a predicate is\n compatible with [iff] as soon as it is compatible with [impl].\n Same with a binary relation. *)\n\nLemma proper_sym_impl_iff : forall `(Symmetric A R)`(Proper _ (R==>impl) f),\n Proper (R==>iff) f.\nProof.\nintros A R Sym f Hf x x' Hxx'. repeat red in Hf. split; eauto.\nQed.\n\nLemma proper_sym_impl_iff_2 :\n forall `(Symmetric A R)`(Symmetric B R')`(Proper _ (R==>R'==>impl) f),\n Proper (R==>R'==>iff) f.\nProof.\nintros A R Sym B R' Sym' f Hf x x' Hxx' y y' Hyy'.\nrepeat red in Hf. split; eauto.\nQed.\n\n(** A [PartialOrder] is compatible with its underlying equivalence. *)\n\nInstance PartialOrder_proper `(PartialOrder A eqA R) :\n Proper (eqA==>eqA==>iff) R.\nProof.\nintros.\napply proper_sym_impl_iff_2; auto with *.\nintros x x' Hx y y' Hy Hr.\ntransitivity x.\ngeneralize (partial_order_equivalence x x'); compute; intuition.\ntransitivity y; auto.\ngeneralize (partial_order_equivalence y y'); compute; intuition.\nQed.\n\n(** From a [PartialOrder] to the corresponding [StrictOrder]:\n [lt = le /\\ ~eq].\n If the order is total, we could also say [gt = ~le]. *)\n\nLemma PartialOrder_StrictOrder `(PartialOrder A eqA R) :\n StrictOrder (relation_conjunction R (complement eqA)).\nProof.\nsplit; compute.\nintros x (_,Hx). apply Hx, Equivalence_Reflexive.\nintros x y z (Hxy,Hxy') (Hyz,Hyz'). split.\napply PreOrder_Transitive with y; assumption.\nintro Hxz.\napply Hxy'.\napply partial_order_antisym; auto.\nrewrite Hxz; auto.\nQed.\n\n\n(** From a [StrictOrder] to the corresponding [PartialOrder]:\n [le = lt \\/ eq].\n If the order is total, we could also say [ge = ~lt]. *)\n\nLemma StrictOrder_PreOrder\n `(Equivalence A eqA, StrictOrder A R, Proper _ (eqA==>eqA==>iff) R) :\n PreOrder (relation_disjunction R eqA).\nProof.\nsplit.\nintros x. right. reflexivity.\nintros x y z [Hxy|Hxy] [Hyz|Hyz].\nleft. transitivity y; auto.\nleft. rewrite <- Hyz; auto.\nleft. rewrite Hxy; auto.\nright. transitivity y; auto.\nQed.\n\nHint Extern 4 (PreOrder (relation_disjunction _ _)) => \n class_apply StrictOrder_PreOrder : typeclass_instances.\n\nLemma StrictOrder_PartialOrder\n `(Equivalence A eqA, StrictOrder A R, Proper _ (eqA==>eqA==>iff) R) :\n PartialOrder eqA (relation_disjunction R eqA).\nProof.\nintros. intros x y. compute. intuition.\nelim (StrictOrder_Irreflexive x).\ntransitivity y; auto.\nQed.\n\nHint Extern 4 (StrictOrder (relation_conjunction _ _)) => \n class_apply PartialOrder_StrictOrder : typeclass_instances.\n\nHint Extern 4 (PartialOrder _ (relation_disjunction _ _)) => \n class_apply StrictOrder_PartialOrder : typeclass_instances.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Classes/Morphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1052105303904218, "lm_q1q2_score": 0.05219429492205091}} {"text": "(**\nThis file is part of the Coquelicot formalization of real\nanalysis in Coq: http://coquelicot.saclay.inria.fr/\n\nCopyright (C) 2011-2015 Sylvie Boldo\n#
#\nCopyright (C) 2011-2015 Catherine Lelay\n#
#\nCopyright (C) 2011-2015 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\nFrom Coq Require Import Reals Lia List ssreflect ssrbool.\nFrom mathcomp Require Import seq eqtype.\n\nRequire Import Rcomplements.\n\n(** This file describes iterators on lists. This is mainly used for\nRiemannn sums. *)\n\nSection Iter.\n\nContext {I T : Type}.\n\nContext (op : T -> T -> T).\nContext (x0 : T).\nContext (neutral_l : forall x, op x0 x = x).\nContext (neutral_r : forall x, op x x0 = x).\nContext (assoc : forall x y z, op x (op y z) = op (op x y) z).\n\nFixpoint iter (l : list I) (f : I -> T) :=\n match l with\n | nil => x0\n | cons h l' => op (f h) (iter l' f)\n end.\n\nDefinition iter' (l : list I) (f : I -> T) :=\n fold_right (fun i acc => op (f i) acc) x0 l.\n\nLemma iter_iter' l f :\n iter l f = iter' l f.\nProof.\n elim: l => [ | h l IH] //=.\n by rewrite IH.\nQed.\n\nLemma iter_cat l1 l2 f :\n iter (l1 ++ l2) f = op (iter l1 f) (iter l2 f).\nProof.\n elim: l1 => [ | h1 l1 IH] /=.\n by rewrite neutral_l.\n by rewrite IH assoc.\nQed.\nLemma iter_ext l f1 f2 :\n (forall x, In x l -> f1 x = f2 x) ->\n iter l f1 = iter l f2.\nProof.\n elim: l => [ | h l IH] /= Heq.\n by [].\n rewrite IH.\n rewrite Heq //.\n by left.\n intros x Hx.\n apply Heq.\n by right.\nQed.\n\nLemma iter_comp (l : list I) f (g : I -> I) :\n iter l (fun x => f (g x)) = iter (map g l) f.\nProof.\n elim: l => [ | s l IH] //=.\n by rewrite IH.\nQed.\n\nEnd Iter.\n\nLemma iter_const {I} (l : list I) (a : R) :\n iter Rplus 0 l (fun _ => a) = INR (length l) * a.\nProof.\n elim: l => /= [ | h l ->].\n by rewrite /= Rmult_0_l.\n case: (length l) => [ | n] ; simpl ; ring.\nQed.\n\nLemma In_mem {T : eqType} (x : T) l :\n reflect (In x l) (in_mem x (mem l)).\nProof.\napply iffP with (P := x \\in l).\nby case: (x \\in l) => // ; constructor.\n\nelim: l => [ | h l IH] //= E.\nrewrite in_cons in E.\ncase/orP: E => E.\nnow left ; apply sym_eq ; apply / eqP.\nright ; by apply IH.\n\nelim: l => [ | h l IH] E //=.\nsimpl in E.\ncase : E => E.\nrewrite E ; apply mem_head.\nrewrite in_cons.\nrewrite IH.\napply orbT.\nby [].\nQed.\n\nLemma In_iota (n m k : nat) :\n (n <= m <= k)%nat <-> In m (iota n (S k - n)).\nProof.\n generalize (mem_iota n (S k - n) m).\n case: In_mem => // H H0.\n apply sym_eq in H0.\n case/andP: H0 => H0 H1.\n apply Rcomplements.SSR_leq in H0.\n apply SSR_leq in H1.\n change ssrnat.addn with Peano.plus in H1.\n split => // _.\n split => //.\n case: (le_dec n (S m)).\n intro ; lia.\n intro H2.\n rewrite not_le_minus_0 in H1 => //.\n contradict H2.\n by eapply le_trans, le_n_Sn.\n contradict H2.\n by eapply le_trans, le_n_Sn.\n change ssrnat.addn with Peano.plus in H0.\n split => // H1.\n case: H1 => /= H1 H2.\n apply sym_eq in H0.\n apply Bool.andb_false_iff in H0.\n case: H0 => //.\n move/SSR_leq: H1 ; by case: ssrnat.leq.\n rewrite <- le_plus_minus by lia.\n move/le_n_S/SSR_leq: H2 ; by case: ssrnat.leq.\nQed.\n\nSection Iter_nat.\n\nContext {T : Type}.\n\nContext (op : T -> T -> T).\nContext (x0 : T).\nContext (neutral_l : forall x, op x0 x = x).\nContext (neutral_r : forall x, op x x0 = x).\nContext (assoc : forall x y z, op x (op y z) = op (op x y) z).\n\nDefinition iter_nat (a : nat -> T) n m :=\n iter op x0 (iota n (S m - n)) a.\n\nLemma iter_nat_ext_loc (a b : nat -> T) (n m : nat) :\n (forall k, (n <= k <= m)%nat -> a k = b k) ->\n iter_nat a n m = iter_nat b n m.\nProof.\n intros Heq.\n apply iter_ext.\n intros k Hk.\n apply Heq.\n by apply In_iota.\nQed.\n\nLemma iter_nat_point a n :\n iter_nat a n n = a n.\nProof.\n unfold iter_nat.\n rewrite -minus_Sn_m // minus_diag /=.\n by apply neutral_r.\nQed.\n\nLemma iter_nat_Chasles a n m k :\n (n <= S m)%nat -> (m <= k)%nat ->\n iter_nat a n k = op (iter_nat a n m) (iter_nat a (S m) k).\nProof.\n intros Hnm Hmk.\n rewrite -iter_cat //.\n pattern (S m) at 2 ;\n replace (S m) with (ssrnat.addn n (S m - n)).\n rewrite -(iota_add n (S m - n)).\n apply (f_equal (fun k => iter _ _ (iota n k) _)).\n change ssrnat.addn with Peano.plus.\n lia.\n change ssrnat.addn with Peano.plus.\n lia.\nQed.\n\nLemma iter_nat_S a n m :\n iter_nat (fun n => a (S n)) n m = iter_nat a (S n) (S m).\nProof.\n rewrite /iter_nat iter_comp.\n apply (f_equal (fun l => iter _ _ l _)).\n rewrite MyNat.sub_succ.\n elim: (S m - n)%nat {1 3}(n) => {n m} [ | n IH] m //=.\n by rewrite IH.\nQed.\n\nEnd Iter_nat.\n", "meta": {"author": "jtassarotti", "repo": "coquelicot-ext", "sha": "1c11715037fdd4e15de6491bfdb9f923209ddb63", "save_path": "github-repos/coq/jtassarotti-coquelicot-ext", "path": "github-repos/coq/jtassarotti-coquelicot-ext/coquelicot-ext-1c11715037fdd4e15de6491bfdb9f923209ddb63/theories/Iter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10970577824417872, "lm_q1q2_score": 0.05185610866580864}} {"text": "(**\nThis file is part of the Coquelicot formalization of real\nanalysis in Coq: http://coquelicot.saclay.inria.fr/\n\nCopyright (C) 2011-2015 Sylvie Boldo\n#
#\nCopyright (C) 2011-2015 Catherine Lelay\n#
#\nCopyright (C) 2011-2015 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\nRequire Import Reals RList Psatz.\nRequire Import mathcomp.ssreflect.ssreflect mathcomp.ssreflect.seq mathcomp.ssreflect.ssrbool.\nRequire Import Rcomplements Rbar Lub.\nRequire Import Hierarchy.\n\n(** This file describes many properties about sequences of real\nnumbers. Several formalizations are provided. They are mainly used for\ndefining pointed subvivision in order to define Riemann sums. *)\n\n\nOpen Scope R_scope.\n\n(** * Complements abouts lists *)\n(** seq R <-> Rlist *)\nFixpoint seq2Rlist (s : seq R) :=\n match s with\n | [::] => RList.nil\n | h::t => RList.cons h (seq2Rlist t)\n end.\nFixpoint Rlist2seq (s : Rlist) : seq R :=\n match s with\n | RList.nil => [::]\n | RList.cons h t => h::(Rlist2seq t)\n end.\n\nLemma seq2Rlist_bij (s : Rlist) :\n seq2Rlist (Rlist2seq s) = s.\nProof.\n by elim: s => //= h s ->.\nQed.\nLemma Rlist2seq_bij (s : seq R) :\n Rlist2seq (seq2Rlist s) = s.\nProof.\n by elim: s => //= h s ->.\nQed.\n\nLemma size_compat (s : seq R) :\n Rlength (seq2Rlist s) = size s.\nProof.\n elim: s => // t s IHs /= ; by rewrite IHs.\nQed.\n\nLemma nth_compat (s : seq R) (n : nat) :\n pos_Rl (seq2Rlist s) n = nth 0 s n.\nProof.\n elim: s n => [n|t s IHs n] /= ;\n case: n => //=.\nQed.\n\n(** Various properties *)\n\nLemma rev_rev {T} (l : seq T) : rev (rev l) = l.\nProof.\n elim: l => /= [ | h l IH].\n by [].\n by rewrite rev_cons rev_rcons IH.\nQed.\nLemma head_rev {T} (x0 : T) (l : seq T) :\n head x0 (rev l) = last x0 l.\nProof.\n elim: l x0 => /= [ | x1 l IH] x0.\n by [].\n by rewrite rev_cons head_rcons.\nQed.\nLemma last_rev {T} (x0 : T) (l : seq T) :\n last x0 (rev l) = head x0 l.\nProof.\n by rewrite -head_rev rev_rev.\nQed.\n\nLemma last_unzip1 {S T} x0 y0 (s : seq (S * T)) :\n last x0 (unzip1 s) = fst (last (x0,y0) s).\nProof.\n case: s => [ | h s] //= .\n elim: s h => [ | h0 s IH] h //=.\nQed.\n\n(** sorted *)\n\nFixpoint sorted {T : Type} (Ord : T -> T -> Prop) (s : seq T) :=\n match s with\n | [::] | [:: _] => True\n | h0 :: (h1 :: t1) as t0 => Ord h0 h1 /\\ sorted Ord t0\n end.\nLemma sorted_nth {T : Type} (Ord : T -> T -> Prop) (s : seq T) :\n sorted Ord s <-> (forall i : nat,\n (i < Peano.pred (size s))%nat -> forall x0 : T, Ord (nth x0 s i) (nth x0 s (S i))).\nProof.\n case: s.\n split => // _ i Hi ; contradict Hi ; apply lt_n_O.\n move => t s ; elim: s t => [ t | t s IHs t0] ; split => // H.\n move => i Hi ; contradict Hi ; apply lt_n_O.\n case => [| i] Hi x0 ; simpl in Hi.\n apply H.\n case: (IHs t) => {IHs} IHs _ ;\n apply (IHs (proj2 H) i (lt_S_n _ _ Hi) x0).\n split.\n apply (H O (lt_0_Sn _) t).\n case: (IHs t) => {IHs} _ IHs.\n apply: IHs => i Hi x0 ; apply: (H (S i)) ; simpl ; apply lt_n_S, Hi.\nQed.\nLemma sorted_cat {T : Type} (Ord : T -> T -> Prop) (s1 s2 : seq T) x0 :\n sorted Ord s1 -> sorted Ord s2 -> Ord (last x0 s1) (head x0 s2)\n -> sorted Ord (s1 ++ s2).\nProof.\n move/sorted_nth => H1.\n move/sorted_nth => H2 H0.\n apply sorted_nth => i Hi => x1.\n rewrite ?nth_cat.\n rewrite ?SSR_minus.\n case: (le_dec (S i) (size s1)) => Hi0.\n move: (proj2 (SSR_leq _ _) Hi0) ;\n case: (ssrnat.leq (S i) (size s1)) => // _.\n case: (le_dec (S (S i)) (size s1)) => Hi1.\n move: (proj2 (SSR_leq _ _) Hi1) ;\n case: (ssrnat.leq (S (S i)) (size s1)) => // _.\n apply H1 ; intuition.\n have : ~ (ssrnat.leq (S (S i)) (size s1)).\n contradict Hi1 ; by apply SSR_leq.\n case: (ssrnat.leq (S (S i)) (size s1)) => // _.\n suff Hi' : i = Peano.pred (size s1).\n rewrite Hi' nth_last.\n replace (S (Peano.pred (size s1)) - size s1)%nat with O.\n rewrite nth0.\n apply not_le in Hi1.\n case: (s1) H0 Hi Hi' Hi0 Hi1 => [ | x2 s1'] //= H0 Hi Hi' Hi0 Hi1.\n by apply le_Sn_O in Hi0.\n case: (s2) H0 Hi0 Hi => [ | x3 s2'] //= H0 Hi0 Hi.\n rewrite cats0 /= in Hi.\n rewrite Hi' in Hi.\n by apply lt_irrefl in Hi.\n case: (s1) Hi0 => //= [ | x2 s0] Hi0.\n by apply le_Sn_O in Hi0.\n by rewrite minus_diag.\n apply sym_eq, le_antisym.\n apply MyNat.le_pred_le_succ.\n apply not_le in Hi1.\n by apply lt_n_Sm_le.\n replace i with (Peano.pred (S i)) by auto.\n by apply le_pred.\n have : ~ (ssrnat.leq (S i) (size s1)).\n contradict Hi0 ; by apply SSR_leq.\n case: (ssrnat.leq (S i) (size s1)) => // _.\n have : ~ssrnat.leq (S (S i)) (size s1).\n contradict Hi0.\n apply SSR_leq in Hi0.\n intuition.\n case: (ssrnat.leq (S (S i)) (size s1)) => // _.\n replace (S i - size s1)%nat with (S (i - size s1)).\n apply H2.\n rewrite size_cat in Hi.\n apply not_le in Hi0.\n elim: (size s1) i Hi Hi0 => [ | n IH] /= i Hi Hi0.\n rewrite -minus_n_O.\n unfold ssrnat.addn, ssrnat.addn_rec in Hi.\n by rewrite plus_0_l in Hi.\n case: i Hi Hi0 => [ | i] /= Hi Hi0.\n by apply lt_S_n, lt_n_O in Hi0.\n apply IH ; by intuition.\n apply not_le in Hi0.\n rewrite minus_Sn_m ; by intuition.\nQed.\n\nLemma sorted_head (s : seq R) i :\n sorted Rle s -> (i < size s)%nat -> forall x0, head x0 s <= nth x0 s i.\nProof.\n case: s => [| h s].\n move => _ Hi ; by apply lt_n_O in Hi.\n elim: s h i => [| h0 s IH] h i Hs Hi x0.\n apply lt_n_Sm_le, le_n_O_eq in Hi ; rewrite -Hi ; apply Rle_refl.\n case: i Hi => [| i] Hi.\n apply Rle_refl.\n apply Rle_trans with (r2 := head x0 (h0::s)).\n apply Hs.\n apply IH.\n apply Hs.\n apply lt_S_n, Hi.\nQed.\n\nLemma sorted_incr (s : seq R) i j : sorted Rle s -> (i <= j)%nat -> (j < size s)%nat\n -> forall x0, nth x0 s i <= nth x0 s j.\nProof.\n elim: i j s => [| i IH] j s Hs Hij Hj x0.\n rewrite nth0 ; by apply sorted_head.\n case: j Hij Hj => [| j] Hij Hj.\n by apply le_Sn_O in Hij.\n case: s Hs Hj => [| h s] Hs Hj.\n by apply lt_n_O in Hj.\n apply (IH j s) with (x0 := x0) => //.\n case: (s) Hs => {s Hj} [| h0 s] Hs ; apply Hs.\n apply le_S_n, Hij.\n apply le_S_n, Hj.\nQed.\n\nLemma sorted_last (s : seq R) i :\n sorted Rle s -> (i < size s)%nat -> forall x0, nth x0 s i <= last x0 s.\nProof.\n move => Hs Hi x0 ; rewrite -nth_last.\n case: s Hi Hs => [| h s] Hi Hs //.\n by apply lt_n_O in Hi.\n apply sorted_incr => //.\n intuition.\nQed.\n\nLemma sorted_dec (s : seq R) x0 (x : R) :\n sorted Rle s -> head x0 s <= x <= last x0 s ->\n {i : nat | nth x0 s i <= x < nth x0 s (S i) /\\ (S (S i) < size s)%nat}\n + {nth x0 s (size s - 2)%nat <= x <= nth x0 s (size s - 1)%nat}.\nProof.\n case: s => [/= _ Hx| h s] ; simpl minus ; rewrite -?minus_n_O.\n by right.\n case: s => [/= _ Hx| h0 s] ; simpl minus ; rewrite -?minus_n_O.\n by right.\n elim: s h h0 => [/= | h1 s IH] h h0 Hs Hx.\n by right.\n case: (Rlt_le_dec x h0) => Hx'.\n left ; exists O => /= ; intuition.\n case: (IH h0 h1) => [ | |[i Hi]|Hi].\n apply Hs.\n split ; [apply Hx'|apply Hx].\n left ; exists (S i) => /= ; intuition.\n right => /= ; simpl in Hi.\n by rewrite -minus_n_O in Hi.\nQed.\n\nLemma sorted_compat (s : seq R) :\n sorted Rle s <-> ordered_Rlist (seq2Rlist s).\nProof.\n case: s => [| h s].\n(* s = [::] *)\n split => // H i /= Hi ; contradict Hi ; apply lt_n_O.\n elim: s h => [h | h s IHs h'].\n(* s = [::_] *)\n split => // H i /= Hi ; contradict Hi ; apply lt_n_O.\n(* s = _::(_::_) *)\n split => H.\n case => [ /= | i] ; rewrite size_compat => Hi ; simpl in Hi.\n apply H.\n apply (proj1 (IHs h) (proj2 H) i) ; rewrite size_compat /= ; apply lt_S_n => //.\n split.\n apply (H O) ; rewrite size_compat /= ; apply lt_O_Sn.\n apply IHs => i ; rewrite size_compat /= => Hi ; apply (H (S i)) ;\n rewrite size_compat /= ; apply lt_n_S, Hi.\nQed.\n\n(** seq_step *)\n\nDefinition seq_step (s : seq R) :=\n foldr Rmax 0 (pairmap (fun x y => Rabs (Rminus y x)) (head 0 s) (behead s)).\n\nLemma seq_step_ge_0 x : (0 <= seq_step x).\nProof.\n clear ; unfold seq_step ; case: x => [ | x0 x] //= .\n by apply Rle_refl.\n elim: x x0 => [ | x1 x IH] //= x0.\n by apply Rle_refl.\n apply Rmax_case.\n by apply Rabs_pos.\n by [].\nQed.\nLemma seq_step_cat (x y : seq R) :\n (0 < size x)%nat -> (0 < size y)%nat ->\n last 0 x = head 0 y ->\n seq_step (cat x (behead y)) = Rmax (seq_step x) (seq_step y).\nProof.\n case: x => /= [ H | x0 x _].\n by apply lt_irrefl in H.\n case: y => /= [ H | y0 y _].\n by apply lt_irrefl in H.\n move => <-.\n elim: x y x0 {y0} => /= [ | x1 x IH] y x0.\n rewrite {2}/seq_step /=.\n rewrite /Rmax ; case: Rle_dec (seq_step_ge_0 (x0 :: y)) => // _ _.\n unfold seq_step ; simpl.\n rewrite -Rmax_assoc.\n apply f_equal.\n by apply IH.\nQed.\n\nLemma seq_step_rev (l : seq R) : seq_step (rev l) = seq_step l.\nProof.\n rewrite /seq_step.\n rewrite head_rev behead_rev /=.\n case: l => [ | x0 l] //=.\n case: l => [ | x1 l] //=.\n rewrite rev_cons.\n case: l => [ | x2 l] //=.\n by rewrite -Rabs_Ropp Ropp_minus_distr'.\n rewrite rev_cons pairmap_rcons foldr_rcons.\n rewrite -Rabs_Ropp Ropp_minus_distr'.\n generalize (Rabs (x1 - x0)) ; clear.\n elim: l x1 x2 => [ | x2 l IH] x0 x1 r //=.\n rewrite -Rabs_Ropp Ropp_minus_distr' !Rmax_assoc.\n apply f_equal2 => //.\n by apply Rmax_comm.\n rewrite rev_cons pairmap_rcons foldr_rcons.\n rewrite -Rabs_Ropp Ropp_minus_distr' Rmax_assoc IH.\n by rewrite (Rmax_comm _ r) !Rmax_assoc.\nQed.\n\nLemma nth_le_seq_step x0 (l : seq R) (i : nat) : (S i < size l)%nat ->\n Rabs (nth x0 l (S i) - nth x0 l i) <= seq_step l.\nProof.\n elim: i l => [ | i IH] ; case => [ | x1 l] /= Hi.\n by apply lt_n_O in Hi.\n apply lt_S_n in Hi.\n destruct l as [ | x2 l].\n by apply lt_n_O in Hi.\n by apply Rmax_l.\n by apply lt_n_O in Hi.\n apply lt_S_n in Hi.\n move: (IH l Hi).\n destruct l as [ | x2 l] ; simpl.\n by apply lt_n_O in Hi.\n simpl in Hi ; apply lt_S_n in Hi.\n move => {IH} IH.\n eapply Rle_trans.\n by apply IH.\n by apply Rmax_r.\nQed.\n\n(** * Definitions of SF_seq *)\n\nSection SF_seq.\nContext {T : Type}.\n\nRecord SF_seq := mkSF_seq {SF_h : R ; SF_t : seq (R * T)}.\nDefinition SF_lx (s : SF_seq) : seq R := (SF_h s)::(unzip1 (SF_t s)).\nDefinition SF_ly (s : SF_seq) : seq T := unzip2 (SF_t s).\nDefinition SF_make (lx : seq R) (ly : seq T) (Hs : size lx = S (size ly)) : SF_seq :=\n mkSF_seq (head 0 lx) (zip (behead lx) ly).\n\nLemma SF_size_lx_ly (s : SF_seq) : size (SF_lx s) = S (size (SF_ly s)).\nProof.\n case: s => sh st ;\n rewrite /SF_lx /SF_ly /= ;\n elim: st => //= t s -> //.\nQed.\nLemma SF_seq_bij (s : SF_seq) :\n SF_make (SF_lx s) (SF_ly s) (SF_size_lx_ly s) = s.\nProof.\n case: s => sh st ; by rewrite /SF_make (zip_unzip st).\nQed.\nLemma SF_seq_bij_lx (lx : seq R) (ly : seq T)\n (Hs : size lx = S (size ly)) : SF_lx (SF_make lx ly Hs) = lx.\nProof.\n case: lx Hs => // x lx Hs ;\n rewrite /SF_make / SF_lx unzip1_zip //= ;\n apply SSR_leq, le_S_n ; rewrite -Hs => //.\nQed.\nLemma SF_seq_bij_ly (lx : seq R) (ly : seq T)\n (Hs : size lx = S (size ly)) : SF_ly (SF_make lx ly Hs) = ly.\nProof.\n case: lx Hs => // x lx Hs ;\n rewrite /SF_make / SF_ly unzip2_zip //= ;\n apply SSR_leq, le_S_n ; rewrite -Hs => //.\nQed.\n\n(** ** Constructors *)\n\nDefinition SF_nil (x0 : R) : SF_seq := mkSF_seq x0 [::].\nDefinition SF_cons (h : R*T) (s : SF_seq) :=\n mkSF_seq (fst h) ((SF_h s,snd h)::(SF_t s)).\nDefinition SF_rcons (s : SF_seq) (t : R*T) :=\n mkSF_seq (SF_h s) (rcons (SF_t s) t).\n\nLemma SF_cons_dec (P : SF_seq -> Type) :\n (forall x0 : R, P (SF_nil x0)) -> (forall h s, P (SF_cons h s))\n -> (forall s, P s).\nProof.\n move => Hnil Hcons [sh st] ; case: st => [| h sf].\n apply Hnil.\n move: (Hcons (sh,snd h) (mkSF_seq (fst h) sf)) => {Hcons} ;\n rewrite /SF_cons -surjective_pairing //=.\nQed.\nLemma SF_cons_ind (P : SF_seq -> Type) :\n (forall x0 : R, P (SF_nil x0)) -> (forall h s, P s -> P (SF_cons h s))\n -> (forall s, P s).\nProof.\n move => Hnil Hcons [sh st] ; elim: st sh => [sh |h sf IHst sh].\n apply Hnil.\n move: (IHst (fst h)) => {IHst} IHst.\n move: (Hcons (sh,snd h) (mkSF_seq (fst h) sf) IHst) => {Hcons} ;\n rewrite /SF_cons -surjective_pairing //=.\nQed.\n\nLemma SF_rcons_dec (P : SF_seq -> Type) :\n (forall x0 : R, P (SF_nil x0)) -> (forall s t, P (SF_rcons s t))\n -> (forall s, P s).\nProof.\n move => Hnil Hrcons [sh st] ; move: st ; apply rcons_dec => [| st t].\n apply Hnil.\n apply (Hrcons (mkSF_seq sh st) t).\nQed.\nLemma SF_rcons_ind (P : SF_seq -> Type) :\n (forall x0 : R, P (SF_nil x0)) -> (forall s t, P s -> P (SF_rcons s t))\n -> (forall s, P s).\nProof.\n move => Hnil Hrcons [sh st] ; move: st sh ;\n apply (rcons_ind (fun st => forall sh, P {| SF_h := sh; SF_t := st |})) => [sh | st t IHst sh].\n apply Hnil.\n apply (Hrcons (mkSF_seq sh st) t) => //.\nQed.\n\nLemma SF_cons_rcons (h : R*T) (s : SF_seq) (l : R*T) :\n SF_cons h (SF_rcons s l) = SF_rcons (SF_cons h s) l.\nProof.\n case: h => hx hy ;\n case: l => lx ly ;\n case: s => sh st //.\nQed.\n\n(** ** SF_seq and seq *)\n\nLemma SF_lx_nil (x0 : R) :\n SF_lx (SF_nil x0) = [:: x0].\nProof.\n by [].\nQed.\nLemma SF_ly_nil (x0 : R) :\n SF_ly (SF_nil x0) = [::].\nProof.\n by [].\nQed.\n\nLemma SF_lx_cons (h : R*T) (s : SF_seq) :\n SF_lx (SF_cons h s) = (fst h) :: (SF_lx s).\nProof.\n by [].\nQed.\nLemma SF_ly_cons (h : R*T) (s : SF_seq) :\n SF_ly (SF_cons h s) = (snd h) :: (SF_ly s).\nProof.\n by [].\nQed.\nLemma SF_lx_rcons (s : SF_seq) (h : R*T) :\n SF_lx (SF_rcons s h) = rcons (SF_lx s) (fst h).\nProof.\n case: s => sh st ; rewrite /SF_lx /SF_rcons /= ; elim: st sh => // [[x y] st] IHst sh /= ;\n by rewrite (IHst x).\nQed.\nLemma SF_ly_rcons (s : SF_seq) (h : R*T) :\n SF_ly (SF_rcons s h) = rcons (SF_ly s) (snd h).\nProof.\n case: s => sh st ; rewrite /SF_ly /SF_rcons /= ; elim: st sh => // [[x y] st] IHst sh /= ;\n by rewrite (IHst x).\nQed.\n\nLemma SF_lx_surj (s s0 : SF_seq) :\n s = s0 -> SF_lx s = SF_lx s0.\nProof.\n by move => ->.\nQed.\nLemma SF_ly_surj (s s0 : SF_seq) :\n s = s0 -> SF_ly s = SF_ly s0.\nProof.\n by move => ->.\nQed.\nLemma SF_lx_ly_inj (s s0 : SF_seq) :\n SF_lx s = SF_lx s0 -> SF_ly s = SF_ly s0 -> s = s0.\nProof.\n move: s0 ; apply SF_cons_ind with (s := s) => {s} [x | h s IH] s0 ;\n apply SF_cons_dec with (s := s0) => {s0} [x0 | h0 s0] Hx Hy //.\n(* s = SF_nil _ *)\n rewrite !SF_lx_nil in Hx.\n replace x with (head 0 ([::x])) by intuition ;\n by rewrite Hx.\n(* s = SF_cons _ _*)\n rewrite !SF_lx_cons in Hx ; rewrite !SF_ly_cons in Hy.\n replace h with (head (fst h) (fst h :: SF_lx s),head (snd h) (snd h :: SF_ly s)) ;\n [ rewrite Hx Hy (IH s0) //= | move => /= ; by apply injective_projections].\n replace (SF_lx s) with (behead (fst h :: SF_lx s)) by intuition ; by rewrite Hx.\n replace (SF_ly s) with (behead (snd h :: SF_ly s)) by intuition ; by rewrite Hy.\nQed.\n\n(** ** SF_size *)\n\nDefinition SF_size (s : SF_seq) := size (SF_t s).\n\nLemma SF_size_cons (h : R*T) (s : SF_seq) : SF_size (SF_cons h s) = S (SF_size s).\nProof.\n rewrite /SF_cons /SF_size //=.\nQed.\n\nLemma SF_size_rcons (s : SF_seq) (t : R*T) : SF_size (SF_rcons s t) = S (SF_size s).\nProof.\n rewrite /SF_rcons /SF_size size_rcons //=.\nQed.\n\nLemma SF_size_lx (s : SF_seq) : size (SF_lx s) = S (SF_size s).\nProof.\n case: s => sh st ; rewrite /SF_size /= ; elim: st => //= _ st -> //.\nQed.\nLemma SF_size_ly (s : SF_seq) : size (SF_ly s) = SF_size s.\nProof.\n case: s => sh st ; rewrite /SF_size /= ; elim: st => //= _ st -> //.\nQed.\n\n(** ** SF_rev *)\n\nLemma SF_rev_0 (s : SF_seq) :\n size (rev (SF_lx s)) = S (size (rev (SF_ly s))).\nProof.\n by rewrite ?size_rev SF_size_lx SF_size_ly.\nQed.\nDefinition SF_rev (s : SF_seq) : SF_seq :=\n SF_make (rev (SF_lx s)) (rev (SF_ly s)) (SF_rev_0 s).\n\nLemma SF_rev_cons (h : R*T) (s : SF_seq) :\n SF_rev (SF_cons h s) = SF_rcons (SF_rev s) h.\nProof.\n apply SF_lx_ly_inj.\n by rewrite SF_lx_rcons !SF_seq_bij_lx SF_lx_cons rev_cons.\n by rewrite SF_ly_rcons !SF_seq_bij_ly SF_ly_cons rev_cons.\nQed.\nLemma SF_rev_rcons (s : SF_seq) (t : R*T) :\n SF_rev (SF_rcons s t) = SF_cons t (SF_rev s).\nProof.\n apply SF_lx_ly_inj.\n by rewrite SF_lx_cons !SF_seq_bij_lx SF_lx_rcons rev_rcons.\n by rewrite SF_ly_cons !SF_seq_bij_ly SF_ly_rcons rev_rcons.\nQed.\n\nLemma SF_rev_invol (s : SF_seq) :\n SF_rev (SF_rev s) = s.\nProof.\n apply SF_lx_ly_inj.\n by rewrite /SF_rev ?SF_seq_bij_lx revK.\n by rewrite /SF_rev ?SF_seq_bij_ly revK.\nQed.\n\nLemma SF_lx_rev (s : SF_seq) : SF_lx (SF_rev s) = rev (SF_lx s).\nProof.\n by rewrite /SF_rev ?SF_seq_bij_lx.\nQed.\nLemma SF_ly_rev (s : SF_seq) : SF_ly (SF_rev s) = rev (SF_ly s).\nProof.\n by rewrite /SF_rev ?SF_seq_bij_ly.\nQed.\n\nLemma SF_size_rev (s : SF_seq) : SF_size (SF_rev s) = SF_size s.\nProof.\n by rewrite -?SF_size_ly SF_ly_rev size_rev.\nQed.\n\nLemma SF_rev_surj (s s0 : SF_seq) :\n s = s0 -> SF_rev s = SF_rev s0.\nProof.\n by move => ->.\nQed.\nLemma SF_rev_inj (s s0 : SF_seq) :\n SF_rev s = SF_rev s0 -> s = s0.\nProof.\n move => H ; by rewrite -(SF_rev_invol s) -(SF_rev_invol s0) H.\nQed.\n\n(** ** SF_cat *)\n\nDefinition SF_cat (x y : SF_seq) := mkSF_seq (SF_h x) ((SF_t x) ++ (SF_t y)).\nLemma SF_lx_cat (x y : SF_seq) :\n SF_lx (SF_cat x y) = (SF_lx x) ++ (behead (SF_lx y)).\nProof.\n unfold SF_cat, SF_lx ; simpl.\n apply f_equal.\n by elim: (SF_t x) => //= t h ->.\nQed.\nLemma SF_last_cat (x y : SF_seq) :\n last (SF_h x) (SF_lx x) = head (SF_h y) (SF_lx y) ->\n last (SF_h (SF_cat x y)) (SF_lx (SF_cat x y)) = (last (SF_h y) (SF_lx y)).\nProof.\n rewrite SF_lx_cat.\n unfold SF_cat, SF_lx ; simpl => <- /=.\n elim: (SF_t x) (SF_h x) => //= {x} x1 x x0.\nQed.\nLemma SF_cons_cat x0 (x y : SF_seq) :\n SF_cons x0 (SF_cat x y) = SF_cat (SF_cons x0 x) y.\nProof.\n reflexivity.\nQed.\n\n(** ** first and last pair *)\n\nDefinition SF_head (y0 : T) (s : SF_seq) := (SF_h s, head y0 (SF_ly s)).\nDefinition SF_behead (s : SF_seq) :=\n mkSF_seq (head (SF_h s) (unzip1 (SF_t s))) (behead (SF_t s)).\n\nDefinition SF_last y0 (s : SF_seq) : (R*T) :=\n last (SF_h s,y0) (SF_t s).\nDefinition SF_belast (s : SF_seq) : SF_seq :=\n mkSF_seq (SF_h s) (Rcomplements.belast (SF_t s)).\n\nLemma SF_last_lx x0 (s : SF_seq) :\n fst (SF_last x0 s) = last 0 (SF_lx s).\nProof.\n rewrite /SF_last /=.\n apply sym_eq ; by apply last_unzip1.\nQed.\n\n(** ** SF_sorted *)\n\nDefinition SF_sorted (Ord : R -> R -> Prop) (s : SF_seq) :=\n sorted Ord (SF_lx s).\n\nEnd SF_seq.\n\n(** ** SF_map *)\n\nSection SF_map.\n\nContext {T T0 : Type}.\n\nDefinition SF_map (f : T -> T0) (s : SF_seq) : SF_seq :=\n mkSF_seq (SF_h s) (map (fun x => (fst x,f (snd x))) (SF_t s)).\n\nLemma SF_map_cons (f : T -> T0) (h : R*T) (s : SF_seq) :\n SF_map f (SF_cons h s) = SF_cons (fst h, f (snd h)) (SF_map f s).\nProof.\n case: s => sh ; elim => // h st ; rewrite /SF_map => //.\nQed.\n\nLemma SF_map_rcons (f : T -> T0) (s : SF_seq) (h : R*T) :\n SF_map f (SF_rcons s h) = SF_rcons (SF_map f s) (fst h, f (snd h)).\nProof.\n move: h ; apply SF_cons_ind with (s := s) => {s} [x0 | h0 s IH] //= h.\n rewrite SF_map_cons.\n replace (SF_rcons (SF_cons h0 s) h) with\n (SF_cons h0 (SF_rcons s h)) by auto.\n rewrite SF_map_cons.\n rewrite IH.\n auto.\nQed.\n\nLemma SF_map_lx (f : T -> T0) (s : SF_seq) :\n SF_lx (SF_map f s) = SF_lx s.\nProof.\n apply SF_cons_ind with (s := s) => {s} //= h s IH ;\n by rewrite SF_map_cons ?SF_lx_cons IH.\nQed.\n\nLemma SF_map_ly (f : T -> T0) (s : SF_seq) :\n SF_ly (SF_map f s) = map f (SF_ly s).\nProof.\n apply SF_cons_ind with (s := s) => {s} //= h s IH ;\n by rewrite SF_map_cons ?SF_ly_cons IH.\nQed.\n\nLemma SF_map_rev (f : T -> T0) s :\n SF_rev (SF_map f s) = SF_map f (SF_rev s).\nProof.\n apply SF_lx_ly_inj.\n by rewrite SF_lx_rev ?SF_map_lx ?SF_lx_rev.\n by rewrite SF_ly_rev ?SF_map_ly ?SF_ly_rev map_rev.\nQed.\n\nLemma SF_map_sort (f : T -> T0) (s : SF_seq) (Ord : R -> R -> Prop) :\n SF_sorted Ord s -> SF_sorted Ord (SF_map f s).\nProof.\n unfold SF_sorted ;\n apply SF_cons_ind with (s := s) => {s} /= [x0 | [x0 _] /= s IH] Hs.\n by [].\n split.\n by apply Hs.\n now apply IH.\nQed.\n\nLemma SF_size_map (f : T -> T0) s :\n SF_size (SF_map f s) = SF_size s.\nProof.\n by rewrite -!SF_size_ly SF_map_ly size_map.\nQed.\n\nEnd SF_map.\n\n(** * Pointed subvivision *)\n\nDefinition pointed_subdiv (ptd : @SF_seq R) :=\n forall i : nat, (i < SF_size ptd)%nat ->\n nth 0 (SF_lx ptd) i <= nth 0 (SF_ly ptd) i <= nth 0 (SF_lx ptd) (S i).\n\nLemma ptd_cons h s : pointed_subdiv (SF_cons h s) -> pointed_subdiv s.\nProof.\n move => H i Hi ; apply (H (S i)) ; rewrite SF_size_cons ; intuition.\nQed.\nLemma ptd_sort ptd :\n pointed_subdiv ptd -> SF_sorted Rle ptd.\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} [x0 | [x0 y0] ptd] ;\n [ | apply SF_cons_dec with (s := ptd) => {ptd} [ x1 | [x1 y1] ptd] IH] =>\n Hptd ; try split => //=.\n apply Rle_trans with y0 ; apply (Hptd O) ; rewrite SF_size_cons ; apply lt_O_Sn.\n apply Rle_trans with y0 ; apply (Hptd O) ; rewrite SF_size_cons ; apply lt_O_Sn.\n apply IH, (ptd_cons (x0,y0)) => //.\nQed.\nLemma ptd_sort' ptd :\n pointed_subdiv ptd -> sorted Rle (SF_ly ptd).\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} [x0 | [x0 y0] ptd] ;\n [ | apply SF_cons_dec with (s := ptd) => {ptd} [ x1 | [x1 y1] ptd] IH] =>\n Hptd ; try split.\n apply Rle_trans with x1 ; [apply (Hptd O) | apply (Hptd 1%nat)] ;\n rewrite ?SF_size_cons ; repeat apply lt_n_S ; apply lt_O_Sn.\n apply IH, (ptd_cons (x0,y0)) => //.\nQed.\n\nLemma SF_cat_pointed (x y : SF_seq) :\n last (SF_h x) (SF_lx x) = head (SF_h y) (SF_lx y) ->\n pointed_subdiv x -> pointed_subdiv y\n -> pointed_subdiv (SF_cat x y).\nProof.\n intros Hxy Hx Hy.\n move: Hxy Hx.\n apply (SF_cons_ind (fun x => last (SF_h x) (SF_lx x) = head (SF_h y) (SF_lx y) -> pointed_subdiv x -> pointed_subdiv (SF_cat x y)))\n => {x} /= [x0 | x0 x IH] Hxy Hx.\n rewrite Hxy.\n by apply Hy.\n rewrite -SF_cons_cat.\n case => [ | i] Hi.\n apply (Hx O), lt_O_Sn.\n apply IH =>//.\n by apply ptd_cons with x0.\n by apply lt_S_n, Hi.\nQed.\n\n(** * SF_seq for Chasles *)\n\nFixpoint seq_cut_down (s : seq (R*R)) (x : R) : seq (R*R) :=\n match s with\n | [::] => [:: (x,x)]\n | h :: t =>\n match Rle_dec (fst h) x with\n | right _ => [:: (x,Rmin (snd h) x)]\n | left _ => h :: (seq_cut_down t x)\n end\n end.\nFixpoint seq_cut_up (s : seq (R*R)) (x : R) : seq (R*R) :=\n match s with\n | [::] => [:: (x,x)]\n | h :: t =>\n match Rle_dec (fst h) x with\n | right _ => (x,x)::(fst h,Rmax (snd h) x)::t\n | left _ => seq_cut_up t x\n end\n end.\n\nDefinition SF_cut_down (sf : @SF_seq R) (x : R) :=\n let s := seq_cut_down ((SF_h sf,SF_h sf) :: (SF_t sf)) x in\n mkSF_seq (fst (head (SF_h sf,SF_h sf) s)) (behead s).\nDefinition SF_cut_up (sf : @SF_seq R) (x : R) :=\n let s := seq_cut_up ((SF_h sf,SF_h sf) :: (SF_t sf)) x in\n mkSF_seq (fst (head (SF_h sf,SF_h sf) s)) (behead s).\n\nLemma SF_cut_down_step s x eps :\n SF_h s <= x <= last (SF_h s) (SF_lx s) ->\n seq_step (SF_lx s) < eps\n -> seq_step (SF_lx (SF_cut_down s x)) < eps.\nProof.\n unfold SF_cut_down, seq_step ; simpl.\n case => Hh Hl.\n case: Rle_dec => //= _.\n move: Hh Hl ;\n apply SF_cons_ind with (s := s) => {s} [ x1 | [x1 y0] s IH ] /= Hx Hh Hl.\n rewrite (Rle_antisym _ _ Hx Hh) Rminus_eq_0 Rabs_R0.\n rewrite /Rmax ; by case: Rle_dec.\n case: Rle_dec => //= Hx'.\n apply Rmax_case.\n apply Rle_lt_trans with (2 := Hl) ; by apply Rmax_l.\n apply IH ; try assumption.\n apply Rle_lt_trans with (2 := Hl) ; by apply Rmax_r.\n apply Rle_lt_trans with (2 := Hl).\n apply Rmax_case ;\n apply Rle_trans with (2 := Rmax_l _ _).\n rewrite ?Rabs_pos_eq.\n apply Rplus_le_compat_r.\n by apply Rlt_le, Rnot_le_lt.\n rewrite -Rminus_le_0.\n apply Rle_trans with x.\n by [].\n by apply Rlt_le, Rnot_le_lt.\n by rewrite -Rminus_le_0.\n by apply Rabs_pos.\nQed.\nLemma SF_cut_up_step s x eps :\n SF_h s <= x <= last (SF_h s) (SF_lx s) ->\n seq_step (SF_lx s) < eps\n -> seq_step (SF_lx (SF_cut_up s x)) < eps.\nProof.\n unfold SF_cut_down, seq_step ; simpl.\n case => Hh Hl.\n case: Rle_dec => //= _.\n move: {4 5}(SF_h s) Hh Hl ;\n apply SF_cons_ind with (s := s) => {s} [ x1 | [x1 y0] s IH ] /= x0 Hh Hl He.\n by apply He.\n case: Rle_dec => //= Hx.\n apply (IH x0) => //=.\n apply Rle_lt_trans with (2 := He).\n by apply Rmax_r.\n apply Rle_lt_trans with (2 := He).\n apply Rnot_le_lt in Hx.\n apply Rmax_case.\n apply Rle_trans with (2 := Rmax_l _ _).\n rewrite ?Rabs_pos_eq.\n by apply Rplus_le_compat_l, Ropp_le_contravar.\n rewrite -Rminus_le_0 ; by apply Rlt_le, Rle_lt_trans with x.\n rewrite -Rminus_le_0 ; by apply Rlt_le.\n by apply Rmax_r.\nQed.\n\nLemma SF_cut_down_pointed s x :\n SF_h s <= x -> pointed_subdiv s\n -> pointed_subdiv (SF_cut_down s x).\nProof.\n unfold SF_cut_down ; simpl.\n case: Rle_dec => //= _.\n apply SF_cons_ind with (s := s) => {s} [x0 | [x1 y1] s IH] /= Hx0 H.\n move => i /= Hi.\n unfold SF_size in Hi ; simpl in Hi.\n apply lt_n_Sm_le, le_n_O_eq in Hi.\n rewrite -Hi ; simpl ; split.\n by [].\n by apply Rle_refl.\n case: Rle_dec => //= Hx1.\n move: (H O (lt_O_Sn _)) => /= H0.\n apply ptd_cons in H.\n move: (IH Hx1 H) => {IH} IH.\n rewrite /pointed_subdiv => i.\n destruct i => /= Hi.\n by apply H0.\n apply (IH i).\n apply lt_S_n, Hi.\n move => i /= Hi.\n unfold SF_size in Hi ; simpl in Hi.\n apply lt_n_Sm_le, le_n_O_eq in Hi.\n rewrite -Hi ; simpl ; split.\n apply Rmin_case.\n apply (H O).\n by apply lt_O_Sn.\n by [].\n by apply Rmin_r.\nQed.\n\nLemma SF_cut_up_pointed s x :\n SF_h s <= x ->\n pointed_subdiv s\n -> pointed_subdiv (SF_cut_up s x).\nProof.\n unfold SF_cut_up ; simpl.\n case: Rle_dec => //= _.\n move: {2 3}(SF_h s) ;\n apply SF_cons_ind with (s := s) => {s} [ x1 | [x1 y0] s IH] /= x0 Hx0 H i Hi.\n by apply lt_n_O in Hi.\n destruct (Rle_dec (SF_h s) x) as [Hx1|Hx1].\n apply IH => //=.\n move: H ; by apply ptd_cons.\n destruct i ; simpl.\n split.\n by apply Rmax_r.\n apply Rmax_case.\n by apply (H O), lt_O_Sn.\n by apply Rlt_le, Rnot_le_lt.\n apply (H (S i)), Hi.\nQed.\nLemma SF_cut_down_h s x :\n SF_h s <= x -> SF_h (SF_cut_down s x) = SF_h s.\nProof.\n unfold SF_cut_down ; simpl.\n by case: Rle_dec.\nQed.\nLemma SF_cut_up_h s x :\n SF_h (SF_cut_up s x) = x.\nProof.\n unfold SF_cut_up ; simpl.\n case: Rle_dec => //= ; simpl.\n move: {2 3}(SF_h s) ;\n apply SF_cons_ind with (s := s) => {s} [x1 | [x1 y1] s IH ] /= x0 Hx.\n by [].\n case: Rle_dec => //= Hx'.\n by apply IH.\nQed.\nLemma SF_cut_down_l s x :\n last (SF_h (SF_cut_down s x)) (SF_lx (SF_cut_down s x)) = x.\nProof.\n unfold SF_cut_down ; simpl.\n case: Rle_dec => //= ; simpl.\n apply SF_cons_ind with (s := s) => {s} [x1 | [x1 y1] s IH ] /= Hx.\n by [].\n case: Rle_dec => //= Hx'.\nQed.\nLemma SF_cut_up_l s x :\n x <= last (SF_h s) (SF_lx s) ->\n last (SF_h (SF_cut_up s x)) (SF_lx (SF_cut_up s x)) = last (SF_h s) (SF_lx s).\nProof.\n unfold SF_cut_down ; simpl.\n case: Rle_dec => //=.\n move: {3 4}(SF_h s);\n apply SF_cons_ind with (s := s) => {s} [x1 | [x1 y1] s IH ] /= x0 Hx Hx'.\n by apply Rle_antisym.\n case: Rle_dec => //= {Hx} Hx.\n by apply IH.\nQed.\n\nLemma SF_cut_down_cons_0 h ptd x :\n x < fst h -> SF_cut_down (SF_cons h ptd) x = SF_nil x.\nProof.\n intros H0.\n apply Rlt_not_le in H0.\n rewrite /SF_cut_down /=.\n by case: Rle_dec.\nQed.\nLemma SF_cut_up_cons_0 h ptd x :\n x < fst h -> SF_cut_up (SF_cons h ptd) x = SF_cons (x,Rmax (fst h) x) (SF_cons h ptd).\nProof.\n intros H0.\n apply Rlt_not_le in H0.\n rewrite /SF_cut_up /=.\n by case: Rle_dec.\nQed.\nLemma SF_cut_down_cons_1 h ptd x :\n fst h <= x < SF_h ptd -> SF_cut_down (SF_cons h ptd) x = SF_cons (fst h, Rmin (snd h) x) (SF_nil x).\nProof.\n intros [H0 Hx0].\n apply Rlt_not_le in Hx0.\n rewrite /SF_cut_down /=.\n case: Rle_dec => //= _.\n by case: Rle_dec.\nQed.\nLemma SF_cut_up_cons_1 h ptd x :\n fst h <= x < SF_h ptd -> SF_cut_up (SF_cons h ptd) x = SF_cons (x,Rmax (snd h) x) ptd.\nProof.\n intros [H0 Hx0].\n apply Rlt_not_le in Hx0.\n rewrite /SF_cut_up /=.\n case: Rle_dec => //= _.\n by case: Rle_dec.\nQed.\nLemma SF_cut_down_cons_2 h ptd x :\n fst h <= SF_h ptd <= x -> SF_cut_down (SF_cons h ptd) x = SF_cons h (SF_cut_down ptd x).\nProof.\n intros [H0 Hx0].\n rewrite /SF_cut_down /=.\n case: Rle_dec (Rle_trans _ _ _ H0 Hx0) => //= _ _.\n by case: Rle_dec.\nQed.\nLemma SF_cut_up_cons_2 h ptd x :\n fst h <= SF_h ptd <= x -> SF_cut_up (SF_cons h ptd) x = SF_cut_up ptd x.\nProof.\n intros [H0 Hx0].\n rewrite /SF_cut_up /=.\n case: Rle_dec (Rle_trans _ _ _ H0 Hx0) => //= _ _.\n case: Rle_dec => //= _.\n move: {2 3}(SF_h ptd) Hx0 ;\n apply SF_cons_ind with (s := ptd) => {ptd H0} [ x0 | [x0 y0] ptd IH ] //= x0' Hx0.\n case: Rle_dec => //= Hx1.\n by apply IH.\nQed.\n\n(** * Definition of SF_fun *)\n\nSection SF_fun.\n\nContext {T : Type}.\n\nFixpoint SF_fun_aux (h : R*T) (s : seq (R*T)) (y0 : T) (x : R) :=\n match s with\n | [::] => match Rle_dec x (fst h) with\n | left _ => snd h\n | right _ => y0\n end\n | h0 :: s0 => match Rlt_dec x (fst h) with\n | left _ => snd h\n | right _ => SF_fun_aux h0 s0 y0 x\n end\n end.\nDefinition SF_fun (s : SF_seq) (y0 : T) (x : R) :=\n SF_fun_aux (SF_h s,y0) (SF_t s) y0 x.\n\nLemma SF_fun_incr (s : SF_seq) (y0 : T) (x : R) Hs Hx :\n SF_fun s y0 x =\n match (sorted_dec (SF_lx s) 0 x Hs Hx) with\n | inleft H => nth y0 (SF_ly s) (proj1_sig H)\n | inright _ => nth y0 (SF_ly s) (SF_size s -1)%nat\n end.\nProof.\n rewrite /SF_fun /=.\n(* s = SF_nil _ *)\n move: Hs Hx ; apply SF_cons_dec with (s := s) => {s} [/= x1 | h s] Hs /= Hx.\n case: sorted_dec => /= [[i Hi]|Hi] ; rewrite /SF_ly ; case: Rle_dec => //= ;\n case: i Hi => //.\n(* s = SF_cons _ (SF_nil _) *)\n case: Rlt_dec => [Hx' | _].\n contradict Hx' ; apply Rle_not_lt, Hx.\n move: h Hs Hx ; apply SF_cons_ind with (s := s) => {s} [x1 | h0 s IH] h Hs /= Hx.\n case: sorted_dec => [/= [i [Hi' Hi]] /= |Hi].\n by apply lt_S_n, lt_S_n, lt_n_O in Hi.\n case: Hx => Hx Hx' ; apply Rle_not_lt in Hx ; case: Rle_dec => //.\n(* s = SF_cons _ (SF_cons _ _) *)\n case: Rlt_dec => Hx'.\n case: sorted_dec => /= [[i Hi]|Hi]/=.\n case: i Hi => //= i Hi ; contradict Hx' ;\n apply Rle_not_lt, Rle_trans with (2 := proj1 (proj1 Hi)).\n simpl in Hs ; elim: (unzip1 (SF_t s)) (fst h0) (SF_h s) (i) (proj2 Hs) (proj2 Hi)\n => {s IH Hs Hx Hi h h0} [| h1 s IH] h h0 n Hs Hn.\n repeat apply lt_S_n in Hn ; by apply lt_n_O in Hn.\n case: n Hn => [| n] Hn.\n apply Rle_refl.\n apply Rle_trans with (1 := proj1 Hs) => //= ; intuition.\n contradict Hx' ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hi).\n simpl in Hs ; elim: (unzip1 (SF_t s)) (fst h0) (SF_h s) (proj2 Hs)\n => {s IH Hs Hx Hi h h0} [| h1 s IH] h h0 Hs.\n apply Rle_refl.\n apply Rle_trans with (1 := proj1 Hs) => //= ; intuition.\n have : fst h0 <= x <= last (SF_h s) (unzip1 (SF_t s)) => [ | {Hx'} Hx'].\n split ; [by apply Rnot_lt_le | by apply Hx].\n rewrite (IH h0 (proj2 Hs) Hx') => {IH} ;\n case: sorted_dec => [[i [Hxi Hi]]|Hi] ; case: sorted_dec => [[j [Hxj Hj]]|Hj] ;\n rewrite -?minus_n_O //=.\n(* i,j < size s - 2 *)\n move : h h0 i j Hs {Hx Hx'} Hxi Hi Hxj Hj ; apply SF_cons_ind with (s := s)\n => {s} [x1 | h1 s IH] h h0 i j Hs //= Hxi Hi Hxj Hj.\n by apply lt_S_n, lt_S_n, lt_n_O in Hi.\n case: j Hxj Hj => [/= | j] Hxj Hj.\n case: Hxj => _ Hxj ; contradict Hxj ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hxi).\n elim: (i) Hi => {i Hxi IH} //= [| i IH] Hi.\n apply Rle_refl.\n apply Rle_trans with (1 := IH (lt_trans _ _ _ (lt_n_Sn _) Hi)), (sorted_nth Rle) ;\n [apply Hs | simpl ; intuition].\n case: i Hxi Hi => [/= | i] Hxi Hi.\n case: j Hxj Hj => [//= | j] Hxj Hj.\n case: Hxi => _ Hxi ; contradict Hxi ;\n apply Rle_not_lt, Rle_trans with (2 := proj1 Hxj) ;\n elim: (j) Hj => {j Hxj IH} //= [| j IH] Hj.\n apply Rle_refl.\n apply Rle_trans with (1 := IH (lt_trans _ _ _ (lt_n_Sn _) Hj)), (sorted_nth Rle) ;\n [apply Hs | simpl ; intuition].\n apply (IH h0 h1 i j) => //.\n apply Hs.\n apply lt_S_n, Hi.\n apply lt_S_n, Hj.\n(* i < j = size s - 2 *)\n simpl in Hxi, Hj ; case: Hxi => _ Hxi ; contradict Hxi ;\n apply Rle_not_lt, Rle_trans with (2 := proj1 Hj).\n move: Hi Hs ; rewrite ?SF_lx_cons /SF_lx.\n elim: i (fst h) (fst h0) (SF_h s) (unzip1 (SF_t s))\n => {s Hx Hx' Hj h y0 h0} [| i IH] h h0 h1 s Hi Hs.\n case: s Hi Hs => [| h2 s] Hi Hs /=.\n by apply lt_S_n, lt_S_n, lt_n_O in Hi.\n elim: s h h0 h1 h2 {Hi} Hs => [| h3 s IH] h h0 h1 h2 Hs /=.\n apply Rle_refl.\n apply Rle_trans with (r2 := h2).\n apply Hs.\n apply (IH h0 h1).\n apply (proj2 Hs).\n case: s Hi Hs => [| h2 s] Hi Hs.\n by apply lt_S_n, lt_S_n, lt_n_O in Hi.\n apply (IH h0 h1 h2 s).\n apply lt_S_n, Hi.\n apply Hs.\n(* j < i = size s - 2 *)\n simpl in Hxj, Hi ; case: Hxj => _ Hxj ; contradict Hxj ;\n apply Rle_not_lt, Rle_trans with (2 := proj1 Hi).\n move: Hj Hs ; rewrite ?SF_lx_cons /SF_lx.\n rewrite -minus_n_O ;\n elim: j (fst h) (fst h0) (SF_h s) (unzip1 (SF_t s))\n => {s Hx Hx' Hi h y0 h0} [ | j IH] h h0 h1 s Hj Hs /=.\n elim: s h h0 h1 {Hj} Hs => [| h2 s IH] h h0 h1 Hs /=.\n apply Rle_refl.\n apply Rle_trans with (r2 := h1).\n apply Hs.\n apply (IH h0 h1 h2).\n apply (proj2 Hs).\n case: s Hj Hs => [| h2 s] Hj Hs.\n by apply lt_S_n, lt_S_n, lt_S_n, lt_n_O in Hj.\n apply (IH h0 h1 h2 s).\n apply lt_S_n, Hj.\n apply Hs.\nQed.\n\nEnd SF_fun.\n\nLemma SF_fun_map {T T0 : Type} (f : T -> T0) (s : SF_seq) y0 :\n forall x, SF_fun (SF_map f s) (f y0) x = f (SF_fun s y0 x).\nProof.\n case: s => sh st ; rewrite /SF_fun /SF_map /= ; case: st => [| h st] x /=.\n by case: Rle_dec.\n case: Rlt_dec => //.\n elim: st sh h y0 x => [| h0 st IH] sh h y0 x Hx //=.\n by case: Rle_dec.\n case: Rlt_dec => // {Hx} Hx.\n by apply: (IH (fst h)).\nQed.\n\n(** * Particular SF_seq *)\n\nDefinition SF_seq_f1 {T : Type} (f1 : R -> T) (P : seq R) : SF_seq :=\n mkSF_seq (head 0 P) (pairmap (fun x y => (y, f1 x)) (head 0 P) (behead P)).\nDefinition SF_seq_f2 {T : Type} (f2 : R -> R -> T) (P : seq R) : SF_seq :=\n mkSF_seq (head 0 P) (pairmap (fun x y => (y, f2 x y)) (head 0 P) (behead P)).\n\nLemma SF_cons_f1 {T : Type} (f1 : R -> T) (h : R) (P : seq R) :\n (0 < size P)%nat -> SF_seq_f1 f1 (h::P) = SF_cons (h,f1 h) (SF_seq_f1 f1 P).\nProof.\n case: P => [ H | h0 P _] //.\n by apply lt_n_O in H.\nQed.\nLemma SF_cons_f2 {T : Type} (f2 : R -> R -> T) (h : R) (P : seq R) :\n (0 < size P)%nat ->\n SF_seq_f2 f2 (h::P) = SF_cons (h,f2 h (head 0 P)) (SF_seq_f2 f2 P).\nProof.\n case: P => [ H | h0 P _] //.\n by apply lt_n_O in H.\nQed.\n\nLemma SF_size_f1 {T : Type} (f1 : R -> T) P :\n SF_size (SF_seq_f1 f1 P) = Peano.pred (size P).\nProof.\n case: P => [| h P] //= ; by rewrite /SF_size /= size_pairmap.\nQed.\nLemma SF_size_f2 {T : Type} (f2 : R -> R -> T) P :\n SF_size (SF_seq_f2 f2 P) = Peano.pred (size P).\nProof.\n case: P => [| h P] //= ; by rewrite /SF_size /= size_pairmap.\nQed.\n\nLemma SF_lx_f1 {T : Type} (f1 : R -> T) P :\n (0 < size P)%nat -> SF_lx (SF_seq_f1 f1 P) = P.\nProof.\n elim: P => [ H | h l IH _] //=.\n by apply lt_n_O in H.\n case: l IH => [ | h' l] //= IH.\n rewrite -{2}IH //.\n by apply lt_O_Sn.\nQed.\nLemma SF_lx_f2 {T : Type} (f2 : R -> R -> T) P :\n (0 < size P)%nat ->\n SF_lx (SF_seq_f2 f2 P) = P.\nProof.\n elim: P => [ H | h l IH _] //=.\n by apply lt_n_O in H.\n case: l IH => [ | h' l] //= IH.\n rewrite -{2}IH //.\n by apply lt_O_Sn.\nQed.\n\nLemma SF_ly_f1 {T : Type} (f1 : R -> T) P :\n SF_ly (SF_seq_f1 f1 P) = Rcomplements.belast (map f1 P).\nProof.\n case: P => [| h P] // ; elim: P h => //= h P IH h0 ;\n by rewrite -(IH h).\nQed.\nLemma SF_ly_f2 {T : Type} (f2 : R -> R -> T) P :\n SF_ly (SF_seq_f2 f2 P) = behead (pairmap f2 0 P).\nProof.\n case: P => [| h P] // ; elim: P h => //= h P IH h0 ;\n by rewrite -(IH h).\nQed.\n\nLemma SF_sorted_f1 {T : Type} (f1 : R -> T) P Ord :\n (sorted Ord P) <-> (SF_sorted Ord (SF_seq_f1 f1 P)).\nProof.\n case: P => [ | h P] //.\n rewrite /SF_sorted SF_lx_f1 //.\n by apply lt_O_Sn.\nQed.\nLemma SF_sorted_f2 {T : Type} (f2 : R -> R -> T) P Ord :\n (sorted Ord P) <-> (SF_sorted Ord (SF_seq_f2 f2 P)).\nProof.\n case: P => [ | h P] //.\n rewrite /SF_sorted SF_lx_f2 //.\n by apply lt_O_Sn.\nQed.\n\nLemma SF_rev_f2 {T : Type} (f2 : R -> R -> T) P : (forall x y, f2 x y = f2 y x) ->\n SF_rev (SF_seq_f2 f2 P) = SF_seq_f2 f2 (rev P).\nProof.\n move => Hf2 ; apply SF_lx_ly_inj ;\n case: P => [ | h P] //=.\n rewrite SF_lx_rev !SF_lx_f2 ?rev_cons /= 1?headI // ; by apply lt_O_Sn.\n rewrite SF_ly_rev !SF_ly_f2 /= ?rev_cons.\n elim: P h => [ | h0 P IH] h //=.\n rewrite !rev_cons pairmap_rcons behead_rcons ?(IH h0) ?(Hf2 h h0) //.\n rewrite size_pairmap size_rcons ; apply lt_O_Sn.\nQed.\n\nLemma SF_map_f1 {T T0 : Type} (f : T -> T0) (f1 : R -> T) P :\n SF_map f (SF_seq_f1 f1 P) = SF_seq_f1 (fun x => f (f1 x)) P.\nProof.\n case: P => [| h P] // ; elim: P h => [| h0 P IH] h //.\n rewrite ?(SF_cons_f1 _ _ (h0::P)) /= ; try intuition.\n rewrite SF_map_cons IH ; intuition.\nQed.\nLemma SF_map_f2 {T T0 : Type} (f : T -> T0) (f2 : R -> R -> T) P :\n SF_map f (SF_seq_f2 f2 P) = SF_seq_f2 (fun x y => f (f2 x y)) P.\nProof.\n case: P => [| h P] // ; elim: P h => [| h0 P IH] h //.\n rewrite ?(SF_cons_f2 _ _ (h0::P)) /= ; try intuition.\n rewrite SF_map_cons IH ; intuition.\nQed.\n\nLemma ptd_f2 (f : R -> R -> R) s :\n sorted Rle s -> (forall x y, x <= y -> x <= f x y <= y)\n -> pointed_subdiv (SF_seq_f2 f s).\nProof.\n intros Hs Hf.\n elim: s Hs => [ _ | h s].\n intros i Hi.\n by apply lt_n_O in Hi.\n case: s => [ | h' s] IH Hs.\n intros i Hi.\n by apply lt_n_O in Hi.\n case => [ | i] Hi.\n apply Hf, Hs.\n apply IH.\n apply Hs.\n by apply lt_S_n.\nQed.\n\n(** ** SF_fun *)\n\nDefinition SF_fun_f1 {T : Type} (f1 : R -> T) (P : seq R) x : T :=\n SF_fun (SF_seq_f1 f1 P) (f1 0) x.\nDefinition SF_fun_f2 {T : Type} (f2 : R -> R -> T) (P : seq R) x :=\n SF_fun (SF_seq_f2 f2 P) (f2 0 0) x.\n\n(** * Uniform partition *)\n\nDefinition unif_part (a b : R) (n : nat) : seq R :=\n mkseq (fun i => a + (INR i) * (b - a) / (INR n + 1)) (S (S n)).\n\nLemma unif_part_bound (a b : R) (n : nat) :\n unif_part a b n = rev (unif_part b a n).\nProof.\n apply (@eq_from_nth R 0) ; rewrite ?size_rev ?size_mkseq => // ;\n move => i Hi ; apply SSR_leq in Hi.\n rewrite nth_rev ?SSR_minus ?size_mkseq.\n 2: now apply SSR_leq.\n rewrite ?nth_mkseq.\n 3: now apply SSR_leq.\n rewrite minus_INR ?S_INR => // ; field.\n apply Rgt_not_eq, INRp1_pos.\n apply SSR_leq, INR_le ; rewrite ?S_INR minus_INR ?S_INR => //.\n apply Rminus_le_0 ; ring_simplify.\n apply pos_INR.\nQed.\n\nLemma unif_part_sort (a b : R) (n : nat) : a <= b -> sorted Rle (unif_part a b n).\nProof.\n move => Hab ; apply sorted_nth => i Hi x0 ;\n rewrite ?size_mkseq in Hi ; rewrite ?nth_mkseq ?S_INR ;\n [ |apply SSR_leq ; intuition | apply SSR_leq ; intuition ].\n apply Rminus_le_0 ; field_simplify ;\n [| apply Rgt_not_eq ; intuition] ; rewrite ?Rdiv_1 ;\n apply Rdiv_le_0_compat ; intuition.\n rewrite Rplus_comm ; by apply (proj1 (Rminus_le_0 _ _)).\nQed.\n\nLemma head_unif_part x0 (a b : R) (n : nat) :\n head x0 (unif_part a b n) = a.\nProof.\n rewrite /= Rmult_0_l /Rdiv ; ring.\nQed.\n\nLemma last_unif_part x0 (a b : R) (n : nat) :\n last x0 (unif_part a b n) = b.\nProof.\n rewrite (last_nth b) size_mkseq.\n replace (nth b (x0 :: unif_part a b n) (S (S n)))\n with (nth b (unif_part a b n) (S n)) by auto.\n rewrite nth_mkseq.\n rewrite S_INR ; field.\n by apply Rgt_not_eq, INRp1_pos.\n by [].\nQed.\n\nLemma unif_part_nat (a b : R) (n : nat) (x : R) : (a <= x <= b) ->\n {i : nat |\n nth 0 (unif_part a b n) i <= x < nth 0 (unif_part a b n) (S i) /\\\n (S (S i) < size (unif_part a b n))%nat} +\n {nth 0 (unif_part a b n) (n) <= x <=\n nth 0 (unif_part a b n) (S n)}.\nProof.\n move: (sorted_dec (unif_part a b n) 0 x) => Hdec Hx.\n have Hs : sorted Rle (unif_part a b n) ;\n [ apply unif_part_sort, Rle_trans with (r2 := x) ; intuition\n | move: (Hdec Hs) => {Hdec Hs} Hdec].\n have Hx' : (head 0 (unif_part a b n) <= x <= last 0 (unif_part a b n)).\n by rewrite head_unif_part last_unif_part.\n case: (Hdec Hx') => {Hdec Hx'} [[i Hi]|Hi].\n left ; by exists i.\n right ; rewrite size_mkseq /= in Hi ; intuition.\n by rewrite -minus_n_O in H1.\nQed.\n\nLemma seq_step_unif_part (a b : R) (n : nat) :\n seq_step (unif_part a b n) = Rabs ((b - a) / (INR n + 1)).\nProof.\n assert (forall i, (S i < size (unif_part a b n))%nat ->\n (nth 0 (unif_part a b n) (S i) - nth 0 (unif_part a b n) i = (b - a) / (INR n + 1))%R).\n rewrite size_mkseq => i Hi.\n rewrite !nth_mkseq.\n rewrite S_INR /Rdiv /= ; ring.\n by apply SSR_leq, lt_le_weak.\n by apply SSR_leq.\n move: (eq_refl (size (unif_part a b n))).\n rewrite {2}size_mkseq.\n rewrite /seq_step ;\n elim: {2}(n) (unif_part a b n) H => [ | m IH] l //= ;\n destruct l as [ | x0 l] => //= ;\n destruct l as [ | x1 l] => //= ;\n destruct l as [ | x2 l] => //= ; intros.\n rewrite (H O).\n rewrite Rmax_comm /Rmax ; case: Rle_dec => // H1.\n contradict H1 ; by apply Rabs_pos.\n by apply lt_n_S, lt_O_Sn.\n rewrite -(IH (x1::x2::l)) /=.\n rewrite (H O).\n rewrite (H 1%nat).\n rewrite Rmax_assoc.\n apply f_equal2 => //.\n rewrite /Rmax ; by case: Rle_dec.\n by apply lt_n_S, lt_n_S, lt_O_Sn.\n by apply lt_n_S, lt_O_Sn.\n now intros ; apply (H (S i)), lt_n_S.\n by apply eq_add_S.\nQed.\n\nLemma seq_step_unif_part_ex (a b : R) (eps : posreal) :\n {n : nat | seq_step (unif_part a b n) < eps}.\nProof.\n destruct (nfloor_ex (Rabs ((b - a) / eps))) as [n Hn].\n by apply Rabs_pos.\n exists n.\n rewrite seq_step_unif_part.\n rewrite Rabs_div.\n rewrite (Rabs_pos_eq (INR n + 1)).\n apply Rlt_div_l.\n by apply INRp1_pos.\n rewrite Rmult_comm -Rlt_div_l.\n rewrite -(Rabs_pos_eq eps).\n rewrite -Rabs_div.\n by apply Hn.\n by apply Rgt_not_eq, eps.\n by apply Rlt_le, eps.\n by apply eps.\n by apply Rlt_le, INRp1_pos.\n by apply Rgt_not_eq, INRp1_pos.\nQed.\n\nLemma unif_part_S a b n :\n unif_part a b (S n) = a :: unif_part ((a * INR (S n) + b) / INR (S (S n))) b n.\nProof.\n apply eq_from_nth with 0.\n by rewrite /= !size_map !size_iota.\n case => [ | i] Hi.\n by rewrite nth0 head_unif_part.\n change (nth 0 (a :: unif_part ((a * INR (S n) + b) / INR (S (S n))) b n) (S i))\n with (nth 0 (unif_part ((a * INR (S n) + b) / INR (S (S n))) b n) i).\n rewrite /unif_part size_mkseq in Hi.\n rewrite /unif_part !nth_mkseq ; try by intuition.\n rewrite !S_INR ; field.\n rewrite -!S_INR ; split ; apply sym_not_eq, (not_INR 0), O_S.\nQed.\n\nDefinition SF_val_seq {T} (f : R -> T) (a b : R) (n : nat) : SF_seq :=\n SF_seq_f2 (fun x y => f ((x+y)/2)) (unif_part a b n).\nDefinition SF_val_fun {T} (f : R -> T) (a b : R) (n : nat) (x : R) : T :=\n SF_fun_f2 (fun x y => f ((x+y)/2)) (unif_part a b n) x.\n\nDefinition SF_val_ly {T} (f : R -> T) (a b : R) (n : nat) : seq T :=\n behead (pairmap (fun x y => f ((x+y)/2)) 0 (unif_part a b n)).\n\nLemma SF_val_ly_bound {T} (f : R -> T) (a b : R) (n : nat) :\n SF_val_ly f a b n = rev (SF_val_ly f b a n).\nProof.\n rewrite /SF_val_ly (unif_part_bound b a).\n case: (unif_part a b n) => [| h s] // ; elim: s h => [| h0 s IH] h //=.\n rewrite ?rev_cons.\n replace (pairmap (fun x y : R => f ((x + y) / 2)) 0 (rcons (rcons (rev s) h0) h))\n with (rcons (pairmap (fun x y : R => f ((x + y) / 2)) 0 (rcons (rev s) h0)) (f ((h0+h)/2))).\n rewrite behead_rcons.\n rewrite rev_rcons Rplus_comm -rev_cons -IH //.\n rewrite size_pairmap size_rcons ; apply lt_O_Sn.\n move: (0) h h0 {IH} ; apply rcons_ind with (s := s) => {s} [| s h1 IH] x0 h h0 //.\n rewrite ?rev_rcons /= IH //.\nQed.\n\n(** ** A proper filter on SF_seq *)\n\nLemma Riemann_fine_unif_part :\n forall (f : R -> R -> R) (a b : R) (n : nat),\n (forall a b, a <= b -> a <= f a b <= b) ->\n a <= b ->\n seq_step (SF_lx (SF_seq_f2 f (unif_part a b n))) <= (b - a) / (INR n + 1) /\\\n pointed_subdiv (SF_seq_f2 f (unif_part a b n)) /\\\n SF_h (SF_seq_f2 f (unif_part a b n)) = a /\\\n last (SF_h (SF_seq_f2 f (unif_part a b n))) (SF_lx (SF_seq_f2 f (unif_part a b n))) = b.\nProof.\nintros f a b n Hf Hab.\nassert (Hab' : 0 <= (b - a) / (INR n + 1)).\n apply Rdiv_le_0_compat.\n apply -> Rminus_le_0.\n apply Hab.\n apply INRp1_pos.\nunfold pointed_subdiv.\nrewrite SF_lx_f2.\nchange (head 0 (unif_part a b n) :: behead (unif_part a b n)) with (unif_part a b n).\nsplit ; [|split ; [|split]].\n- cut (forall i, (S i < size (unif_part a b n))%nat ->\n nth 0 (unif_part a b n) (S i) - nth 0 (unif_part a b n) i = (b - a) / (INR n + 1)).\n + induction (unif_part a b n) as [|x0 l IHl].\n now intros _.\n intros H.\n destruct l as [|x1 l].\n easy.\n change (seq_step _) with (Rmax (Rabs (x1 - x0)) (seq_step (x1 :: l))).\n apply Rmax_case.\n apply Req_le.\n rewrite (H 0%nat).\n now apply Rabs_pos_eq.\n apply lt_n_S.\n apply lt_0_Sn.\n apply IHl.\n intros i Hi.\n apply (H (S i)).\n now apply lt_n_S.\n + rewrite size_mkseq.\n intros i Hi.\n rewrite !nth_mkseq.\n rewrite S_INR.\n unfold Rdiv.\n ring.\n apply SSR_leq.\n now apply lt_le_weak.\n now apply SSR_leq.\n- unfold pointed_subdiv.\n rewrite SF_size_f2.\n rewrite size_mkseq.\n intros i Hi.\n rewrite SF_ly_f2.\n rewrite nth_behead.\n apply gt_S_le, SSR_leq in Hi.\n rewrite (nth_pairmap 0).\n change (nth 0 (0 :: unif_part a b n) (S i)) with (nth 0 (unif_part a b n) i).\n apply Hf.\n rewrite !nth_mkseq //.\n rewrite S_INR.\n lra.\n now apply ssrnat.leqW.\n by rewrite size_mkseq.\n- apply head_unif_part.\n- apply last_unif_part.\nrewrite size_mkseq ; by apply lt_O_Sn.\nQed.\n\nDefinition Riemann_fine (a b : R) :=\n within (fun ptd => pointed_subdiv ptd /\\ SF_h ptd = Rmin a b /\\ last (SF_h ptd) (SF_lx ptd) = Rmax a b)\n (locally_dist (fun ptd => seq_step (SF_lx ptd))).\n\nGlobal Instance Riemann_fine_filter :\n forall a b, ProperFilter (Riemann_fine a b).\nProof.\nintros a b.\nconstructor.\n- intros P [alpha H].\n assert (Hab : Rmin a b <= Rmax a b).\n apply Rmax_case.\n apply Rmin_l.\n apply Rmin_r.\n assert (Hn : 0 <= ((Rmax a b - Rmin a b) / alpha)).\n apply Rdiv_le_0_compat.\n apply -> Rminus_le_0.\n apply Hab.\n apply cond_pos.\n set n := (nfloor _ Hn).\n exists (SF_seq_f2 (fun x y => x) (unif_part (Rmin a b) (Rmax a b) n)).\n destruct (Riemann_fine_unif_part (fun x y => x) (Rmin a b) (Rmax a b) n).\n intros u v Huv.\n split.\n apply Rle_refl.\n exact Huv.\n exact Hab.\n apply H.\n apply Rle_lt_trans with (1 := H0).\n apply Rlt_div_l.\n apply INRp1_pos.\n unfold n, nfloor.\n destruct nfloor_ex as [n' Hn'].\n simpl.\n rewrite Rmult_comm.\n apply Rlt_div_l.\n apply cond_pos.\n apply Hn'.\n exact H1.\n- apply within_filter.\n apply locally_dist_filter.\nQed.\n\n(** * Riemann sums *)\n\n(** Riemann_sum *)\n\nSection Riemann_sum.\n\nContext {V : ModuleSpace R_Ring}.\n\nDefinition Riemann_sum (f : R -> V) (ptd : SF_seq) : V :=\n foldr plus zero (pairmap (fun x y => (scal (fst y - fst x) (f (snd y)))) (SF_h ptd,zero) (SF_t ptd)).\n\nLemma Riemann_sum_cons (f : R -> V) (h0 : R * R) (ptd : SF_seq) :\n Riemann_sum f (SF_cons h0 ptd) =\n plus (scal (SF_h ptd - fst h0) (f (snd h0))) (Riemann_sum f ptd).\nProof.\n rewrite /Riemann_sum /=.\n case: h0 => x0 y0 ;\n apply SF_cons_dec with (s := ptd) => {ptd} [ x1 | [x1 y1] ptd ] //=.\nQed.\n\nLemma Riemann_sum_rcons (f : R -> V) ptd l0 :\n Riemann_sum f (SF_rcons ptd l0) =\n plus (Riemann_sum f ptd) (scal (fst l0 - last (SF_h ptd) (SF_lx ptd)) (f (snd l0))).\nProof.\n rewrite /Riemann_sum .\n case: l0 => x0 y0.\n apply SF_rcons_dec with (s := ptd) => {ptd} [ x1 | ptd [x1 y1]].\n apply plus_comm.\n rewrite ?SF_map_rcons /=.\n rewrite pairmap_rcons foldr_rcons /=.\n rewrite unzip1_rcons last_rcons /=.\n set l := pairmap _ _ _.\n induction l ; simpl.\n apply plus_comm.\n rewrite IHl.\n apply plus_assoc.\nQed.\n\nLemma Riemann_sum_zero (f : R -> V) ptd :\n SF_sorted Rle ptd ->\n SF_h ptd = last (SF_h ptd) (SF_lx ptd) ->\n Riemann_sum f ptd = zero.\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} [x0 | [x0 y0] ptd IH] //= Hs Hhl.\n rewrite Riemann_sum_cons IH /= => {IH}.\n replace x0 with (SF_h ptd).\n rewrite Rminus_eq_0.\n rewrite plus_zero_r.\n by apply: scal_zero_l.\n apply Rle_antisym.\n rewrite Hhl => {Hhl} /=.\n apply (sorted_last (SF_h ptd :: @map (R*R) R (@fst R R) (SF_t ptd)) O) with (x0 := 0).\n replace ((SF_h ptd) :: map _ _) with (SF_lx ptd).\n apply Hs.\n apply SF_cons_ind with (s := ptd) => {ptd Hs} [x1 | [x1 y1] ptd IH] //=.\n apply lt_O_Sn.\n apply Hs.\n apply Hs.\n apply Rle_antisym.\n apply (sorted_last (SF_h ptd :: @map (R*R) R (@fst R R) (SF_t ptd)) O) with (x0 := 0).\n replace ((SF_h ptd) :: map _ _) with (SF_lx ptd).\n apply Hs.\n apply SF_cons_ind with (s := ptd) => {ptd Hs Hhl} [x1 | [x1 y1] ptd IH] //=.\n apply lt_O_Sn.\n move: Hhl ; rewrite -?(last_map (@fst R R)) /= => <- ; apply Hs.\nQed.\n\nLemma Riemann_sum_map (f : R -> V) (g : R -> R) ptd :\n Riemann_sum (fun x => f (g x)) ptd = Riemann_sum f (SF_map g ptd).\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} [x0 | h ptd IH].\n by [].\n rewrite SF_map_cons !Riemann_sum_cons /=.\n by rewrite IH.\nQed.\n\nLemma Riemann_sum_const (v : V) ptd :\n Riemann_sum (fun _ => v) ptd = scal (last (SF_h ptd) (SF_lx ptd) - SF_h ptd) v.\nProof.\napply SF_cons_ind with (s := ptd) => {ptd} [x0 | [x0 y0] s IH] /=.\nby rewrite /Riemann_sum /= Rminus_eq_0 scal_zero_l.\nrewrite Riemann_sum_cons IH /=.\nrewrite -scal_distr_r /=.\napply (f_equal (fun x => scal x v)).\nrewrite /plus /=.\nring.\nQed.\n\nLemma Riemann_sum_scal (a : R) (f : R -> V) ptd :\n Riemann_sum (fun x => scal a (f x)) ptd = scal a (Riemann_sum f ptd).\nProof.\napply SF_cons_ind with (s := ptd) => {ptd} /= [x0 | [x0 y0] s IH].\nrewrite /Riemann_sum /=.\napply sym_eq. apply @scal_zero_r.\nrewrite !Riemann_sum_cons /= IH.\nrewrite scal_distr_l.\napply f_equal with (f := fun v => plus v _).\nrewrite 2!scal_assoc.\nby rewrite /mult /= Rmult_comm.\nQed.\n\nLemma Riemann_sum_opp (f : R -> V) ptd :\n Riemann_sum (fun x => opp (f x)) ptd = opp (Riemann_sum f ptd).\nProof.\napply SF_cons_ind with (s := ptd) => {ptd} /= [x0 | [x0 y0] s IH].\nrewrite /Riemann_sum /=.\napply sym_eq, @opp_zero.\nrewrite !Riemann_sum_cons /= IH.\nrewrite opp_plus.\napply f_equal with (f := fun v => plus v (opp (Riemann_sum f s))).\napply scal_opp_r.\nQed.\n\nLemma Riemann_sum_plus (f g : R -> V) ptd :\n Riemann_sum (fun x => plus (f x) (g x)) ptd =\n plus (Riemann_sum f ptd) (Riemann_sum g ptd).\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} /= [x0 | [x0 y0] s IH].\n rewrite /Riemann_sum /=.\n apply sym_eq, @plus_zero_l.\n rewrite !Riemann_sum_cons /= ; rewrite IH.\n rewrite scal_distr_l.\n rewrite -!plus_assoc.\n apply f_equal.\n rewrite !plus_assoc.\n apply (f_equal (fun x => plus x (Riemann_sum g s))).\n apply plus_comm.\nQed.\n\nLemma Riemann_sum_minus (f g : R -> V) ptd :\n Riemann_sum (fun x => minus (f x) (g x)) ptd =\n minus (Riemann_sum f ptd) (Riemann_sum g ptd).\nProof.\nunfold minus.\nrewrite -Riemann_sum_opp.\napply Riemann_sum_plus.\nQed.\n\nEnd Riemann_sum.\n\nSection Riemann_sum_Normed.\n\nContext {V : NormedModule R_AbsRing}.\n\nLemma Riemann_sum_Chasles_0\n (f : R -> V) (M : R) (x : R) ptd :\n forall (eps : posreal),\n (forall x, SF_h ptd <= x <= last (SF_h ptd) (SF_lx ptd) -> norm (f x) < M) ->\n SF_h ptd <= x <= last (SF_h ptd) (SF_lx ptd) ->\n pointed_subdiv ptd ->\n seq_step (SF_lx ptd) < eps ->\n norm (minus (plus (Riemann_sum f (SF_cut_down ptd x)) (Riemann_sum f (SF_cut_up ptd x)))\n (Riemann_sum f ptd)) < 2 * eps * M.\nProof.\n intros eps.\n apply (SF_cons_ind (T := R)) with (s := ptd)\n => {ptd} /= [ x0 | [x0 y1] ptd IH] /= Hfx [ Hx0 Hl] Hptd Hstep.\n + rewrite (Rle_antisym _ _ Hx0 Hl) ; clear -Hfx.\n rewrite /Riemann_sum /=.\n case: Rle_dec (Rle_refl x) => //= _ _.\n rewrite ?plus_zero_r Rminus_eq_0.\n rewrite scal_zero_l.\n rewrite /minus plus_zero_l norm_opp norm_zero.\n apply Rmult_lt_0_compat.\n apply Rmult_lt_0_compat.\n by apply Rlt_0_2.\n by apply eps.\n by apply Rle_lt_trans with (2:= (Hfx x0 (conj (Rle_refl _) (Rle_refl _)))), norm_ge_0.\n + case: (Rle_dec (SF_h ptd) x) => Hx1.\n - replace (minus (plus (Riemann_sum f (SF_cut_down (SF_cons (x0, y1) ptd) x))\n (Riemann_sum f (SF_cut_up (SF_cons (x0, y1) ptd) x)))\n (Riemann_sum f (SF_cons (x0, y1) ptd)))\n with (minus (plus (Riemann_sum f (SF_cut_down ptd x))\n (Riemann_sum f (SF_cut_up ptd x))) (Riemann_sum f ptd)).\n apply IH.\n intros y Hy.\n apply Hfx.\n split.\n apply Rle_trans with y1.\n by apply (Hptd O (lt_O_Sn _)).\n apply Rle_trans with (SF_h ptd).\n by apply (Hptd O (lt_O_Sn _)).\n by apply Hy.\n by apply Hy.\n by split.\n by apply ptd_cons in Hptd.\n apply Rle_lt_trans with (2 := Hstep).\n by apply Rmax_r.\n rewrite SF_cut_down_cons_2.\n rewrite SF_cut_up_cons_2.\n rewrite /minus 2?(Riemann_sum_cons _ (x0, y1)) SF_cut_down_h.\n rewrite opp_plus plus_assoc /=.\n apply (f_equal (fun x => plus x _)).\n rewrite (plus_comm (scal (SF_h ptd - x0) (f y1))) -2!plus_assoc.\n apply f_equal.\n by rewrite plus_comm -plus_assoc plus_opp_l plus_zero_r.\n by [].\n split ; [ | apply Hx1].\n apply Rle_trans with y1 ; by apply (Hptd O (lt_O_Sn _)).\n split ; [ | apply Hx1].\n apply Rle_trans with y1 ; by apply (Hptd O (lt_O_Sn _)).\n - apply Rnot_le_lt in Hx1.\n rewrite SF_cut_down_cons_1 /=.\n rewrite SF_cut_up_cons_1 /=.\n rewrite 3!Riemann_sum_cons /= => {IH}.\n replace (Riemann_sum f (SF_nil x) : V) with (zero : V) by auto.\n rewrite plus_zero_r /minus opp_plus.\n rewrite (plus_comm (opp (scal (SF_h ptd - x0) (f y1)))).\n rewrite ?plus_assoc -(plus_assoc _ _ (opp (Riemann_sum f ptd))).\n rewrite plus_opp_r plus_zero_r.\n rewrite -scal_opp_l.\n rewrite /opp /= Ropp_minus_distr.\n rewrite /Rmin /Rmax ; case: Rle_dec => _.\n rewrite (plus_comm (scal (x - x0) (f y1))) -plus_assoc.\n rewrite -scal_distr_r /plus /= -/plus.\n ring_simplify (x - x0 + (x0 - SF_h ptd)).\n eapply Rle_lt_trans.\n apply @norm_triangle.\n replace (2 * eps * M) with (eps * M + eps * M) by ring.\n apply Rplus_lt_compat ;\n eapply Rle_lt_trans ; try (apply @norm_scal) ;\n apply Rmult_le_0_lt_compat.\n by apply Rabs_pos.\n by apply norm_ge_0.\n apply Rle_lt_trans with (2 := Hstep).\n apply Rle_trans with (2 := Rmax_l _ _).\n simpl.\n apply Rlt_le in Hx1.\n move: (Rle_trans _ _ _ Hx0 Hx1) => Hx0'.\n apply Rminus_le_0 in Hx1.\n apply Rminus_le_0 in Hx0'.\n rewrite /abs /= ?Rabs_pos_eq //.\n by apply Rplus_le_compat_l, Ropp_le_contravar.\n apply Hfx.\n by split.\n by apply Rabs_pos.\n by apply norm_ge_0.\n apply Rle_lt_trans with (2 := Hstep).\n apply Rle_trans with (2 := Rmax_l _ _).\n rewrite /abs /plus /= -Ropp_minus_distr Rabs_Ropp.\n apply Rlt_le in Hx1.\n move: (Rle_trans _ _ _ Hx0 Hx1) => Hx0'.\n apply Rminus_le_0 in Hx1.\n apply Rminus_le_0 in Hx0'.\n rewrite ?Rabs_pos_eq //.\n by apply Rplus_le_compat_l, Ropp_le_contravar.\n apply Hfx.\n split.\n apply (Hptd O (lt_O_Sn _)).\n apply Rle_trans with (SF_h ptd).\n apply (Hptd O (lt_O_Sn _)).\n apply (fun H => sorted_last ((SF_h ptd) :: (unzip1 (SF_t ptd))) O H (lt_O_Sn _) (SF_h ptd)).\n apply ptd_sort in Hptd.\n by apply Hptd.\n rewrite -plus_assoc -scal_distr_r /plus /= -/plus.\n replace (SF_h ptd - x + (x0 - SF_h ptd)) with (opp (x - x0)) by (rewrite /opp /= ; ring).\n rewrite scal_opp_l -scal_opp_r.\n rewrite -scal_distr_l.\n eapply Rle_lt_trans. apply @norm_scal.\n replace (2 * eps * M) with (eps * (M + M)) by ring.\n apply Rmult_le_0_lt_compat.\n by apply Rabs_pos.\n by apply norm_ge_0.\n apply Rle_lt_trans with (2 := Hstep).\n apply Rle_trans with (2 := Rmax_l _ _).\n simpl.\n apply Rlt_le in Hx1.\n move: (Rle_trans _ _ _ Hx0 Hx1) => Hx0'.\n apply Rminus_le_0 in Hx0.\n apply Rminus_le_0 in Hx0'.\n rewrite /abs /= ?Rabs_pos_eq //.\n by apply Rplus_le_compat_r.\n apply Rle_lt_trans with (norm (f x) + norm (opp (f y1))).\n apply @norm_triangle.\n apply Rplus_lt_compat.\n apply Hfx.\n by split.\n rewrite norm_opp.\n apply Hfx.\n split.\n apply (Hptd O (lt_O_Sn _)).\n apply Rle_trans with (SF_h ptd).\n apply (Hptd O (lt_O_Sn _)).\n apply (fun H => sorted_last ((SF_h ptd) :: (unzip1 (SF_t ptd))) O H (lt_O_Sn _) (SF_h ptd)).\n apply ptd_sort in Hptd.\n by apply Hptd.\n by split.\n by split.\nQed.\n\nLemma Riemann_sum_norm (f : R -> V) (g : R -> R) ptd :\n pointed_subdiv ptd ->\n (forall t, SF_h ptd <= t <= last (SF_h ptd) (SF_lx ptd) -> norm (f t) <= g t)\n -> norm (Riemann_sum f ptd) <= Riemann_sum g ptd.\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} /= [x0 | [x0 y0] s IH] /= Hs H.\n rewrite norm_zero ; exact: Rle_refl.\n rewrite !Riemann_sum_cons /=.\n eapply Rle_trans.\n by apply @norm_triangle.\n apply Rplus_le_compat.\n eapply Rle_trans. apply @norm_scal.\n refine (_ (Hs O _)).\n simpl.\n intros [H1 H2].\n rewrite /abs /= Rabs_pos_eq.\n apply Rmult_le_compat_l.\n apply -> Rminus_le_0.\n now apply Rle_trans with y0.\n apply H.\n apply (conj H1).\n apply Rle_trans with (1 := H2).\n apply (sorted_last (SF_lx s) O) with (x0 := 0).\n by apply (ptd_sort _ Hs).\n exact: lt_O_Sn.\n apply -> Rminus_le_0.\n now apply Rle_trans with y0.\n exact: lt_O_Sn.\n apply IH.\n by apply ptd_cons with (h := (x0,y0)).\n move => t Ht ; apply H ; split.\n by apply Rle_trans with (2 := proj1 Ht), (ptd_sort _ Hs).\n by apply Ht.\nQed.\n\nEnd Riemann_sum_Normed.\n\nLemma Riemann_sum_le (f : R -> R) (g : R -> R) ptd :\n pointed_subdiv ptd ->\n (forall t, SF_h ptd <= t <= last (SF_h ptd) (SF_lx ptd) -> f t <= g t) ->\n Riemann_sum f ptd <= Riemann_sum g ptd.\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} /= [x0 | [x0 y0] s IH] /= Hs H.\n apply Rle_refl.\n rewrite !Riemann_sum_cons /=.\n apply Rplus_le_compat.\n refine (_ (Hs O _)).\n simpl.\n intros [H1 H2].\n apply Rmult_le_compat_l.\n apply -> Rminus_le_0.\n now apply Rle_trans with y0.\n apply H.\n apply (conj H1).\n apply Rle_trans with (1 := H2).\n apply (sorted_last (SF_lx s) O) with (x0 := 0).\n by apply (ptd_sort _ Hs).\n exact: lt_O_Sn.\n exact: lt_O_Sn.\n apply IH.\n by apply ptd_cons with (h := (x0,y0)).\n move => t Ht ; apply H ; split.\n by apply Rle_trans with (2 := proj1 Ht), (ptd_sort _ Hs).\n by apply Ht.\nQed.\n\n(** Structures *)\n\nLemma Riemann_sum_pair {U : ModuleSpace R_Ring} {V : ModuleSpace R_Ring}\n (f : R -> U * V) ptd :\n Riemann_sum f ptd =\n (Riemann_sum (fun t => fst (f t)) ptd, Riemann_sum (fun t => snd (f t)) ptd).\nProof.\n apply SF_cons_ind with (s := ptd) => {ptd} [x0 | h0 ptd IH].\n by [].\n rewrite !Riemann_sum_cons IH.\n by apply injective_projections.\nQed.\n\n(** RInt_val *)\n\nSection RInt_val.\n\nContext {V : ModuleSpace R_Ring}.\n\nDefinition RInt_val (f : R -> V) (a b : R) (n : nat) :=\n Riemann_sum f (SF_seq_f2 (fun x y => (x + y) / 2) (unif_part a b n)).\n\nLemma RInt_val_point (f : R -> V) (a : R) (n : nat) :\n RInt_val f a a n = zero.\nProof.\n unfold RInt_val ; apply Riemann_sum_zero.\n rewrite /SF_sorted SF_lx_f2.\n apply unif_part_sort ; apply Rle_refl.\n rewrite size_mkseq ; by apply lt_O_Sn.\n rewrite SF_lx_f2 /=.\n rewrite -{2}[1]/(INR 1) last_map.\n unfold Rdiv ; ring.\n by apply lt_O_Sn.\nQed.\n\nLemma RInt_val_swap :\n forall (f : R -> V) (a b : R) (n : nat),\n RInt_val f a b n = opp (RInt_val f b a n).\nProof.\n intros f a b n.\n rewrite /RInt_val.\n rewrite -Riemann_sum_opp.\n rewrite unif_part_bound.\n elim: (unif_part b a n) => [ | x1 s IH] /=.\n by [].\n clear -IH.\n rewrite rev_cons.\n destruct s as [ | x2 s].\n by [].\n rewrite SF_cons_f2.\n 2: by apply lt_O_Sn.\n rewrite Riemann_sum_cons /= -IH => {IH}.\n rewrite scal_opp_r -scal_opp_l /=.\n rewrite rev_cons.\n elim: (rev s) => {s} /= [ | x3 s IH].\n rewrite /Riemann_sum /=.\n apply (f_equal2 (fun x y => plus (scal x (f y)) _)) ;\n rewrite /Rdiv /opp /= ; ring.\n rewrite !SF_cons_f2 ; try (by rewrite size_rcons ; apply lt_O_Sn).\n rewrite !Riemann_sum_cons /= IH !plus_assoc => {IH}.\n apply (f_equal (fun x => plus x _)).\n rewrite plus_comm.\n apply f_equal.\n apply (f_equal2 (fun x y => scal (x - x3)\n (f ((x3 + y) / 2)))) ; clear ;\n by elim: s.\nQed.\n\nLemma RInt_val_ext (f g : R -> V) (a b : R) (n : nat) :\n (forall x, Rmin a b <= x <= Rmax a b -> f x = g x)\n -> RInt_val g a b n = RInt_val f a b n.\nProof.\n wlog: a b / (a <= b) => [Hw | Hab].\n case: (Rle_lt_dec a b) => Hab.\n by apply Hw.\n rewrite Rmin_comm Rmax_comm => Heq.\n apply Rlt_le in Hab.\n rewrite RInt_val_swap Hw => //=.\n apply sym_eq ; by apply RInt_val_swap.\n rewrite /Rmin /Rmax ; case: Rle_dec => //= _ Heq.\n unfold RInt_val.\n set l := (SF_seq_f2 (fun x y : R => (x + y) / 2) (unif_part a b n)).\n assert (forall i, (i < size (SF_ly l))%nat -> f (nth 0 (SF_ly l) i) = g (nth 0 (SF_ly l) i)).\n move => i Hi.\n apply Heq.\n destruct (fun H0 => Riemann_fine_unif_part (fun x y : R => (x + y) / 2) a b n H0 Hab) as [H [H0 [H1 H2]]].\n clear.\n intros a b Hab.\n lra.\n fold l in H, H0, H1, H2.\n rewrite -H1 -H2 ; split.\n apply Rle_trans with (head 0 (SF_ly l)).\n apply (H0 O).\n by apply lt_O_Sn.\n apply sorted_head.\n by apply ptd_sort'.\n by [].\n apply Rle_trans with (last 0 (SF_ly l)).\n apply sorted_last.\n by apply ptd_sort'.\n by [].\n rewrite -!nth_last SF_size_ly SF_size_lx SF_size_f2 size_mkseq.\n simpl Peano.pred.\n replace (nth (SF_h l) (SF_lx l) (S n)) with (nth 0 (SF_lx l) (S n)).\n apply (H0 n).\n rewrite SF_size_f2 size_mkseq /=.\n by apply lt_n_Sn.\n rewrite SF_lx_f2.\n assert (size (unif_part a b n) = S (S n)).\n by apply size_mkseq.\n elim: (S n) (unif_part a b n) H3 ; simpl ; clear ; intros.\n destruct unif_part0 ; simpl => //.\n replace unif_part0 with (head 0 unif_part0 :: behead unif_part0).\n apply H.\n destruct unif_part0 ; by intuition.\n destruct unif_part0 ; by intuition.\n by apply lt_O_Sn.\n move: H => {Heq}.\n apply SF_cons_ind with (s := l) => {l} [x0 | h0 s IH] /= Heq.\n by [].\n rewrite !Riemann_sum_cons.\n apply (f_equal2 (fun x y => plus (scal (SF_h s - fst h0) x) y)).\n by apply sym_eq, (Heq O), lt_O_Sn.\n apply IH => i Hi.\n now apply (Heq (S i)), lt_n_S.\nQed.\n\nLemma RInt_val_comp_opp (f : R -> V) (a b : R) (n : nat) :\n RInt_val (fun x => f (- x)) a b n = opp (RInt_val f (- a) (- b) n).\nProof.\n rewrite /RInt_val.\n replace (unif_part (- a) (- b) n) with (map Ropp (unif_part a b n)).\n elim: (unif_part a b n) {1}0 {2}0 => /= [ | x1 s IH] x0 x0'.\n rewrite /Riemann_sum /=.\n by apply sym_eq, @opp_zero.\n destruct s as [ | x2 s].\n rewrite /Riemann_sum /=.\n by apply sym_eq, @opp_zero.\n rewrite (SF_cons_f2 _ x1) ; try by apply lt_O_Sn.\n rewrite (SF_cons_f2 _ (- x1)) ; try by apply lt_O_Sn.\n rewrite !Riemann_sum_cons /=.\n rewrite opp_plus.\n apply f_equal2.\n rewrite -scal_opp_l.\n apply (f_equal2 (fun x y => scal x (f y))) ;\n rewrite /Rdiv /opp /= ; field.\n by apply IH.\n apply eq_from_nth with 0.\n by rewrite size_map !size_mkseq.\n rewrite size_map => i Hi.\n rewrite (nth_map 0 0) => //.\n rewrite size_mkseq in Hi.\n rewrite !nth_mkseq => //.\n field.\n now rewrite -S_INR ; apply not_0_INR, sym_not_eq, O_S.\nQed.\n\nLemma RInt_val_comp_lin (f : R -> V) (u v : R) (a b : R) (n : nat) :\n scal u (RInt_val (fun x => f (u * x + v)) a b n) = RInt_val f (u * a + v) (u * b + v) n.\nProof.\n rewrite /RInt_val.\n replace (unif_part (u * a + v) (u * b + v) n) with (map (fun x => u * x + v) (unif_part a b n)).\n elim: (unif_part a b n) {1}0 {2}0 => /= [ | x1 s IH] x0 x0'.\n by apply @scal_zero_r.\n destruct s as [ | x2 s].\n by apply @scal_zero_r.\n rewrite (SF_cons_f2 _ x1) ; try by apply lt_O_Sn.\n rewrite (SF_cons_f2 _ (u * x1 + v)) ; try by apply lt_O_Sn.\n rewrite !Riemann_sum_cons /=.\n rewrite scal_distr_l.\n apply f_equal2.\n rewrite scal_assoc.\n apply (f_equal2 (fun x y => scal x (f y))) ;\n rewrite /mult /= ; field.\n by apply IH.\n apply eq_from_nth with 0.\n by rewrite size_map !size_mkseq.\n rewrite size_map => i Hi.\n rewrite (nth_map 0 0) => //.\n rewrite size_mkseq in Hi.\n rewrite !nth_mkseq => //.\n field.\n now rewrite -S_INR ; apply not_0_INR, sym_not_eq, O_S.\nQed.\n\nEnd RInt_val.\n\n(** ** From SF_seq to StepFun *)\n\n(** Alternative Chasles relation *)\n\nFixpoint seq_cut_down' (s : seq (R*R)) (x x0 : R) : seq (R*R) :=\n match s with\n | [::] => [:: (x,x0)]\n | h :: t =>\n match Rle_dec (fst h) x with\n | right _ => [:: (x,snd h)]\n | left _ => h :: (seq_cut_down' t x (snd h))\n end\n end.\nFixpoint seq_cut_up' (s : seq (R*R)) (x x0 : R) : seq (R*R) :=\n match s with\n | [::] => [:: (x,x0)]\n | h :: t =>\n match Rle_dec (fst h) x with\n | right _ => (x,x0)::h::t\n | left _ => seq_cut_up' t x (snd h)\n end\n end.\n\nDefinition SF_cut_down' (sf : @SF_seq R) (x : R) x0 :=\n let s := seq_cut_down' ((SF_h sf,x0) :: (SF_t sf)) x x0 in\n mkSF_seq (fst (head (SF_h sf,x0) s)) (behead s).\nDefinition SF_cut_up' (sf : @SF_seq R) (x : R) x0 :=\n let s := seq_cut_up' ((SF_h sf,x0) :: (SF_t sf)) x x0 in\n mkSF_seq (fst (head (SF_h sf,x0) s)) (behead s).\nLemma SF_Chasles {V : ModuleSpace R_AbsRing} (f : R -> V) (s : SF_seq) x x0 :\n (SF_h s <= x <= last (SF_h s) (unzip1 (SF_t s))) ->\n Riemann_sum f s =\n plus (Riemann_sum f (SF_cut_down' s x x0)) (Riemann_sum f (SF_cut_up' s x x0)).\nProof.\n rename x0 into z0.\n apply SF_cons_ind with (s := s) => {s} /= [ x0 | [x0 y0] s IH] /= Hx.\n rewrite (Rle_antisym _ _ (proj1 Hx) (proj2 Hx)).\n move: (Rle_refl x).\n rewrite /SF_cut_down' /SF_cut_up' /= ; case: Rle_dec => //= _ _.\n by rewrite /Riemann_sum /= Rminus_eq_0 scal_zero_l !plus_zero_l.\n move: (fun Hx1 => IH (conj Hx1 (proj2 Hx))) => {IH}.\n rewrite /SF_cut_down' /SF_cut_up' /= ;\n case: (Rle_dec x0 _) (proj1 Hx) => //= Hx0 _.\n case: (Rle_dec (SF_h s) x) => //= Hx1 IH.\n move: (IH Hx1) => {IH} IH.\n rewrite (Riemann_sum_cons _ (x0,y0))\n (Riemann_sum_cons _ (x0,y0) (mkSF_seq (SF_h s) (seq_cut_down' (SF_t s) x y0)))\n IH /= => {IH}.\n rewrite -!plus_assoc ; apply f_equal.\n assert (forall x0 y0, fst (head (x0, z0) (seq_cut_up' (SF_t s) x y0)) = x).\n elim: (SF_t s) => [ | x2 t IH] x1 y1 //=.\n by case: Rle_dec.\n rewrite ?H.\n move: (proj2 Hx) Hx1 => {Hx} ;\n apply SF_cons_dec with (s := s) => {s H} /= [x1 | [x1 y1] s] //= Hx Hx1.\n by rewrite /Riemann_sum /= (Rle_antisym _ _ Hx Hx1) Rminus_eq_0 !scal_zero_l !plus_zero_l.\n case: Rle_dec => //.\n rewrite Riemann_sum_cons (Riemann_sum_cons _ (x,y0) s) {2}/Riemann_sum /=.\n clear IH.\n rewrite plus_zero_r !plus_assoc.\n apply f_equal2 => //.\n rewrite -scal_distr_r.\n apply f_equal2 => //.\n rewrite /plus /= ; ring.\nQed.\n\nLemma seq_cut_up_head' (s : seq (R*R)) x x0 z :\n fst (head z (seq_cut_up' s x x0)) = x.\nProof.\n elim: s z x0 => [ | x1 s IH] //= z x0.\n by case: Rle_dec.\nQed.\n\n(** Build StepFun using SF_seq *)\n\nLemma ad_SF_compat z0 (s : SF_seq) (pr : SF_sorted Rle s) :\n adapted_couple (SF_fun s z0) (head 0 (SF_lx s)) (last 0 (SF_lx s))\n (seq2Rlist (SF_lx s)) (seq2Rlist (SF_ly s)).\nProof.\n(* head and last *)\n have H : ((head 0 (SF_lx s)) <= (last 0 (SF_lx s))).\n move: pr ; rewrite /SF_sorted.\n case: (SF_lx s) => {s} [| h s] Hs.\n apply Rle_refl.\n rewrite -nth0 ; apply sorted_last => // ; apply lt_O_Sn.\n rewrite /adapted_couple ?nth_compat ?size_compat ?nth0 ?nth_last\n /Rmin /Rmax ?SF_size_lx ?SF_size_ly ;\n case: (Rle_dec (head 0 (SF_lx s)) (last 0 (SF_lx s))) => // {H} _ ; intuition.\n(* sorted *)\n apply sorted_compat => //.\n(* adapted *)\n move: i pr H ; apply SF_cons_dec with (s := s)\n => {s} [x0 | h s] i Hs Hi x [Hx0 Hx1].\n by apply lt_n_O in Hi.\n rewrite /SF_fun ?SF_size_cons ?nth_compat -?SF_size_lx ?SF_lx_cons in Hi, Hx0, Hx1 |- *.\n simpl.\n move: h i x {1}z0 Hs Hi Hx0 Hx1 ; apply SF_cons_ind with (s := s)\n => {s} [x1 | h0 s IH] h ; case => [| i ] x z0' Hs Hi Hx0 Hx1 //= ; case: Rlt_dec => Hx' //.\n now contradict Hx' ; apply Rle_not_lt, Rlt_le, Hx0.\n now case: Rle_dec => Hx'' // ; contradict Hx'' ; apply Rlt_le, Hx1.\n now rewrite /= in Hi ; by apply lt_S_n, lt_n_O in Hi.\n now rewrite /= in Hi ; by apply lt_S_n, lt_n_O in Hi.\n now contradict Hx' ; apply Rle_not_lt, Rlt_le, Hx0.\n now case: Rlt_dec => Hx'' //.\n now contradict Hx' ; apply Rle_not_lt, Rlt_le, Rle_lt_trans with (2 := Hx0) ;\n have Hi' : (S i < size (SF_lx (SF_cons h (SF_cons h0 s))))%nat ;\n [ rewrite ?SF_lx_cons /= in Hi |-* ; apply lt_trans with (1 := Hi), lt_n_Sn | ] ;\n apply (sorted_head (SF_lx (SF_cons h (SF_cons h0 s))) (S i) Hs Hi' 0).\n rewrite -(IH h0 i x (snd h)) //=.\n apply Hs.\n rewrite ?SF_lx_cons /= in Hi |-* ; apply lt_S_n, Hi.\nQed.\n\nDefinition SF_compat_le (s : @SF_seq R) (pr : SF_sorted Rle s) :\n StepFun (head 0 (SF_lx s)) (last 0 (SF_lx s)).\nProof.\n exists (SF_fun s 0) ; exists (seq2Rlist (SF_lx s)) ; exists (seq2Rlist (SF_ly s)).\n by apply ad_SF_compat.\nDefined.\n\nLemma Riemann_sum_compat f (s : SF_seq) (pr : SF_sorted Rle s) :\n Riemann_sum f s = RiemannInt_SF (SF_compat_le (SF_map f s) (SF_map_sort f s _ pr)).\nProof.\n rewrite /RiemannInt_SF ; case: Rle_dec => // [_ | H].\n move: pr ; apply SF_cons_ind with (s := s) => {s} [x0 | h s IH] pr //=.\n rewrite /= -IH /Riemann_sum /SF_map /= => {IH}.\n rewrite Rmult_comm.\n by apply SF_cons_dec with (s := s).\n apply pr.\n contradict H ; rewrite -nth_last -nth0 ; move: (le_refl (ssrnat.predn (size (SF_lx (SF_map f s))))) ;\n elim: {1 3}(ssrnat.predn (size (SF_lx (SF_map f s)))) => /= [| i IH] Hi.\n apply Rle_refl.\n apply Rle_trans with (1 := IH (le_trans _ _ _ (le_n_Sn i) Hi)), (sorted_nth Rle) ;\n intuition.\n by apply SF_map_sort.\nQed.\n\n(** Build StepFun using uniform partition *)\n\nLemma ad_SF_val_fun (f : R -> R) (a b : R) (n : nat) :\n ((a <= b) -> adapted_couple (SF_val_fun f a b n) a b\n (seq2Rlist (unif_part a b n)) (seq2Rlist (SF_val_ly f a b n)))\n /\\ (~(a <= b) -> adapted_couple (SF_val_fun f b a n) a b\n (seq2Rlist (unif_part b a n)) (seq2Rlist (SF_val_ly f b a n))).\nProof.\n wlog : a b / (a <= b) => Hw.\n split ; case: (Rle_dec a b) => // Hab _.\n by apply Hw.\n apply StepFun_P2 ; apply Hw ; by apply Rlt_le, Rnot_le_lt.\n split ; case: (Rle_dec a b) => // {Hw} Hab _.\n\n have : (a = head 0 (SF_lx (SF_val_seq f a b n))) ;\n [rewrite SF_lx_f2 /= ; (try by apply lt_O_Sn) ; field ; apply Rgt_not_eq ; intuition | move => {2}->].\n pattern b at 3 ; replace b with (last 0 (SF_lx (SF_val_seq f a b n))).\n rewrite -(SF_lx_f2 (fun x y => f ((x+y)/2)) (unif_part a b n)) ; try by apply lt_O_Sn.\n rewrite /SF_val_ly -SF_ly_f2.\n unfold SF_val_fun, SF_fun_f2.\n replace (SF_seq_f2 (fun x y : R => f ((x + y) / 2)) (unif_part a b n))\n with (SF_val_seq f a b n) by auto.\n apply (ad_SF_compat _ (SF_val_seq f a b n)).\n by apply SF_sorted_f2, unif_part_sort.\n rewrite SF_lx_f2 ;\n replace (head 0 (unif_part a b n) :: behead (unif_part a b n))\n with (unif_part a b n) by auto.\n rewrite -nth_last size_mkseq nth_mkseq ?S_INR //= ;\n field ; apply Rgt_not_eq, INRp1_pos.\n now rewrite size_mkseq ; apply lt_O_Sn.\nQed.\n\nDefinition sf_SF_val_fun (f : R -> R) (a b : R) (n : nat) : StepFun a b.\nProof.\n case : (Rle_dec a b) => Hab.\n exists (SF_val_fun f a b n) ;\n exists (seq2Rlist (unif_part a b n)) ;\n exists (seq2Rlist (SF_val_ly f a b n)) ; by apply ad_SF_val_fun.\n exists (SF_val_fun f b a n) ;\n exists (seq2Rlist (unif_part b a n)) ;\n exists (seq2Rlist (SF_val_ly f b a n)) ; by apply ad_SF_val_fun.\nDefined.\nLemma SF_val_subdiv (f : R -> R) (a b : R) (n : nat) :\n subdivision (sf_SF_val_fun f a b n) =\n match (Rle_dec a b) with\n | left _ => seq2Rlist (unif_part a b n)\n | right _ => seq2Rlist (unif_part b a n)\n end.\nProof.\n rewrite /sf_SF_val_fun ; case: (Rle_dec a b) => Hab //.\nQed.\nLemma SF_val_subdiv_val (f : R -> R) (a b : R) (n : nat) :\n subdivision_val (sf_SF_val_fun f a b n) =\n match (Rle_dec a b) with\n | left _ => seq2Rlist (SF_val_ly f a b n)\n | right _ => seq2Rlist (SF_val_ly f b a n)\n end.\nProof.\n rewrite /sf_SF_val_fun ; case: (Rle_dec a b) => Hab //.\nQed.\n\nLemma SF_val_fun_rw (f : R -> R) (a b : R) (n : nat) (x : R) (Hx : a <= x <= b) :\n SF_val_fun f a b n x =\n match (unif_part_nat a b n x Hx) with\n | inleft H => f (a + (INR (proj1_sig H) + /2) * (b-a) / (INR n + 1))\n | inright _ => f (a + (INR n + /2) * (b-a) / (INR n + 1))\n end.\nProof.\n have Hab : (a <= b) ; [by apply Rle_trans with (1 := proj1 Hx), Hx | ].\n case: unif_part_nat => {Hx} [ [ i [Hx Hi] ] | Hx] /=.\n(* i < 2^n - 1 *)\n rewrite /SF_val_fun /SF_fun_f2.\n replace (a + (INR i + /2) * (b - a) / (INR n+1))\n with ((nth 0 (unif_part a b n) i + nth 0 (unif_part a b n) (S i)) / 2) ;\n [ | rewrite size_mkseq in Hi ; rewrite ?nth_mkseq ?S_INR ;\n [field ; apply Rgt_not_eq | apply SSR_leq | apply SSR_leq ] ; intuition].\n case: (unif_part a b n) (unif_part_sort a b n Hab) i Hi x Hx => {a b Hab n} [| h s] Hs /= i Hi.\n by apply lt_n_O in Hi.\n case: (s) Hs (i) (lt_S_n _ _ Hi) => {s i Hi} [| h0 s] Hs /= i Hi.\n by apply lt_n_O in Hi.\n elim: (s) h h0 Hs (i) (lt_S_n _ _ Hi) => {s i Hi} [|h1 s IH] h h0 Hs /= i Hi x Hx.\n by apply lt_n_O in Hi.\n case: i Hx Hi => [|i]/= Hx Hi.\n rewrite /SF_fun /=.\n case: Rlt_dec => [Hx0 | _ ].\n contradict Hx0 ; apply Rle_not_lt, Hx.\n case: Rlt_dec => // Hx0 ; contradict Hx0 ; apply Hx.\n rewrite -(IH h0 h1 (proj2 Hs) i (lt_S_n _ _ Hi) x Hx).\n rewrite /SF_fun /= ; case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (1 := proj1 Hs),\n Rle_trans with (2 := proj1 Hx), (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ;\n simpl; intuition.\n case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hx),\n (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ; simpl; intuition.\n(* i = 2^n - 1 *)\n replace (a + (INR n + /2) * (b - a) / (INR n + 1))\n with ((nth 0 (unif_part a b n) (n) + nth 0 (unif_part a b n) (S n)) / 2) ;\n [ | rewrite ?nth_mkseq ?minus_INR ?S_INR /= ;\n [field ; apply Rgt_not_eq |\n apply SSR_leq | apply SSR_leq ] ; intuition].\n suff : (1 < size (unif_part a b n))%nat.\n move: x Hx ; have: (n = size (unif_part a b n) - 2)%nat ;\n [ rewrite size_mkseq ; intuition | ].\n move => {2 4 8 10}->.\n rewrite /SF_val_fun /SF_fun_f2.\n case: (unif_part a b n) (unif_part_sort a b n Hab) => {a b Hab n} [| h s Hs x Hx /= Hi] .\n intros _ x Hx Hi.\n by apply lt_n_O in Hi.\n case: s h Hs Hi x Hx => [| h0 s] h Hs /= Hi.\n by apply lt_irrefl in Hi.\n elim: s h h0 Hs {Hi} => [| h1 s IH] h h0 Hs /= x Hx.\n rewrite /SF_fun /= ; case: Rlt_dec => [Hx0 | _].\n contradict Hx0 ; apply Rle_not_lt, Hx.\n case: Rle_dec => [| Hx0] // ; contradict Hx0 ; apply Hx.\n rewrite -minus_n_O in IH.\n rewrite -(IH h0 h1 (proj2 Hs) x Hx ).\n rewrite /SF_fun /= ; case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (1 := proj1 Hs),\n Rle_trans with (2 := proj1 Hx), (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ;\n simpl; intuition.\n case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hx),\n (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ; simpl; intuition.\n rewrite size_mkseq ; by apply lt_n_S, lt_O_Sn.\nQed.\n\nLemma RInt_val_Reals (f : R -> R) (a b : R) (n : nat) :\n RInt_val f a b n = RiemannInt_SF (sf_SF_val_fun f a b n).\nProof.\nrewrite /RiemannInt_SF SF_val_subdiv SF_val_subdiv_val ;\ncase: Rle_dec => Hab.\n(* a <= b *)\n rewrite /RInt_val /SF_val_ly ; case: (unif_part a b n) => [| h s] /=.\n by [].\n elim: s h => [|h0 s IH] h /=.\n by [].\n rewrite (SF_cons_f2 _ h).\n 2: by apply lt_O_Sn.\n rewrite Riemann_sum_cons /= IH /plus /scal /= /mult /=.\n ring.\n(* ~ a <= Rmult_plus_distr_l (b )*)\n rewrite RInt_val_swap /SF_val_ly /RInt_val.\n simpl opp ; apply f_equal.\n case: (unif_part b a n) => [| h s] /=.\n by [].\n elim: s h => [|h0 s IH] h /=.\n by [].\n rewrite SF_cons_f2.\n 2: by apply lt_O_Sn.\n rewrite Riemann_sum_cons IH /= /plus /scal /= /mult /=.\n ring.\nQed.\n\n(** ** Upper and lower step functions *)\n\nLemma ex_Im_fct (f : R -> R) (a b : R) : a <> b ->\n exists x, (fun y => exists x, y = f x /\\ Rmin a b < x < Rmax a b) x.\nProof.\n exists (f ((a+b)/2)) ; exists ((a+b)/2) ; split.\n by [].\n rewrite /Rmin /Rmax.\n case Rle_dec ; lra.\nQed.\n\nDefinition Sup_fct (f : R -> R) (a b : R) : Rbar :=\n match Req_EM_T a b with\n | right Hab => Lub_Rbar (fun y => exists x, y = f x /\\ Rmin a b < x < Rmax a b)\n | left _ => Finite 0\n end.\nDefinition Inf_fct (f : R -> R) (a b : R) : Rbar :=\n match Req_EM_T a b with\n | right Hab => Glb_Rbar (fun y => exists x, y = f x /\\ Rmin a b < x < Rmax a b)\n | left _ => Finite 0\n end.\n\nLemma Sup_fct_bound (f : R -> R) (a b : R) :\n Sup_fct f a b = Sup_fct f b a.\nProof.\n rewrite /Sup_fct /= ;\n case: Req_EM_T => Hab ;\n case: Req_EM_T => Hba.\n by [].\n by apply sym_equal in Hab.\n by apply sym_equal in Hba.\n apply Lub_Rbar_eqset => x ;\n by rewrite Rmin_comm Rmax_comm.\nQed.\nLemma Inf_fct_bound (f : R -> R) (a b : R) :\n Inf_fct f a b = Inf_fct f b a.\nProof.\n rewrite /Inf_fct /= ;\n case: Req_EM_T => Hab ;\n case: Req_EM_T => Hba.\n by [].\n by apply sym_equal in Hab.\n by apply sym_equal in Hba.\n apply Glb_Rbar_eqset => x ;\n by rewrite Rmin_comm Rmax_comm.\nQed.\n\nLemma Sup_fct_le (f : R -> R) (a b : R) (x : R) :\n (Rmin a b < x < Rmax a b) ->\n Rbar_le (Finite (f x)) (Sup_fct f a b).\nProof.\n move => Hx ; rewrite /Sup_fct.\n case: Req_EM_T => Hab.\n move: (Rlt_trans _ _ _ (proj1 Hx) (proj2 Hx)) => {Hx} ;\n rewrite /Rmin /Rmax ;\n case: Rle_dec (Req_le _ _ Hab) => //= _ _ Hx.\n contradict Hx ; by apply Rle_not_lt, Req_le.\n rewrite /Lub_Rbar ;\n case: ex_lub_Rbar => l lub ;\n apply lub ; exists x ; split ; by [].\nQed.\nLemma Inf_fct_le (f : R -> R) (a b : R) (x : R) : (Rmin a b < x < Rmax a b) ->\n Rbar_le (Inf_fct f a b) (Finite (f x)).\nProof.\n move => Hx ; rewrite /Inf_fct.\n case: Req_EM_T => Hab.\n move: (Rlt_trans _ _ _ (proj1 Hx) (proj2 Hx)) => {Hx} ;\n rewrite /Rmin /Rmax ;\n case: Rle_dec (Req_le _ _ Hab) => //= _ _ Hx.\n contradict Hx ; by apply Rle_not_lt, Req_le.\n rewrite /Glb_Rbar ;\n case: ex_glb_Rbar => l lub ;\n apply lub ; exists x ; split ; by [].\nQed.\n\nLemma Sup_fct_maj (f : R -> R) (a b : R) (M : R) :\n (forall x, Rmin a b < x < Rmax a b -> f x <= M) ->\n is_finite (Sup_fct f a b).\nProof.\n rewrite /Sup_fct ; case: Req_EM_T => Hab Hf.\n by [].\n rewrite /Lub_Rbar ;\n case: ex_lub_Rbar ; case => [l | | ] [lub ub] /=.\n by [].\n case: (ub (Finite M)) => //.\n move => _ [x [-> Hx]].\n by apply Hf.\n case: (lub (f((a+b)/2))) => //.\n exists ((a + b) / 2) ; split.\n by [].\n rewrite /Rmin /Rmax.\n case Rle_dec ; lra.\nQed.\nLemma Inf_fct_min (f : R -> R) (a b : R) (m : R) :\n (forall x, Rmin a b < x < Rmax a b -> m <= f x) ->\n is_finite (Inf_fct f a b).\nProof.\n rewrite /Inf_fct ; case: Req_EM_T => Hab Hf.\n by [].\n rewrite /Glb_Rbar ;\n case: ex_glb_Rbar ; case => [l | | ] [lub ub] /=.\n by [].\n case: (lub (f((a+b)/2))) => //.\n exists ((a + b) / 2) ; split.\n by [].\n rewrite /Rmin /Rmax.\n case Rle_dec ; lra.\n case: (ub (Finite m)) => //.\n move => _ [x [-> Hx]].\n by apply Hf.\nQed.\n\n(** SF_sup and SF_inf *)\n\nDefinition SF_sup_seq (f : R -> R) (a b : R) (n : nat) : SF_seq :=\n SF_seq_f2 (Sup_fct f) (unif_part a b n).\nLemma SF_sup_lx (f : R -> R) (a b : R) (n : nat) :\n SF_lx (SF_sup_seq f a b n) = unif_part a b n.\nProof.\n apply SF_lx_f2.\n now apply lt_O_Sn.\nQed.\nLemma SF_sup_ly (f : R -> R) (a b : R) (n : nat) :\n SF_ly (SF_sup_seq f a b n) = behead (pairmap (Sup_fct f) 0 (unif_part a b n)).\nProof.\n by apply SF_ly_f2.\nQed.\n\nDefinition SF_inf_seq (f : R -> R) (a b : R) (n : nat) : SF_seq :=\n SF_seq_f2 (Inf_fct f) (unif_part a b n).\nLemma SF_inf_lx (f : R -> R) (a b : R) (n : nat) :\n SF_lx (SF_inf_seq f a b n) = unif_part a b n.\nProof.\n by apply SF_lx_f2, lt_O_Sn.\nQed.\nLemma SF_inf_ly (f : R -> R) (a b : R) (n : nat) :\n SF_ly (SF_inf_seq f a b n) = behead (pairmap (Inf_fct f) 0 (unif_part a b n)).\nProof.\n by apply SF_ly_f2.\nQed.\n\nLemma SF_sup_bound (f : R -> R) (a b : R) (n : nat) :\n SF_rev (SF_sup_seq f a b n) = SF_sup_seq f b a n.\nProof.\n rewrite /SF_sup_seq unif_part_bound => //.\n rewrite SF_rev_f2 ?revK //.\n move => x y ; apply Sup_fct_bound.\nQed.\nLemma SF_inf_bound (f : R -> R) (a b : R) (n : nat) :\n SF_rev (SF_inf_seq f a b n) = SF_inf_seq f b a n.\nProof.\n rewrite /SF_inf_seq unif_part_bound => //.\n rewrite SF_rev_f2 ?revK //.\n move => x y ; apply Inf_fct_bound.\nQed.\n\n\nDefinition SF_sup_fun (f : R -> R) (a b : R) (n : nat) (x : R) : Rbar :=\n match (Rle_dec a b) with\n | left _ => SF_fun (SF_sup_seq f a b n) (Finite 0) x\n | right _ => SF_fun (SF_sup_seq f b a n) (Finite 0) x\n end.\nDefinition SF_inf_fun (f : R -> R) (a b : R) (n : nat) (x : R) : Rbar :=\n match (Rle_dec a b) with\n | left _ => SF_fun (SF_inf_seq f a b n) (Finite 0) x\n | right _ => SF_fun (SF_inf_seq f b a n) (Finite 0) x\n end.\n\nLemma SF_sup_fun_bound (f : R -> R) (a b : R) (n : nat) (x : R) :\n SF_sup_fun f a b n x = SF_sup_fun f b a n x.\nProof.\n rewrite /SF_sup_fun ; case: (Rle_dec a b) => Hab ; case : (Rle_dec b a) => Hba //.\n by rewrite (Rle_antisym _ _ Hab Hba).\n by contradict Hba ; apply Rlt_le, Rnot_le_lt.\nQed.\nLemma SF_inf_fun_bound (f : R -> R) (a b : R) (n : nat) (x : R) :\n SF_inf_fun f a b n x = SF_inf_fun f b a n x.\nProof.\n rewrite /SF_inf_fun ; case: (Rle_dec a b) => Hab ; case : (Rle_dec b a) => Hba //.\n by rewrite (Rle_antisym _ _ Hab Hba).\n by contradict Hba ; apply Rlt_le, Rnot_le_lt.\nQed.\n\nLemma SF_sup_fun_rw (f : R -> R) (a b : R) (n : nat) (x : R) (Hx : a <= x <= b) :\n SF_sup_fun f a b n x =\n match (unif_part_nat a b n x Hx) with\n | inleft H => Sup_fct f (nth 0 (unif_part a b n) (proj1_sig H))\n (nth 0 (unif_part a b n) (S (proj1_sig H)))\n | inright _ => Sup_fct f (nth 0 (unif_part a b n) (n))\n (nth 0 (unif_part a b n) (S n))\n end.\nProof.\n have Hab : (a <= b) ; [by apply Rle_trans with (1 := proj1 Hx), Hx | ].\n rewrite /SF_sup_fun /SF_sup_seq ; case: Rle_dec => // _.\n case: unif_part_nat => {Hx} [ [ i [Hx Hi] ] | Hx] ; simpl proj1_sig.\n(* i < n *)\n case: (unif_part a b n) (unif_part_sort a b n Hab) i Hi x Hx => {a b Hab n} [| h s] Hs /= i Hi.\n by apply lt_n_O in Hi.\n case: (s) Hs (i) (lt_S_n _ _ Hi) => {s i Hi} [| h0 s] Hs /= i Hi.\n by apply lt_n_O in Hi.\n elim: (s) h h0 Hs (i) (lt_S_n _ _ Hi) => {s i Hi} [|h1 s IH] h h0 Hs /= i Hi x Hx.\n by apply lt_n_O in Hi.\n case: i Hx Hi => [|i]/= Hx Hi.\n rewrite /SF_fun /=.\n case: Rlt_dec => [Hx0 | _ ].\n contradict Hx0 ; apply Rle_not_lt, Hx.\n case: Rlt_dec => // Hx0 ; contradict Hx0 ; apply Hx.\n rewrite -(IH h0 h1 (proj2 Hs) i (lt_S_n _ _ Hi) x Hx).\n rewrite /SF_fun /= ; case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (1 := proj1 Hs),\n Rle_trans with (2 := proj1 Hx), (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ;\n simpl; intuition.\n case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hx),\n (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ; simpl; intuition.\n(* i = n *)\n move: x Hx.\n suff : (1 < size (unif_part a b n))%nat.\n have: (n = size (unif_part a b n) - 2)%nat ;\n [ rewrite size_mkseq ; intuition | move => {3 5 8 10}->].\n case: (unif_part a b n) (unif_part_sort a b n Hab) => {a b Hab n} [| h s] Hs /= Hi.\n by apply lt_n_O in Hi.\n case: s h Hs Hi => [| h0 s] h Hs /= Hi.\n by apply lt_irrefl in Hi.\n rewrite -minus_n_O ; elim: s h h0 Hs {Hi} => [| h1 s IH] h h0 Hs /= x Hx.\n rewrite /SF_fun /= ; case: Rlt_dec => [Hx0 | _].\n contradict Hx0 ; apply Rle_not_lt, Hx.\n case: Rle_dec => [| Hx0] // ; contradict Hx0 ; apply Hx.\n rewrite -(IH h0 h1 (proj2 Hs) x Hx).\n rewrite /SF_fun /= ; case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (1 := proj1 Hs),\n Rle_trans with (2 := proj1 Hx), (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ;\n simpl; intuition.\n case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hx),\n (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ; simpl; intuition.\n rewrite size_mkseq ; by apply lt_n_S, lt_O_Sn.\nQed.\n\nLemma SF_inf_fun_rw (f : R -> R) (a b : R) (n : nat) (x : R) (Hx : a <= x <= b) :\n SF_inf_fun f a b n x =\n match (unif_part_nat a b n x Hx) with\n | inleft H => Inf_fct f (nth 0 (unif_part a b n) (proj1_sig H))\n (nth 0 (unif_part a b n) (S (proj1_sig H)))\n | inright _ => Inf_fct f (nth 0 (unif_part a b n) (n))\n (nth 0 (unif_part a b n) (S n))\n end.\nProof.\n have Hab : (a <= b) ; [by apply Rle_trans with (1 := proj1 Hx), Hx | ].\n rewrite /SF_inf_fun /SF_inf_seq ; case: Rle_dec => // _.\n case: unif_part_nat => {Hx} [ [ i [Hx Hi] ] | Hx] ; simpl proj1_sig.\n(* i < n *)\n case: (unif_part a b n) (unif_part_sort a b n Hab) i Hi x Hx => {a b Hab n} [| h s] Hs /= i Hi.\n by apply lt_n_O in Hi.\n case: (s) Hs (i) (lt_S_n _ _ Hi) => {s i Hi} [| h0 s] Hs /= i Hi.\n by apply lt_n_O in Hi.\n elim: (s) h h0 Hs (i) (lt_S_n _ _ Hi) => {s i Hi} [|h1 s IH] h h0 Hs /= i Hi x Hx.\n by apply lt_n_O in Hi.\n case: i Hx Hi => [|i]/= Hx Hi.\n rewrite /SF_fun /=.\n case: Rlt_dec => [Hx0 | _ ].\n contradict Hx0 ; apply Rle_not_lt, Hx.\n case: Rlt_dec => // Hx0 ; contradict Hx0 ; apply Hx.\n rewrite -(IH h0 h1 (proj2 Hs) i (lt_S_n _ _ Hi) x Hx).\n rewrite /SF_fun /= ; case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (1 := proj1 Hs),\n Rle_trans with (2 := proj1 Hx), (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ;\n simpl; intuition.\n case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hx),\n (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ; simpl; intuition.\n(* i = n *)\n move: x Hx.\n suff : (1 < size (unif_part a b n))%nat.\n have: (n = size (unif_part a b n) - 2)%nat ;\n [ rewrite size_mkseq ; intuition | move => {3 5 8 10}->].\n case: (unif_part a b n) (unif_part_sort a b n Hab) => {a b Hab n} [| h s] Hs /= Hi.\n by apply lt_n_O in Hi.\n case: s h Hs Hi => [| h0 s] h Hs /= Hi.\n by apply lt_irrefl in Hi.\n rewrite -minus_n_O ; elim: s h h0 Hs {Hi} => [| h1 s IH] h h0 Hs /= x Hx.\n rewrite /SF_fun /= ; case: Rlt_dec => [Hx0 | _].\n contradict Hx0 ; apply Rle_not_lt, Hx.\n case: Rle_dec => [| Hx0] // ; contradict Hx0 ; apply Hx.\n rewrite -(IH h0 h1 (proj2 Hs) x Hx).\n rewrite /SF_fun /= ; case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (1 := proj1 Hs),\n Rle_trans with (2 := proj1 Hx), (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ;\n simpl; intuition.\n case: Rlt_dec => [ Hx0 | _ ] //.\n contradict Hx0 ; apply Rle_not_lt, Rle_trans with (2 := proj1 Hx),\n (sorted_head [:: h0, h1 & s] _ (proj2 Hs)) ; simpl; intuition.\n rewrite size_mkseq ; by apply lt_n_S, lt_O_Sn.\nQed.\n\n(** ** SF_sup_real is a StepFun *)\n\nLemma ad_SF_sup_r (f : R -> R) (a b : R) (n : nat) :\n ((a <= b) -> adapted_couple (fun x => real (SF_sup_fun f a b n x)) a b\n (seq2Rlist (unif_part a b n))\n (seq2Rlist (behead (pairmap (fun x y => real (Sup_fct f x y)) 0 (unif_part a b n)))))\n /\\ (~(a <= b) -> adapted_couple (fun x => real (SF_sup_fun f a b n x)) a b\n (seq2Rlist (unif_part b a n))\n (seq2Rlist (behead (pairmap (fun x y => real (Sup_fct f x y)) 0 (unif_part b a n))))).\nProof.\n wlog : a b / (a <= b) => [Hw|Hab].\n case: (Rle_dec a b) => // Hab ; split => // _.\n by apply (Hw a b).\n apply Rnot_le_lt, Rlt_le in Hab ;\n case : (Hw b a Hab) => {Hw} Hw _ ;\n move: (Hw Hab) => {Hw} Hw ;\n rewrite /adapted_couple in Hw |-* ; rewrite Rmin_comm Rmax_comm ;\n intuition => x Hx ; rewrite SF_sup_fun_bound ; by apply H4.\n split ; case: (Rle_dec a b)=> // _ _.\n rewrite /SF_sup_fun ; case: (Rle_dec a b) => // _.\n have Hs : (SF_sorted Rle (SF_map real (SF_sup_seq f a b n))).\n rewrite /SF_sorted SF_map_lx SF_lx_f2.\n replace (head 0 (unif_part a b n) :: behead (unif_part a b n))\n with (unif_part a b n) by intuition.\n by apply unif_part_sort.\n by apply lt_O_Sn.\n have {2}<-: head 0 (unif_part a b n) = a.\n apply head_unif_part.\n have {3}<-: last 0 (unif_part a b n) = b.\n apply last_unif_part.\n replace (behead\n (pairmap (fun x y : R => real (Sup_fct f x y)) 0 (unif_part a b n)))\n with (SF_ly (SF_map real (SF_sup_seq f a b n))).\n replace (unif_part a b n)\n with (SF_lx (SF_map real (SF_sup_seq f a b n))).\n move: (ad_SF_compat (f ((0+0)/2)) (SF_map real (SF_sup_seq f a b n)) Hs) ;\n rewrite /adapted_couple => Had ; intuition.\n move: (H4 i H3) => {H4} H3' x H4.\n move: (H3' x H4) => {H3'} <-.\n rewrite -(SF_fun_map real).\n\n 2: rewrite SF_map_lx SF_lx_f2 // ; by apply lt_O_Sn.\n 2: rewrite SF_map_ly SF_ly_f2 ;\n by rewrite -behead_map map_pairmap.\n\n move: H3 H4.\n rewrite /SF_sup_seq.\n rewrite !nth_compat size_compat SF_map_lx SF_lx_f2.\n 2: apply lt_O_Sn.\n unfold SF_fun.\n elim: (unif_part a b n) (unif_part_sort a b n Hab) {3}(0) {1}(f ((0 + 0) / 2)) i => [ | x0 l IH] Hl z0 z1 i Hi Hx.\n by apply lt_n_O in Hi.\n simpl in Hi.\n destruct l as [ | x1 l].\n by apply lt_n_O in Hi.\n rewrite SF_cons_f2.\n 2: by apply lt_O_Sn.\n rewrite SF_map_cons.\n case: i Hi Hx => [ | i] Hi /= Hx.\n case: Rlt_dec => Hx0 //.\n contradict Hx0 ; apply Rle_not_lt, Rlt_le, Hx.\n case: (l) => [ | x2 l'] /=.\n case: Rle_dec => // Hx1.\n contradict Hx1 ; by apply Rlt_le, Hx.\n case: Rlt_dec (proj2 Hx) => //.\n case: Rlt_dec => //= Hx0.\n contradict Hx0.\n apply Rle_not_lt, Rlt_le.\n eapply Rle_lt_trans, Hx.\n eapply Rle_trans, sorted_head.\n by apply Hl.\n by apply Hl.\n eapply lt_trans, Hi.\n by apply lt_n_Sn.\n eapply (IH (proj2 Hl) (Sup_fct f x0 x1) (Sup_fct f x0 x1)).\n 2: apply Hx.\n simpl ; by apply lt_S_n.\nQed.\n\nDefinition SF_sup_r (f : R -> R) (a b : R) (n : nat) : StepFun a b.\nProof.\n exists (fun x => real (SF_sup_fun f a b n x)) ;\n case : (Rle_dec a b) => Hab.\n exists (seq2Rlist (unif_part a b n)) ;\n exists (seq2Rlist (behead (pairmap (fun x y => real (Sup_fct f x y)) 0 (unif_part a b n)))) ;\n by apply ad_SF_sup_r.\n exists (seq2Rlist ((unif_part b a n))) ;\n exists (seq2Rlist (behead (pairmap (fun x y => real (Sup_fct f x y)) 0 (unif_part b a n)))) ;\n by apply ad_SF_sup_r.\nDefined.\nLemma SF_sup_subdiv (f : R -> R) (a b : R) (n : nat) :\n subdivision (SF_sup_r f a b n) =\n match (Rle_dec a b) with\n | left _ => seq2Rlist (unif_part a b n)\n | right _ => seq2Rlist (unif_part b a n)\n end.\nProof.\n rewrite /SF_sup_r ; case: (Rle_dec a b) => Hab //.\nQed.\nLemma SF_sup_subdiv_val (f : R -> R) (a b : R) (n : nat) :\n subdivision_val (SF_sup_r f a b n) =\n match (Rle_dec a b) with\n | left _ => (seq2Rlist (behead (pairmap (fun x y => real (Sup_fct f x y)) 0 (unif_part a b n))))\n | right _ => (seq2Rlist (behead (pairmap (fun x y => real (Sup_fct f x y)) 0 (unif_part b a n))))\n end.\nProof.\n rewrite /SF_sup_r ; case: (Rle_dec a b) => Hab //.\nQed.\n\nLemma SF_sup_r_bound (f : R -> R) (a b : R) (n : nat) :\n forall x, SF_sup_r f a b n x = SF_sup_r f b a n x.\nProof.\n move => x /= ; by rewrite SF_sup_fun_bound.\nQed.\n\n(** ** SF_inf_real is a StepFun *)\n\nLemma ad_SF_inf_r (f : R -> R) (a b : R) (n : nat) :\n ((a <= b) -> adapted_couple (fun x => real (SF_inf_fun f a b n x)) a b\n (seq2Rlist (unif_part a b n))\n (seq2Rlist (behead (pairmap (fun x y => real (Inf_fct f x y)) 0 (unif_part a b n)))))\n /\\ (~(a <= b) -> adapted_couple (fun x => real (SF_inf_fun f a b n x)) a b\n (seq2Rlist (unif_part b a n))\n (seq2Rlist (behead (pairmap (fun x y => real (Inf_fct f x y)) 0 (unif_part b a n))))).\nProof.\n wlog : a b / (a <= b) => [Hw|Hab].\n case: (Rle_dec a b) => // Hab ; split => // _.\n by apply (Hw a b).\n apply Rnot_le_lt, Rlt_le in Hab ;\n case : (Hw b a Hab) => {Hw} Hw _ ;\n move: (Hw Hab) => {Hw} Hw ;\n rewrite /adapted_couple in Hw |-* ; rewrite Rmin_comm Rmax_comm ;\n intuition => x Hx ; rewrite SF_inf_fun_bound ; by apply H4.\n split ; case: (Rle_dec a b)=> // _ _.\n rewrite /SF_inf_fun ; case: (Rle_dec a b) => // _.\n have Hs : (SF_sorted Rle (SF_map real (SF_inf_seq f a b n))).\n rewrite /SF_sorted SF_map_lx SF_lx_f2.\n replace (head 0 (unif_part a b n) :: behead (unif_part a b n))\n with (unif_part a b n) by intuition.\n by apply unif_part_sort.\n by apply lt_O_Sn.\n have {2}<-: head 0 (unif_part a b n) = a.\n apply head_unif_part.\n have {3}<-: last 0 (unif_part a b n) = b.\n apply last_unif_part.\n replace (behead\n (pairmap (fun x y : R => real (Inf_fct f x y)) 0 (unif_part a b n)))\n with (SF_ly (SF_map real (SF_inf_seq f a b n))).\n replace (unif_part a b n)\n with (SF_lx (SF_map real (SF_inf_seq f a b n))).\n move: (ad_SF_compat (f ((0+0)/2)) (SF_map real (SF_inf_seq f a b n)) Hs) ;\n rewrite /adapted_couple => Had ; intuition.\n move: (H4 i H3) => {H4} H3' x H4.\n move: (H3' x H4) => {H3'} <-.\n rewrite -(SF_fun_map real).\n\n 2: rewrite SF_map_lx SF_lx_f2 // ; by apply lt_O_Sn.\n 2: rewrite SF_map_ly SF_ly_f2 ;\n by rewrite -behead_map map_pairmap.\n\n move: H3 H4.\n rewrite /SF_inf_seq.\n rewrite !nth_compat size_compat SF_map_lx SF_lx_f2.\n 2: apply lt_O_Sn.\n unfold SF_fun.\n elim: (unif_part a b n) (unif_part_sort a b n Hab) {3}(0) {1}(f ((0 + 0) / 2)) i => [ | x0 l IH] Hl z0 z1 i Hi Hx.\n by apply lt_n_O in Hi.\n simpl in Hi.\n destruct l as [ | x1 l].\n by apply lt_n_O in Hi.\n rewrite SF_cons_f2.\n 2: by apply lt_O_Sn.\n rewrite SF_map_cons.\n case: i Hi Hx => [ | i] Hi /= Hx.\n case: Rlt_dec => Hx0 //.\n contradict Hx0 ; apply Rle_not_lt, Rlt_le, Hx.\n case: (l) => [ | x2 l'] /=.\n case: Rle_dec => // Hx1.\n contradict Hx1 ; by apply Rlt_le, Hx.\n case: Rlt_dec (proj2 Hx) => //.\n case: Rlt_dec => //= Hx0.\n contradict Hx0.\n apply Rle_not_lt, Rlt_le.\n eapply Rle_lt_trans, Hx.\n eapply Rle_trans, sorted_head.\n by apply Hl.\n by apply Hl.\n eapply lt_trans, Hi.\n by apply lt_n_Sn.\n eapply (IH (proj2 Hl) (Inf_fct f x0 x1) (Inf_fct f x0 x1)).\n 2: apply Hx.\n simpl ; by apply lt_S_n.\nQed.\n\nDefinition SF_inf_r (f : R -> R) (a b : R) (n : nat) : StepFun a b.\nProof.\n exists (fun x => real (SF_inf_fun f a b n x)) ;\n case : (Rle_dec a b) => Hab.\n exists (seq2Rlist (unif_part a b n)) ;\n exists (seq2Rlist (behead (pairmap (fun x y => real (Inf_fct f x y)) 0 (unif_part a b n)))) ;\n by apply ad_SF_inf_r.\n exists (seq2Rlist ((unif_part b a n))) ;\n exists (seq2Rlist (behead (pairmap (fun x y => real (Inf_fct f x y)) 0 (unif_part b a n)))) ;\n by apply ad_SF_inf_r.\nDefined.\nLemma SF_inf_subdiv (f : R -> R) (a b : R) (n : nat) :\n subdivision (SF_inf_r f a b n) =\n match (Rle_dec a b) with\n | left _ => seq2Rlist (unif_part a b n)\n | right _ => seq2Rlist (unif_part b a n)\n end.\nProof.\n rewrite /SF_inf_r ; case: (Rle_dec a b) => Hab //.\nQed.\nLemma SF_inf_subdiv_val (f : R -> R) (a b : R) (n : nat) :\n subdivision_val (SF_inf_r f a b n) =\n match (Rle_dec a b) with\n | left _ => (seq2Rlist (behead (pairmap (fun x y => real (Inf_fct f x y)) 0 (unif_part a b n))))\n | right _ => (seq2Rlist (behead (pairmap (fun x y => real (Inf_fct f x y)) 0 (unif_part b a n))))\n end.\nProof.\n rewrite /SF_inf_r ; case: (Rle_dec a b) => Hab //.\nQed.\n\nLemma SF_inf_r_bound (f : R -> R) (a b : R) (n : nat) :\n forall x, SF_inf_r f a b n x = SF_inf_r f b a n x.\nProof.\n move => x /= ; by rewrite SF_inf_fun_bound.\nQed.\n", "meta": {"author": "MSoegtropIMC", "repo": "coquelicot", "sha": "1ec80657ce992fc5aa660dca86d423671f02e33c", "save_path": "github-repos/coq/MSoegtropIMC-coquelicot", "path": "github-repos/coq/MSoegtropIMC-coquelicot/coquelicot-1ec80657ce992fc5aa660dca86d423671f02e33c/theories/SF_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.11757213663746784, "lm_q1q2_score": 0.05147584426094922}} {"text": "(* It is forbidden to erase a variable (or a local def) that is used in\n the current goal. *)\nSection S.\nLet a := 0.\nDefinition b := a.\nGoal b = b.\nFail clear a.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/failure/coqbugs0266.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.12252321412020203, "lm_q1q2_score": 0.05130008929898939}} {"text": "(** This file contains basic tactics and useful lemmas/types *)\nSet Implicit Arguments.\nRequire Export Morphisms.\n\n(** Usable version of iter: *)\n(** Taken from: http://www.ps.uni-saarland.de/courses/sem-ws17/confluence.v *)\n\nSection Iter.\n Variables (X: Type) (f: X -> X).\n\n Fixpoint it n x : X :=\n match n with\n | 0 => x\n | S n'=> f (it n' x)\n end.\n\n Fact it_shift n x :\n f (it n x) = it n (f x).\n Proof.\n induction n; cbn; congruence.\n Qed.\n\nEnd Iter.\n\nNotation \"{ x & P }\" := (sigT (fun x => P)) : type_scope.\n\n\n(** _Type inhabitace_ – Conversion from Type to Prop due to restriction\n on elimination in Prop. Having typing judgements in Type we sometimes \n need to return a wrapped version of them to match on propositions. \n See progress. *)\n\nInductive inhab (X: Type) :Prop :=\n | inhabited: X -> inhab X.\n\n\n(** Pretty version of inversion *)\nLtac inv H := inversion H; subst; clear H.\n\n\nLtac invp R :=\n match goal with\n | [ H: R _ |- _] => inv H\n | [ H: R _ _ |- _] => inv H\n | [ H: R _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ _ _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ _ _ _ _ _ |- _] => inv H\n | [ H: R _ _ _ _ _ _ _ _ _ _|- _] => inv H\n end.\n\nLtac inject :=\n repeat match goal with\n | [H: ?C _ = ?C _ |- _] => injection H as ->\n | [H: ?C _ _ = ?C _ _ |- _] => injection H as -> ->\n | [H: ?C _ _ _ = ?C _ _ _ |- _] => injection H as -> -> ->\n | [H: ?C _ _ _ _ = ?C _ _ _ _ |- _] => injection H as -> -> -> ->\n | [H: ?C _ _ _ _ _ = ?C _ _ _ _ _ |- _] => injection H as -> -> -> -> ->\n end.\n\n\n\n(** Automatically destruct existential quantifier *)\nLtac exdestruct :=\n match goal with\n | [ H: ex ?P |- _] => destruct H\n | [ H: ex2 ?P ?Q |- _] => destruct H\n | [ H: sig ?P |- _] => destruct H\n | [ H: sigT ?P |- _] => destruct H\n end.\n\nLtac exintuition := intuition; repeat exdestruct; intuition.\n\n\n(** Reduction tactic for beta reduction step *)\nLtac reduce := econstructor 2; [ solve [eauto] | cbn ].\n\n(** _Modus Ponens_ - applies to implications,\n will generate a subgoal for the premise of H and then specialize H with the result *)\nLtac mp H :=\nlet x := fresh \"H\" in\n match type of H with\n | ?Q -> ?P => assert P as x; [apply H | clear H; assert P as H by exact x; clear x]\n end.\n", "meta": {"author": "euisuny", "repo": "logrel-iris", "sha": "37ad8f953c97cfa8c7eefa4a159dfbab6db6d17c", "save_path": "github-repos/coq/euisuny-logrel-iris", "path": "github-repos/coq/euisuny-logrel-iris/logrel-iris-37ad8f953c97cfa8c7eefa4a159dfbab6db6d17c/src/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.05100238503791418}} {"text": "(** * Preliminaries *)\n\n(** This file contains definitions and proofs from the Base Library for the ICL lecture. \n - Version: 3 October 2016\n - Author: Gert Smolka, Saarland University\n - Acknowlegments: Sigurd Schneider, Dominik Kirst, Yannick Forster\n *)\n\nRequire Export Bool Omega List Setoid Morphisms Tactics.\n\nGlobal Set Implicit Arguments. \nGlobal Unset Strict Implicit.\nGlobal Unset Printing Records.\nGlobal Unset Printing Implicit Defensive.\nGlobal Set Regular Subst Tactic.\n\n(** ** Lists *)\nExport ListNotations.\nNotation \"x 'el' A\" := (In x A) (at level 70).\nNotation \"A <<= B\" := (incl A B) (at level 70).\nNotation \"| A |\" := (length A) (at level 65).\n\nHint Extern 4 => \nmatch goal with\n|[ H: ?x el nil |- _ ] => destruct H\nend.\n\nLemma incl_nil X (A : list X) :\n nil <<= A.\nProof. intros x []. Qed.\n\nHint Rewrite <- app_assoc : list.\nHint Rewrite rev_app_distr map_app prod_length : list.\nHint Resolve in_eq in_nil in_cons in_or_app.\nHint Resolve incl_refl incl_tl incl_cons incl_appl incl_appr incl_app incl_nil.\n\n(** ** Tactics *)\nLtac inv H := inversion H; subst; try clear H.\n\nTactic Notation \"destruct\" \"_\":=\n match goal with\n | [ |- context[match ?X with _ => _ end] ] => destruct X\n | [ H : context[match ?X with _ => _ end] |- _ ] => destruct X \n end.\n\nHint Extern 4 => \nmatch goal with\n|[ H: False |- _ ] => destruct H\n|[ H: true=false |- _ ] => discriminate H\n|[ H: false=true |- _ ] => discriminate H\nend.\n\nLemma size_induction X (f : X -> nat) (p : X -> Prop) :\n (forall x, (forall y, f y < f x -> p y) -> p x) -> \n forall x, p x.\n\nProof. \n intros IH x. apply IH. \n assert (G: forall n y, f y < n -> p y).\n { intros n. induction n.\n - intros y B. exfalso. omega.\n - intros y B. apply IH. intros z C. apply IHn. omega. }\n apply G.\nQed.\n\nDefinition Injective {A B} (f : A->B) :=\n forall x y, f x = f y -> x = y.\n\nSection fix_X.\n Variable X:Type.\n Implicit Types (A B: list X) (a b c: X). \n\n Lemma last_app_eq A B a b :\n A++[a] = B++[b] -> A = B /\\ a = b.\n Proof.\n intros H%(f_equal (@rev X)). rewrite !rev_app_distr in H. split.\n - inv H. apply (f_equal (@rev X)) in H2. now rewrite !rev_involutive in H2.\n - now inv H.\n Qed.\n \n Lemma rev_eq A B:\n List.rev A = List.rev B <-> A = B.\n Proof.\n split.\n - intros H%(f_equal (@rev X)). now rewrite !rev_involutive in H.\n - now intros <-.\n Qed.\n\n Lemma rev_nil A:\n rev A = [] -> A = [].\n Proof.\n destruct A. auto. now intros H%symmetry%app_cons_not_nil.\n Qed.\n\n Lemma map_inj (Y:Type) A B (f: X -> Y) :\n Injective f -> map f A = map f B <-> A = B.\n Proof.\n intros inj. split.\n - revert B. induction A; intros B H; cbn in *; destruct B; auto; cbn in H; inv H.\n rewrite (inj a x H1). specialize (IHA B H2). now subst.\n - now intros <-.\n Qed.\nEnd fix_X.\n\n\nLemma app_incl_l X (A B C : list X) :\n A ++ B <<= C -> A <<= C.\nProof.\n firstorder eauto.\nQed.\n\nLemma app_incl_R X (A B C : list X) :\n A ++ B <<= C -> B <<= C.\nProof.\n firstorder eauto.\nQed.\n\nLemma cons_incl X (a : X) (A B : list X) : a :: A <<= B -> A <<= B.\nProof.\n intros ? ? ?. eapply H. firstorder.\nQed.\n\nLemma incl_sing X (a : X) A : a el A -> [a] <<= A.\nProof.\n now intros ? ? [-> | [] ].\nQed.\n\nHint Resolve app_incl_l app_incl_R cons_incl incl_sing.\n\n\nHint Extern 4 (_ el map _ _) => eapply in_map_iff.\nHint Extern 4 (_ el filter _ _) => eapply filter_In.\n\nFixpoint count (l : list nat) (n : nat) :=\n match l with\n | [] => 0\n | m :: l => if Nat.eqb n m then S (count l n) else count l n\n end.\n\nLemma countSplit (A B: list nat) (x: nat) : count A x + count B x = count (A ++ B) x. \nProof. \n induction A. \n - reflexivity. \n - cbn. destruct (x =? a).\n + cbn. f_equal; exact IHA. \n + exact IHA. \nQed.\n\nLemma notInZero (x: nat) A :\n not (x el A) <-> count A x = 0.\nProof.\n split; induction A.\n - reflexivity.\n - intros H. cbn in *. destruct (Nat.eqb_spec x a).\n + exfalso. apply H. left. congruence.\n + apply IHA. intros F. apply H. now right.\n - tauto.\n - cbn. destruct (Nat.eqb_spec x a).\n + subst a. omega.\n + intros H [E | E].\n * now symmetry in E.\n * tauto.\nQed.\n\nFixpoint pos (X : Type) (d : forall x y : X, {x = y} + {x <> y}) (x : X) l : option nat :=\n match l with\n | nil => None\n | y :: l => if d x y then Some 0 else match pos d x l with Some f => Some (S f) | None => None end\n end.\n\nLemma el_pos X d (x : X) l : x el l -> exists n, pos d x l = Some n.\nProof.\n induction l; firstorder subst.\n - exists 0. cbn. destruct (d x x); congruence.\n - destruct (d x a); subst.\n + exists 0. cbn. destruct (d a a); congruence.\n + exists (S x0). cbn. destruct (d x a); try congruence. now rewrite H0.\nQed.\n\nLemma pos_nth X d (x : X) l n def : pos d x l = Some n -> nth n l def = x.\nProof.\n revert n; induction l; cbn; intros; try congruence.\n destruct (d x a); try destruct (pos d x l) eqn:E; inv H; eauto.\nQed.\n\nLemma pos_length X d (x : X) l n : pos d x l = Some n -> n < | l |.\nProof.\n revert n; induction l; cbn; intros; try congruence.\n destruct (d x a).\n - inv H. omega.\n - destruct (pos d x l) eqn:E; inv H; try omega. specialize (IHl _ eq_refl). omega.\nQed.\n\n\nFixpoint omap X Y (f : X -> option Y) l :=\n match l with\n | nil => nil\n | x :: l => match f x with Some y => y :: omap f l | None => omap f l end\n end.\n\nLemma in_omap_iff X Y (f : X -> option Y) l y : y el omap f l <-> exists x, x el l /\\ f x = Some y.\nProof.\n induction l; cbn.\n - firstorder.\n - destruct (f a) eqn:E; firstorder (subst; firstorder congruence).\nQed.\n", "meta": {"author": "uds-psl", "repo": "ill-undecidability", "sha": "0bfda1a33cb3411c8f2c0263e15d5c85c090721d", "save_path": "github-repos/coq/uds-psl-ill-undecidability", "path": "github-repos/coq/uds-psl-ill-undecidability/ill-undecidability-0bfda1a33cb3411c8f2c0263e15d5c85c090721d/coq/Prelim/Prelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.10669059252545564, "lm_q1q2_score": 0.05001554972513359}}