(* *****************************************************************)
(*                                                                 *)
(*               Verified polyhedral AST generation                *)
(*                                                                 *)
(*                 Nathanaël Courant, Inria Paris                  *)
(*                                                                 *)
(*  Copyright Inria. All rights reserved. This file is distributed *)
(*  under the terms of the GNU Lesser General Public License as    *)
(*  published by the Free Software Foundation, either version 2.1  *)
(*  of the License, or (at your option) any later version.         *)
(*                                                                 *)
(* *****************************************************************)

Require Import ZArith.
Require Import List.
Require Import Bool.
Require Import Psatz.

Require Import Instr.
Require Import Misc.
Require Import Semantics.

Open Scope Z_scope.
Open Scope list_scope.

(** * The semantics of the Loop language *)

Inductive expr :=
| Constant : Z -> expr
| Sum : expr -> expr -> expr
| Mult : Z -> expr -> expr
| Div : expr -> Z -> expr
| Mod : expr -> Z -> expr
| Var : nat -> expr
| Max : expr -> expr -> expr
| Min : expr -> expr -> expr.

Fixpoint eval_expr (env : list Z) (e : expr) :=
  match e with
  | Constant c => c
  | Sum e1 e2 => eval_expr env e1 + eval_expr env e2
  | Mult k e => k * eval_expr env e
  | Div e k => eval_expr env e / k
  | Mod e k => (eval_expr env e) mod k
  | Var n => nth n env 0
  | Max e1 e2 => Z.max (eval_expr env e1) (eval_expr env e2)
  | Min e1 e2 => Z.min (eval_expr env e1) (eval_expr env e2)
  end.

Ltac destruct_match :=
  match goal with
  | [ |- context[match ?X with _ => _ end] ] => destruct X
  end.

Definition make_sum e1 e2 :=
  match e1, e2 with
  | Constant n, Constant m => Constant (n + m)
  | Constant 0, e2 => e2
  | e1, Constant 0 => e1
  | e1, e2 => Sum e1 e2
  end.

Lemma make_sum_correct :
  forall env e1 e2, eval_expr env (make_sum e1 e2) = eval_expr env e1 + eval_expr env e2.
Proof.
  intros env e1 e2; unfold make_sum; repeat destruct_match; simpl; try reflexivity; lia.
Qed.

Definition make_mult n e :=
  match n, e with
  | _, Constant m => Constant (n * m)
  | 0, _ => Constant 0
  | 1, e => e
  | n, e => Mult n e
  end.

Lemma make_mult_correct :
  forall env n e, eval_expr env (make_mult n e) = n * eval_expr env e.
Proof.
  intros env n e; unfold make_mult; repeat (destruct_match; simpl); try reflexivity; lia.
Qed.

Definition make_div e n :=
  match e, n with
  | Constant m, _ => Constant (m / n)
  | e, 1 => e
  | e, -1 => make_mult (-1) e
  | e, n => Div e n
  end.

Lemma make_div_correct :
  forall env e n, eval_expr env (make_div e n) = eval_expr env e / n.
Proof.
  intros env e n; unfold make_div; repeat (destruct_match; simpl); try reflexivity; rewrite ?Z.div_1_r; try reflexivity;
    rewrite <- Z.div_opp_opp, Z.div_1_r by lia; reflexivity.
Qed.

Definition make_mod e n :=
  match e, n with
  | Constant m, _ => Constant (m mod n)
  | e, 1 => Constant 0
  | e, (-1) => Constant 0
  | e, n => Mod e n
  end.

Lemma make_mod_correct :
  forall env e n, eval_expr env (make_mod e n) = eval_expr env e mod n.
Proof.
  intros env e n; unfold make_mod; repeat (destruct_match; simpl); try reflexivity; rewrite ?Z.mod_1_r; try reflexivity;
    replace (-1) with (-(1)) by reflexivity; rewrite Z.mod_opp_r_z; rewrite ?Z.mod_1_r; lia.
Qed.

Definition make_max e1 e2 :=
  match e1, e2 with
  | Constant m, Constant n => Constant (Z.max m n)
  | e1, e2 => Max e1 e2
  end.

Lemma make_max_correct :
  forall env e1 e2, eval_expr env (make_max e1 e2) = Z.max (eval_expr env e1) (eval_expr env e2).
Proof.
  intros env e1 e2; unfold make_max; repeat (destruct_match; simpl); reflexivity.
Qed.

Definition make_min e1 e2 :=
  match e1, e2 with
  | Constant m, Constant n => Constant (Z.min m n)
  | e1, e2 => Min e1 e2
  end.

Lemma make_min_correct :
  forall env e1 e2, eval_expr env (make_min e1 e2) = Z.min (eval_expr env e1) (eval_expr env e2).
Proof.
  intros env e1 e2; unfold make_min; repeat (destruct_match; simpl); reflexivity.
Qed.

Inductive test :=
| LE : expr -> expr -> test
| EQ : expr -> expr -> test
| And : test -> test -> test
| Or : test -> test -> test
| Not : test -> test
| TConstantTest : bool -> test.

Fixpoint eval_test (env : list Z) (t : test) :=
  match t with
  | LE e1 e2 => eval_expr env e1 <=? eval_expr env e2
  | EQ e1 e2 => eval_expr env e1 =? eval_expr env e2
  | And t1 t2 => eval_test env t1 && eval_test env t2
  | Or t1 t2 => eval_test env t1 || eval_test env t2
  | Not t => negb (eval_test env t)
  | TConstantTest b => b
  end.

Definition make_le e1 e2 :=
  match e1, e2 with
  | Constant n, Constant m => TConstantTest (n <=? m)
  | e1, e2 => LE e1 e2
  end.

Lemma make_le_correct :
  forall env e1 e2, eval_test env (make_le e1 e2) = (eval_expr env e1 <=? eval_expr env e2).
Proof.
  intros env e1 e2; unfold make_le; repeat (destruct_match; simpl); reflexivity.
Qed.

Definition make_eq e1 e2 :=
  match e1, e2 with
  | Constant n, Constant m => TConstantTest (n =? m)
  | e1, e2 => EQ e1 e2
  end.

Lemma make_eq_correct :
  forall env e1 e2, eval_test env (make_eq e1 e2) = (eval_expr env e1 =? eval_expr env e2).
Proof.
  intros env e1 e2; unfold make_eq; repeat (destruct_match; simpl); reflexivity.
Qed.

Definition make_and t1 t2 :=
  match t1, t2 with
  | TConstantTest true, t | t, TConstantTest true => t
  | TConstantTest false, _ | _, TConstantTest false => TConstantTest false
  | t1, t2 => And t1 t2
  end.

Lemma make_and_correct :
  forall env t1 t2, eval_test env (make_and t1 t2) = eval_test env t1 && eval_test env t2.
Proof.
  intros env t1 t2; unfold make_and; repeat (destruct_match; simpl); try reflexivity;
    repeat (match goal with [ |- context[?X && ?Y]] => destruct X; simpl end); auto.
Qed.

Definition make_or t1 t2 :=
  match t1, t2 with
  | TConstantTest false, t | t, TConstantTest false => t
  | TConstantTest true, _ | _, TConstantTest true => TConstantTest true
  | t1, t2 => Or t1 t2
  end.

Lemma make_or_correct :
  forall env t1 t2, eval_test env (make_or t1 t2) = eval_test env t1 || eval_test env t2.
Proof.
  intros env t1 t2; unfold make_or; repeat (destruct_match; simpl); try reflexivity;
    repeat (match goal with [ |- context[?X || ?Y]] => destruct X; simpl end); auto.
Qed.

Definition make_not t :=
  match t with
  | TConstantTest b => TConstantTest (negb b)
  | t => Not t
  end.

Lemma make_not_correct :
  forall env t, eval_test env (make_not t) = negb (eval_test env t).
Proof.
  intros env t; unfold make_not; repeat (destruct_match; simpl); reflexivity.
Qed.

Fixpoint and_all l :=
  match l with
  | nil => TConstantTest true
  | x :: l => make_and x (and_all l)
  end.

Theorem and_all_correct :
  forall l env, eval_test env (and_all l) = forallb (eval_test env) l.
Proof.
  induction l; simpl in *; [auto|].
  intros; rewrite make_and_correct, IHl; auto.
Qed.

Inductive stmt :=
| Loop : expr -> expr -> stmt -> stmt
| Instr : instr -> list expr -> stmt
| Seq : list stmt -> stmt
| Guard : test -> stmt -> stmt.

Inductive loop_semantics : stmt -> list Z -> mem -> mem -> Prop :=
| LInstr : forall i es env mem1 mem2,
    instr_semantics i (map (eval_expr env) es) mem1 mem2 ->
    loop_semantics (Instr i es) env mem1 mem2
| LSeqEmpty : forall env mem, loop_semantics (Seq nil) env mem mem
| LSeq : forall env st sts mem1 mem2 mem3,
    loop_semantics st env mem1 mem2 ->
    loop_semantics (Seq sts) env mem2 mem3 ->
    loop_semantics (Seq (st :: sts)) env mem1 mem3
| LGuardTrue : forall env t st mem1 mem2,
    loop_semantics st env mem1 mem2 ->
    eval_test env t = true ->
    loop_semantics (Guard t st) env mem1 mem2
| LGuardFalse : forall env t st mem,
    eval_test env t = false -> loop_semantics (Guard t st) env mem mem
| LLoop : forall env lb ub st mem1 mem2,
    iter_semantics (fun x => loop_semantics st (x :: env)) (Zrange (eval_expr env lb) (eval_expr env ub)) mem1 mem2 ->
    loop_semantics (Loop lb ub st) env mem1 mem2.

Definition make_guard test inner :=
  match test with
  | TConstantTest true => inner
  | TConstantTest false => Seq nil
  | test => Guard test inner
  end.

Lemma make_guard_correct :
  forall test inner env mem1 mem2,
    loop_semantics (make_guard test inner) env mem1 mem2 <->
    (if eval_test env test then loop_semantics inner env mem1 mem2 else mem1 = mem2).
Proof.
  intros test inner env mem1 mem2.
  split.
  - destruct (eval_test env test) eqn:Htest.
    + unfold make_guard; intros H; destruct test; simpl;
        try (inversion_clear H; congruence).
      simpl in *. rewrite Htest in H. auto.
    + unfold make_guard; intros H; destruct test; simpl;
        try (inversion_clear H; congruence).
      simpl in *. rewrite Htest in H. inversion_clear H; auto.
  - destruct (eval_test env test) eqn:Htest.
    + unfold make_guard; intros H; destruct test; simpl;
        try (apply LGuardTrue; auto).
      simpl in Htest; rewrite Htest; auto.
    + unfold make_guard; intros H; destruct test; simpl; rewrite H;
        try (apply LGuardFalse; auto).
      simpl in Htest; rewrite Htest; auto.
      constructor; auto.
Qed.

Definition make_let value inner :=
  Loop value (Sum value (Constant 1)) inner.

Lemma make_let_correct :
  forall value inner env mem1 mem2,
    loop_semantics (make_let value inner) env mem1 mem2 <-> loop_semantics inner (eval_expr env value :: env) mem1 mem2.
Proof.
  intros value inner env mem1 mem2.
  split.
  - unfold make_let. intros H; inversion_clear H.
    simpl in H0. rewrite Zrange_single in H0.
    inversion_clear H0. inversion H1. congruence.
  - intros H. unfold make_let. constructor.
    rewrite Zrange_single.
    econstructor; [|econstructor]. auto.
Qed.


From Test Require Import tactic.

Section FOFProblem.

Variable Universe : Set.
Variable UniverseElement : Universe.

Variable tS_ : Universe -> Universe -> Universe -> Universe -> Prop.
Variable par_ : Universe -> Universe -> Universe -> Universe -> Prop.
Variable out_ : Universe -> Universe -> Universe -> Prop.
Variable oS_ : Universe -> Universe -> Universe -> Universe -> Prop.
Variable congA_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.
Variable cong_ : Universe -> Universe -> Universe -> Universe -> Prop.
Variable col_ : Universe -> Universe -> Universe -> Prop.
Variable betS_ : Universe -> Universe -> Universe -> Prop.

Variable lemma_samesidesymmetric_1 : (forall A B P Q : Universe, (oS_ P Q A B -> (oS_ Q P A B /\ (oS_ P Q B A /\ oS_ Q P B A)))).
Variable defequalangles_2 : (forall A B C Ca Cb Cc : Universe, (exists U V Su Sv : Universe, (congA_ A B C Ca Cb Cc -> (out_ B A U /\ (out_ B C V /\ (out_ Cb Ca Su /\ (out_ Cb Cc Sv /\ (cong_ B U Cb Su /\ (cong_ B V Cb Sv /\ (cong_ U V Su Sv /\ ~(col_ A B C))))))))))).
Variable defequalangles2_3 : (forall A B C Ca Cb Cc U V Su Sv : Universe, ((out_ B A U /\ (out_ B C V /\ (out_ Cb Ca Su /\ (out_ Cb Cc Sv /\ (cong_ B U Cb Su /\ (cong_ B V Cb Sv /\ (cong_ U V Su Sv /\ ~(col_ A B C)))))))) -> congA_ A B C Ca Cb Cc)).
Variable defcollinear_4 : (forall A B C : Universe, (col_ A B C -> (A = B \/ (A = C \/ (B = C \/ (betS_ B A C \/ (betS_ A B C \/ betS_ A C B))))))).
Variable defcollinear2a_5 : (forall A B C : Universe, (A = B -> col_ A B C)).
Variable defcollinear2b_6 : (forall A B C : Universe, (A = C -> col_ A B C)).
Variable defcollinear2c_7 : (forall A B C : Universe, (B = C -> col_ A B C)).
Variable defcollinear2d_8 : (forall A B C : Universe, (betS_ B A C -> col_ A B C)).
Variable defcollinear2e_9 : (forall A B C : Universe, (betS_ A B C -> col_ A B C)).
Variable defcollinear2f_10 : (forall A B C : Universe, (betS_ A C B -> col_ A B C)).
Variable lemma_collinearorder_11 : (forall A B C : Universe, (col_ A B C -> (col_ B A C /\ (col_ B C A /\ (col_ C A B /\ (col_ A C B /\ col_ C B A)))))).
Variable lemma_betweennotequal_12 : (forall A B C : Universe, (betS_ A B C -> (B <> C /\ (A <> B /\ A <> C)))).
Variable lemma_inequalitysymmetric_13 : (forall A B : Universe, (A <> B -> B <> A)).
Variable lemma_collinear4_14 : (forall A B C D : Universe, ((col_ A B C /\ (col_ A B D /\ A <> B)) -> col_ B C D)).
Variable defoppositeside_15 : (forall P A B Q : Universe, (exists X : Universe, (tS_ P A B Q -> (betS_ P X Q /\ (col_ A B X /\ ~(col_ A B P)))))).
Variable defoppositeside2_16 : (forall P A B Q X : Universe, ((betS_ P X Q /\ (col_ A B X /\ ~(col_ A B P))) -> tS_ P A B Q)).
Variable lemma_oppositesidesymmetric_17 : (forall A B P Q : Universe, (tS_ P A B Q -> tS_ Q A B P)).
Variable axiom_betweennesssymmetry_18 : (forall A B C : Universe, (betS_ A B C -> betS_ C B A)).
Variable proposition_15_19 : (forall A B C D E : Universe, ((betS_ A E B /\ (betS_ C E D /\ ~(col_ A E C))) -> (congA_ A E C D E B /\ congA_ C E B A E D))).
Variable lemma_equalanglessymmetric_20 : (forall A B C Xa Xb Xc : Universe, (congA_ A B C Xa Xb Xc -> congA_ Xa Xb Xc A B C)).
Variable lemma_equalanglestransitive_21 : (forall A B C D E F P Q R : Universe, ((congA_ A B C D E F /\ congA_ D E F P Q R) -> congA_ A B C P Q R)).
Variable lemma_planeseparation_22 : (forall A B C D E : Universe, ((oS_ C D A B /\ tS_ D A B E) -> tS_ C A B E)).
Variable proposition_27_23 : (forall A B C D E F : Universe, ((betS_ A E B /\ (betS_ C F D /\ (congA_ A E F E F D /\ tS_ A E F D))) -> par_ A B C D)).

Theorem proposition_28A_24 : (forall A B C D E G H : Universe, ((betS_ A G B /\ (betS_ C H D /\ (betS_ E G H /\ (congA_ E G B G H D /\ oS_ B D G H)))) -> par_ A B C D)).
Proof.
  time tac.
Qed.

End FOFProblem.


Require Import Program.
Require Import List.

Lemma map_compose : forall A B C (f : B -> C) (g : A -> B) list,
  map (f ∘ g) list = map f (map g list).
Proof.
  induction list.
  - reflexivity.
  - simpl. rewrite IHlist. unfold compose. reflexivity.
Qed.


From NP Require Export Defs Transitions.

Inductive Context :=
| CTrivial : Context
| CPrefix : action -> Context -> Context
| CChoiceL : Context -> CCS -> Context
| CChoiceR : CCS -> Context -> Context
| CParL : Context -> CCS -> Context
| CParR : CCS -> Context -> Context
| CRestrict : Context -> actionFilter -> Context.

Fixpoint emplaceC (c:Context) (e:CCS) := match c with CTrivial => e
                                                    | CPrefix a c => Prefix a (emplaceC c e)
                                                    | CChoiceL c r => Choice (emplaceC c e) r
                                                    | CChoiceR l c => Choice l (emplaceC c e)
                                                    | CParL c r => Par (emplaceC c e) r
                                                    | CParR l c => Par l (emplaceC c e)
                                                    | CRestrict c H => Restrict (emplaceC c e) H end.

Definition congruence (R : CCS -> CCS -> Type) := forall (k l : CCS) (c:Context), R k l -> R (emplaceC c k) (emplaceC c l).

Fixpoint emplaceR (c:Context) (e:Context) := match c with CTrivial => e
                                                        | CPrefix a c => CPrefix a (emplaceR c e)
                                                        | CChoiceL c r => CChoiceL (emplaceR c e) r
                                                        | CChoiceR l c => CChoiceR l (emplaceR c e)
                                                        | CParL c r => CParL (emplaceR c e) r
                                                        | CParR l c => CParR l (emplaceR c e)
                                                        | CRestrict c H => CRestrict (emplaceR c e) H end.

Definition emplace_eq (c1 c2 : Context) (e:CCS) : emplaceC c1 (emplaceC c2 e) = emplaceC (emplaceR c1 c2) e.
Proof.
induction c1; cbn; congruence.
Defined.


(* Copyright (c) 2006, 2011-2012, 2015, Adam Chlipala
 *
 * This work is licensed under a
 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
 * Unported License.
 * The license text is available at:
 *   http://creativecommons.org/licenses/by-nc-nd/3.0/
 *)

(* begin hide *)
Require Import Arith List Omega.
Add LoadPath "/home/paul/Documents/coqs/protosynth/cpdt/src" as Cpdt.
Require Import Cpdt.CpdtTactics Cpdt.Coinductive.
Set Implicit Arguments.
Set Asymmetric Patterns.
(* end hide *)

(** %\chapter{General Recursion}% *)

(** Termination of all programs is a crucial property of Gallina.  Non-terminating programs introduce logical inconsistency, where any theorem can be proved with an infinite loop.  Coq uses a small set of conservative, syntactic criteria to check termination of all recursive definitions.  These criteria are insufficient to support the natural encodings of a variety of important programming idioms.  Further, since Coq makes it so convenient to encode mathematics computationally, with functional programs, we may find ourselves wanting to employ more complicated recursion in mathematical definitions.

   What exactly are the conservative criteria that we run up against?  For _recursive_ definitions, recursive calls are only allowed on _syntactic subterms_ of the original primary argument, a restriction known as%\index{primitive recursion}% _primitive recursion_.  In fact, Coq's handling of reflexive inductive types (those defined in terms of functions returning the same type) gives a bit more flexibility than in traditional primitive recursion, but the term is still applied commonly.  In Chapter 5, we saw how _co-recursive_ definitions are checked against a syntactic guardedness condition that guarantees productivity.

   Many natural recursion patterns satisfy neither condition.  For instance, there is our simple running example in this chapter, merge sort.  We will study three different approaches to more flexible recursion, and the latter two of the approaches will even support definitions that may fail to terminate on certain inputs, without any up-front characterization of which inputs those may be.

   Before proceeding, it is important to note that the problem here is not as fundamental as it may appear.  The final example of Chapter 5 demonstrated what is called a%\index{deep embedding}% _deep embedding_ of the syntax and semantics of a programming language.  That is, we gave a mathematical definition of a language of programs and their meanings.  This language clearly admitted non-termination, and we could think of writing all our sophisticated recursive functions with such explicit syntax types.  However, in doing so, we forfeit our chance to take advantage of Coq's very good built-in support for reasoning about Gallina programs.  We would rather use a%\index{shallow embedding}% _shallow embedding_, where we model informal constructs by encoding them as normal Gallina programs.  Each of the three techniques of this chapter follows that style. *)

(** * Well-Founded Recursion *)

(** The essence of terminating recursion is that there are no infinite chains of nested recursive calls.  This intuition is commonly mapped to the mathematical idea of a%\index{well-founded relation}% _well-founded relation_, and the associated standard technique in Coq is%\index{well-founded recursion}% _well-founded recursion_.  The syntactic-subterm relation that Coq applies by default is well-founded, but many cases demand alternate well-founded relations.  To demonstrate, let us see where we get stuck on attempting a standard merge sort implementation. *)

Section mergeSort.
  Variable A : Type.
  Variable le : A -> A -> bool.

  (** We have a set equipped with some "less-than-or-equal-to" test. *)

  (** A standard function inserts an element into a sorted list, preserving sortedness. *)

  Fixpoint insert (x : A) (ls : list A) : list A :=
    match ls with
      | nil => x :: nil
      | h :: ls' =>
	if le x h
	  then x :: ls
	  else h :: insert x ls'
    end.

  (** We will also need a function to merge two sorted lists.  (We use a less efficient implementation than usual, because the more efficient implementation already forces us to think about well-founded recursion, while here we are only interested in setting up the example of merge sort.) *)

  Fixpoint merge (ls1 ls2 : list A) : list A :=
    match ls1 with
      | nil => ls2
      | h :: ls' => insert h (merge ls' ls2)
    end.

  (** The last helper function for classic merge sort is the one that follows, to split a list arbitrarily into two pieces of approximately equal length. *)

  Fixpoint split (ls : list A) : list A * list A :=
    match ls with
      | nil => (nil, nil)
      | h :: nil => (h :: nil, nil)
      | h1 :: h2 :: ls' =>
	let (ls1, ls2) := split ls' in
	  (h1 :: ls1, h2 :: ls2)
    end.

  (** Now, let us try to write the final sorting function, using a natural number "[<=]" test [leb] from the standard library.
[[
  Fixpoint mergeSort (ls : list A) : list A :=
    if leb (length ls) 1
      then ls
      else let lss := split ls in
	merge (mergeSort (fst lss)) (mergeSort (snd lss)).
]]

<<
Recursive call to mergeSort has principal argument equal to
"fst (split ls)" instead of a subterm of "ls".
>>

The definition is rejected for not following the simple primitive recursion criterion.  In particular, it is not apparent that recursive calls to [mergeSort] are syntactic subterms of the original argument [ls]; indeed, they are not, yet we know this is a well-founded recursive definition.

To produce an acceptable definition, we need to choose a well-founded relation and prove that [mergeSort] respects it.  A good starting point is an examination of how well-foundedness is formalized in the Coq standard library. *)

  Print well_founded.
  (** %\vspace{-.15in}% [[
well_founded =
fun (A : Type) (R : A -> A -> Prop) => forall a : A, Acc R a
]]

The bulk of the definitional work devolves to the%\index{accessibility relation}\index{Gallina terms!Acc}% _accessibility_ relation [Acc], whose definition we may also examine. *)

(* begin hide *)
(* begin thide *)
Definition Acc_intro' := Acc_intro.
(* end thide *)
(* end hide *)

  Print Acc.
(** %\vspace{-.15in}% [[
Inductive Acc (A : Type) (R : A -> A -> Prop) (x : A) : Prop :=
    Acc_intro : (forall y : A, R y x -> Acc R y) -> Acc R x
]]

In prose, an element [x] is accessible for a relation [R] if every element "less than" [x] according to [R] is also accessible.  Since [Acc] is defined inductively, we know that any accessibility proof involves a finite chain of invocations, in a certain sense that we can make formal.  Building on Chapter 5's examples, let us define a co-inductive relation that is closer to the usual informal notion of "absence of infinite decreasing chains." *)

  CoInductive infiniteDecreasingChain A (R : A -> A -> Prop) : stream A -> Prop :=
  | ChainCons : forall x y s, infiniteDecreasingChain R (Cons y s)
    -> R y x
    -> infiniteDecreasingChain R (Cons x (Cons y s)).

(** We can now prove that any accessible element cannot be the beginning of any infinite decreasing chain. *)

(* begin thide *)
  Lemma noBadChains' : forall A (R : A -> A -> Prop) x, Acc R x
    -> forall s, ~infiniteDecreasingChain R (Cons x s).
    induction 1; crush;
      match goal with
        | [ H : infiniteDecreasingChain _ _ |- _ ] => inversion H; eauto
      end.
  Qed.

(** From here, the absence of infinite decreasing chains in well-founded sets is immediate. *)

  Theorem noBadChains : forall A (R : A -> A -> Prop), well_founded R
    -> forall s, ~infiniteDecreasingChain R s.
    destruct s; apply noBadChains'; auto.
  Qed.
(* end thide *)

(** Absence of infinite decreasing chains implies absence of infinitely nested recursive calls, for any recursive definition that respects the well-founded relation.  The [Fix] combinator from the standard library formalizes that intuition: *)

  Check Fix.
(** %\vspace{-.15in}%[[
Fix
     : forall (A : Type) (R : A -> A -> Prop),
       well_founded R ->
       forall P : A -> Type,
       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->
       forall x : A, P x
]]

A call to %\index{Gallina terms!Fix}%[Fix] must present a relation [R] and a proof of its well-foundedness.  The next argument, [P], is the possibly dependent range type of the function we build; the domain [A] of [R] is the function's domain.  The following argument has this type:
[[
       forall x : A, (forall y : A, R y x -> P y) -> P x
]]

This is an encoding of the function body.  The input [x] stands for the function argument, and the next input stands for the function we are defining.  Recursive calls are encoded as calls to the second argument, whose type tells us it expects a value [y] and a proof that [y] is "less than" [x], according to [R].  In this way, we enforce the well-foundedness restriction on recursive calls.

The rest of [Fix]'s type tells us that it returns a function of exactly the type we expect, so we are now ready to use it to implement [mergeSort].  Careful readers may have noticed that [Fix] has a dependent type of the sort we met in the previous chapter.

Before writing [mergeSort], we need to settle on a well-founded relation.  The right one for this example is based on lengths of lists. *)

  Definition lengthOrder (ls1 ls2 : list A) :=
    length ls1 < length ls2.

  (** We must prove that the relation is truly well-founded.  To save some space in the rest of this chapter, we skip right to nice, automated proof scripts, though we postpone introducing the principles behind such scripts to Part III of the book.  Curious readers may still replace semicolons with periods and newlines to step through these scripts interactively. *)

  Hint Constructors Acc.

  Lemma lengthOrder_wf' : forall len, forall ls, length ls <= len -> Acc lengthOrder ls.
    unfold lengthOrder; induction len; crush.
  Defined.

  Theorem lengthOrder_wf : well_founded lengthOrder.
    red; intro; eapply lengthOrder_wf'; eauto.
  Defined.

  (** Notice that we end these proofs with %\index{Vernacular commands!Defined}%[Defined], not [Qed].  Recall that [Defined] marks the theorems as %\emph{%#<i>#transparent#</i>#%}%, so that the details of their proofs may be used during program execution.  Why could such details possibly matter for computation?  It turns out that [Fix] satisfies the primitive recursion restriction by declaring itself as _recursive in the structure of [Acc] proofs_.  This is possible because [Acc] proofs follow a predictable inductive structure.  We must do work, as in the last theorem's proof, to establish that all elements of a type belong to [Acc], but the automatic unwinding of those proofs during recursion is straightforward.  If we ended the proof with [Qed], the proof details would be hidden from computation, in which case the unwinding process would get stuck.

     To justify our two recursive [mergeSort] calls, we will also need to prove that [split] respects the [lengthOrder] relation.  These proofs, too, must be kept transparent, to avoid stuckness of [Fix] evaluation.  We use the syntax [@foo] to reference identifier [foo] with its implicit argument behavior turned off.  (The proof details below use Ltac features not introduced yet, and they are safe to skip for now.) *)

  Lemma split_wf : forall len ls, 2 <= length ls <= len
    -> let (ls1, ls2) := split ls in
      lengthOrder ls1 ls /\ lengthOrder ls2 ls.
    unfold lengthOrder; induction len; crush; do 2 (destruct ls; crush);
      destruct (le_lt_dec 2 (length ls));
        repeat (match goal with
                  | [ _ : length ?E < 2 |- _ ] => destruct E
                  | [ _ : S (length ?E) < 2 |- _ ] => destruct E
                  | [ IH : _ |- context[split ?L] ] =>
                    specialize (IH L); destruct (split L); destruct IH
                end; crush).
  Defined.

  Ltac split_wf := intros ls ?; intros; generalize (@split_wf (length ls) ls);
    destruct (split ls); destruct 1; crush.

  Lemma split_wf1 : forall ls, 2 <= length ls
    -> lengthOrder (fst (split ls)) ls.
    split_wf.
  Defined.

  Lemma split_wf2 : forall ls, 2 <= length ls
    -> lengthOrder (snd (split ls)) ls.
    split_wf.
  Defined.

  Hint Resolve split_wf1 split_wf2.

  (** To write the function definition itself, we use the %\index{tactics!refine}%[refine] tactic as a convenient way to write a program that needs to manipulate proofs, without writing out those proofs manually.  We also use a replacement [le_lt_dec] for [leb] that has a more interesting dependent type.  (Note that we would not be able to complete the definition without this change, since [refine] will generate subgoals for the [if] branches based only on the _type_ of the test expression, not its _value_.) *)

  Definition mergeSort : list A -> list A.
(* begin thide *)
    refine (Fix lengthOrder_wf (fun _ => list A)
      (fun (ls : list A)
        (mergeSort : forall ls' : list A, lengthOrder ls' ls -> list A) =>
        if le_lt_dec 2 (length ls)
	  then let lss := split ls in
            merge (mergeSort (fst lss) _) (mergeSort (snd lss) _)
	  else ls)); subst lss; eauto.
  Defined.
(* end thide *)
End mergeSort.

(** The important thing is that it is now easy to evaluate calls to [mergeSort]. *)

Eval compute in mergeSort leb (1 :: 2 :: 36 :: 8 :: 19 :: nil).
(** [= 1 :: 2 :: 8 :: 19 :: 36 :: nil] *)

(** %\smallskip{}%Since the subject of this chapter is merely how to define functions with unusual recursion structure, we will not prove any further correctness theorems about [mergeSort]. Instead, we stop at proving that [mergeSort] has the expected computational behavior, for all inputs, not merely the one we just tested. *)

(* begin thide *)
Theorem mergeSort_eq : forall A (le : A -> A -> bool) ls,
  mergeSort le ls = if le_lt_dec 2 (length ls)
    then let lss := split ls in
      merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))
    else ls.
  intros; apply (Fix_eq (@lengthOrder_wf A) (fun _ => list A)); intros.

  (** The library theorem [Fix_eq] imposes one more strange subgoal upon us.  We must prove that the function body is unable to distinguish between "self" arguments that map equal inputs to equal outputs.  One might think this should be true of any Gallina code, but in fact this general%\index{extensionality}% _function extensionality_ property is neither provable nor disprovable within Coq.  The type of [Fix_eq] makes clear what we must show manually: *)

  Check Fix_eq.
(** %\vspace{-.15in}%[[
Fix_eq
     : forall (A : Type) (R : A -> A -> Prop) (Rwf : well_founded R)
         (P : A -> Type)
         (F : forall x : A, (forall y : A, R y x -> P y) -> P x),
       (forall (x : A) (f g : forall y : A, R y x -> P y),
        (forall (y : A) (p : R y x), f y p = g y p) -> F x f = F x g) ->
       forall x : A,
       Fix Rwf P F x = F x (fun (y : A) (_ : R y x) => Fix Rwf P F y)
]]

  Most such obligations are dischargeable with straightforward proof automation, and this example is no exception. *)

  match goal with
    | [ |- context[match ?E with left _ => _ | right _ => _ end] ] => destruct E
  end; simpl; f_equal; auto.
Qed.
(* end thide *)

(** As a final test of our definition's suitability, we can extract to OCaml. *)

Extraction mergeSort.

(** <<
let rec mergeSort le x =
  match le_lt_dec (S (S O)) (length x) with
  | Left ->
    let lss = split x in
    merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))
  | Right -> x
>>

  We see almost precisely the same definition we would have written manually in OCaml!  It might be a good exercise for the reader to use the commands we saw in the previous chapter to clean up some remaining differences from idiomatic OCaml.

  One more piece of the full picture is missing.  To go on and prove correctness of [mergeSort], we would need more than a way of unfolding its definition.  We also need an appropriate induction principle matched to the well-founded relation.  Such a principle is available in the standard library, though we will say no more about its details here. *)

Check well_founded_induction.
(** %\vspace{-.15in}%[[
well_founded_induction
     : forall (A : Type) (R : A -> A -> Prop),
       well_founded R ->
       forall P : A -> Set,
       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->
       forall a : A, P a
]]

  Some more recent Coq features provide more convenient syntax for defining recursive functions.  Interested readers can consult the Coq manual about the commands %\index{Function}%[Function] and %\index{Program Fixpoint}%[Program Fixpoint]. *)

(** * A Non-Termination Monad Inspired by Domain Theory *)

(** The key insights of %\index{domain theory}%domain theory%~\cite{WinskelDomains}% inspire the next approach to modeling non-termination.  Domain theory is based on _information orders_ that relate values representing computation results, according to how much information these values convey.  For instance, a simple domain might include values "the program does not terminate" and "the program terminates with the answer 5."  The former is considered to be an _approximation_ of the latter, while the latter is _not_ an approximation of "the program terminates with the answer 6."  The details of domain theory will not be important in what follows; we merely borrow the notion of an approximation ordering on computation results.

   Consider this definition of a type of computations. *)

Section computation.
  Variable A : Type.
  (** The type [A] describes the result a computation will yield, if it terminates.

     We give a rich dependent type to computations themselves: *)

  Definition computation :=
    {f : nat -> option A
      | forall (n : nat) (v : A),
	f n = Some v
	-> forall (n' : nat), n' >= n
	  -> f n' = Some v}.

  (** A computation is fundamentally a function [f] from an _approximation level_ [n] to an optional result.  Intuitively, higher [n] values enable termination in more cases than lower values.  A call to [f] may return [None] to indicate that [n] was not high enough to run the computation to completion; higher [n] values may yield [Some].  Further, the proof obligation within the subset type asserts that [f] is _monotone_ in an appropriate sense: when some [n] is sufficient to produce termination, so are all higher [n] values, and they all yield the same program result [v].

  It is easy to define a relation characterizing when a computation runs to a particular result at a particular approximation level. *)

  Definition runTo (m : computation) (n : nat) (v : A) :=
    proj1_sig m n = Some v.

  (** On top of [runTo], we also define [run], which is the most abstract notion of when a computation runs to a value. *)

  Definition run (m : computation) (v : A) :=
    exists n, runTo m n v.
End computation.

(** The book source code contains at this point some tactics, lemma proofs, and hint commands, to be used in proving facts about computations.  Since their details are orthogonal to the message of this chapter, I have omitted them in the rendered version. *)
(* begin hide *)

Hint Unfold runTo.

Ltac run' := unfold run, runTo in *; try red; crush;
  repeat (match goal with
            | [ _ : proj1_sig ?E _ = _ |- _ ] =>
              match goal with
                | [ x : _ |- _ ] =>
                  match x with
                    | E => destruct E
                  end
              end
            | [ |- context[match ?M with exist _ _ => _ end] ] => let Heq := fresh "Heq" in
              case_eq M; intros ? ? Heq; try rewrite Heq in *; try subst
            | [ _ : context[match ?M with exist _ _ => _ end] |- _ ] => let Heq := fresh "Heq" in
              case_eq M; intros ? ? Heq; try rewrite Heq in *; subst
            | [ H : forall n v, ?E n = Some v -> _,
                _ : context[match ?E ?N with Some _ => _ | None => _ end] |- _ ] =>
              specialize (H N); destruct (E N); try rewrite (H _ (eq_refl _)) by auto; try discriminate
            | [ H : forall n v, ?E n = Some v -> _, H' : ?E _ = Some _ |- _ ] => rewrite (H _ _ H') by auto
          end; simpl in *); eauto 7.

Ltac run := run'; repeat (match goal with
                            | [ H : forall n v, ?E n = Some v -> _
                                |- context[match ?E ?N with Some _ => _ | None => _ end] ] =>
                              specialize (H N); destruct (E N); try rewrite (H _ (eq_refl _)) by auto; try discriminate
                          end; run').

Lemma ex_irrelevant : forall P : Prop, P -> exists n : nat, P.
  exists 0; auto.
Qed.

Hint Resolve ex_irrelevant.

Require Import Max.

Theorem max_spec_le : forall n m, n <= m /\ max n m = m \/ m <= n /\ max n m = n.
  induction n; destruct m; simpl; intuition;
    specialize (IHn m); intuition.
Qed.

Ltac max := intros n m; generalize (max_spec_le n m); crush.

Lemma max_1 : forall n m, max n m >= n.
  max.
Qed.

Lemma max_2 : forall n m, max n m >= m.
  max.
Qed.

Hint Resolve max_1 max_2.

Lemma ge_refl : forall n, n >= n.
  crush.
Qed.

Hint Resolve ge_refl.

Hint Extern 1 => match goal with
                   | [ H : _ = exist _ _ _ |- _ ] => rewrite H
                 end.
(* end hide *)
(** remove printing exists *)

(** Now, as a simple first example of a computation, we can define [Bottom], which corresponds to an infinite loop.  For any approximation level, it fails to terminate (returns [None]).  Note the use of [abstract] to create a new opaque lemma for the proof found by the #<tt>#%\coqdocvar{%run%}%#</tt># tactic.  In contrast to the previous section, opaque proofs are fine here, since the proof components of computations do not influence evaluation behavior.  It is generally preferable to make proofs opaque when possible, as this enforces a kind of modularity in the code to follow, preventing it from depending on any details of the proof. *)

Section Bottom.
  Variable A : Type.

  Definition Bottom : computation A.
    exists (fun _ : nat => @None A); abstract run.
  Defined.

  Theorem run_Bottom : forall v, ~run Bottom v.
    run.
  Qed.
End Bottom.

(** A slightly more complicated example is [Return], which gives the same terminating answer at every approximation level. *)

Section Return.
  Variable A : Type.
  Variable v : A.

  Definition Return : computation A.
    intros; exists (fun _ : nat => Some v); abstract run.
  Defined.

  Theorem run_Return : run Return v.
    run.
  Qed.
End Return.

(** The name [Return] was meant to be suggestive of the standard operations of %\index{monad}%monads%~\cite{Monads}%.  The other standard operation is [Bind], which lets us run one computation and, if it terminates, pass its result off to another computation.  We implement bind using the notation [let (x, y) := e1 in e2], for pulling apart the value [e1] which may be thought of as a pair.  The second component of a [computation] is a proof, which we do not need to mention directly in the definition of [Bind]. *)

Section Bind.
  Variables A B : Type.
  Variable m1 : computation A.
  Variable m2 : A -> computation B.

  Definition Bind : computation B.
    exists (fun n =>
      let (f1, _) := m1 in
      match f1 n with
	| None => None
	| Some v =>
	  let (f2, _) := m2 v in
	    f2 n
      end); abstract run.
  Defined.

  Theorem run_Bind : forall (v1 : A) (v2 : B),
    run m1 v1
    -> run (m2 v1) v2
    -> run Bind v2.
    run; match goal with
           | [ x : nat, y : nat |- _ ] => exists (max x y)
         end; run.
  Qed.
End Bind.

(** A simple notation lets us write [Bind] calls the way they appear in Haskell. *)

Notation "x <- m1 ; m2" :=
  (Bind m1 (fun x => m2)) (right associativity, at level 70).

(** We can verify that we have indeed defined a monad, by proving the standard monad laws.  Part of the exercise is choosing an appropriate notion of equality between computations.  We use "equality at all approximation levels." *)

Definition meq A (m1 m2 : computation A) := forall n, proj1_sig m1 n = proj1_sig m2 n.

Theorem left_identity : forall A B (a : A) (f : A -> computation B),
  meq (Bind (Return a) f) (f a).
  run.
Qed.

Theorem right_identity : forall A (m : computation A),
  meq (Bind m (@Return _)) m.
  run.
Qed.

Theorem associativity : forall A B C (m : computation A)
  (f : A -> computation B) (g : B -> computation C),
  meq (Bind (Bind m f) g) (Bind m (fun x => Bind (f x) g)).
  run.
Qed.

(** Now we come to the piece most directly inspired by domain theory.  We want to support general recursive function definitions, but domain theory tells us that not all definitions are reasonable; some fail to be _continuous_ and thus represent unrealizable computations.  To formalize an analogous notion of continuity for our non-termination monad, we write down the approximation relation on computation results that we have had in mind all along. *)

Section lattice.
  Variable A : Type.

  Definition leq (x y : option A) :=
    forall v, x = Some v -> y = Some v.
End lattice.

(** We now have the tools we need to define a new [Fix] combinator that, unlike the one we saw in the prior section, does not require a termination proof, and in fact admits recursive definition of functions that fail to terminate on some or all inputs. *)

Section Fix.

  (** First, we have the function domain and range types. *)

  Variables A B : Type.

  (** Next comes the function body, which is written as though it can be parameterized over itself, for recursive calls. *)

  Variable f : (A -> computation B) -> (A -> computation B).

  (** Finally, we impose an obligation to prove that the body [f] is continuous.  That is, when [f] terminates according to one recursive version of itself, it also terminates with the same result at the same approximation level when passed a recursive version that refines the original, according to [leq]. *)

  Hypothesis f_continuous : forall n v v1 x,
    runTo (f v1 x) n v
    -> forall (v2 : A -> computation B),
      (forall x, leq (proj1_sig (v1 x) n) (proj1_sig (v2 x) n))
      -> runTo (f v2 x) n v.

  (** The computational part of the [Fix] combinator is easy to define.  At approximation level 0, we diverge; at higher levels, we run the body with a functional argument drawn from the next lower level. *)

  Fixpoint Fix' (n : nat) (x : A) : computation B :=
    match n with
      | O => Bottom _
      | S n' => f (Fix' n') x
    end.

  (** Now it is straightforward to package [Fix'] as a computation combinator [Fix]. *)

  Hint Extern 1 (_ >= _) => omega.
  Hint Unfold leq.

  Lemma Fix'_ok : forall steps n x v, proj1_sig (Fix' n x) steps = Some v
    -> forall n', n' >= n
      -> proj1_sig (Fix' n' x) steps = Some v.
    unfold runTo in *; induction n; crush;
      match goal with
        | [ H : _ >= _ |- _ ] => inversion H; crush; eauto
      end.
  Qed.

  Hint Resolve Fix'_ok.

  Hint Extern 1 (proj1_sig _ _ = _) => simpl;
    match goal with
      | [ |- proj1_sig ?E _ = _ ] => eapply (proj2_sig E)
    end.

  Definition Fix : A -> computation B.
    intro x; exists (fun n => proj1_sig (Fix' n x) n); abstract run.
  Defined.

  (** Finally, we can prove that [Fix] obeys the expected computation rule. *)

  Theorem run_Fix : forall x v,
    run (f Fix x) v
    -> run (Fix x) v.
    run; match goal with
           | [ n : nat |- _ ] => exists (S n); eauto
         end.
  Qed.
End Fix.

(* begin hide *)
Lemma leq_Some : forall A (x y : A), leq (Some x) (Some y)
  -> x = y.
  intros ? ? ? H; generalize (H _ (eq_refl _)); crush.
Qed.

Lemma leq_None : forall A (x y : A), leq (Some x) None
  -> False.
  intros ? ? ? H; generalize (H _ (eq_refl _)); crush.
Qed.

Ltac mergeSort' := run;
  repeat (match goal with
            | [ |- context[match ?E with O => _ | S _ => _ end] ] => destruct E
          end; run);
  repeat match goal with
           | [ H : forall x, leq (proj1_sig (?f x) _) (proj1_sig (?g x) _) |- _ ] =>
             match goal with
               | [ H1 : f ?arg = _, H2 : g ?arg = _ |- _ ] =>
                 generalize (H arg); rewrite H1; rewrite H2; clear H1 H2; simpl; intro
             end
         end; run; repeat match goal with
                            | [ H : _ |- _ ] => (apply leq_None in H; tauto) || (apply leq_Some in H; subst)
                          end; auto.
(* end hide *)

(** After all that work, it is now fairly painless to define a version of [mergeSort] that requires no proof of termination.  We appeal to a program-specific tactic whose definition is hidden here but present in the book source. *)

Definition mergeSort' : forall A, (A -> A -> bool) -> list A -> computation (list A).
  refine (fun A le => Fix
    (fun (mergeSort : list A -> computation (list A))
      (ls : list A) =>
      if le_lt_dec 2 (length ls)
	then let lss := split ls in
          ls1 <- mergeSort (fst lss);
          ls2 <- mergeSort (snd lss);
          Return (merge le ls1 ls2)
	else Return ls) _); abstract mergeSort'.
Defined.

(** Furthermore, "running" [mergeSort'] on concrete inputs is as easy as choosing a sufficiently high approximation level and letting Coq's computation rules do the rest.  Contrast this with the proof work that goes into deriving an evaluation fact for a deeply embedded language, with one explicit proof rule application per execution step. *)

Lemma test_mergeSort' : run (mergeSort' leb (1 :: 2 :: 36 :: 8 :: 19 :: nil))
  (1 :: 2 :: 8 :: 19 :: 36 :: nil).
  exists 4; reflexivity.
Qed.

(** There is another benefit of our new [Fix] compared with the one we used in the previous section: we can now write recursive functions that sometimes fail to terminate, without losing easy reasoning principles for the terminating cases.  Consider this simple example, which appeals to another tactic whose definition we elide here. *)

(* begin hide *)
Ltac looper := unfold leq in *; run;
  repeat match goal with
           | [ x : unit |- _ ] => destruct x
           | [ x : bool |- _ ] => destruct x
         end; auto.
(* end hide *)

Definition looper : bool -> computation unit.
  refine (Fix (fun looper (b : bool) =>
    if b then Return tt else looper b) _); abstract looper.
Defined.

Lemma test_looper : run (looper true) tt.
  exists 1; reflexivity.
Qed.

(** As before, proving outputs for specific inputs is as easy as demonstrating a high enough approximation level.

   There are other theorems that are important to prove about combinators like [Return], [Bind], and [Fix].  In general, for a computation [c], we sometimes have a hypothesis proving [run c v] for some [v], and we want to perform inversion to deduce what [v] must be.  Each combinator should ideally have a theorem of that kind, for [c] built directly from that combinator.  We have omitted such theorems here, but they are not hard to prove.  In general, the domain theory-inspired approach avoids the type-theoretic "gotchas" that tend to show up in approaches that try to mix normal Coq computation with explicit syntax types.  The next section of this chapter demonstrates two alternate approaches of that sort.  In the final section of the chapter, we review the pros and cons of the different choices, coming to the conclusion that none of them is obviously better than any one of the others for all situations. *)

(** * Co-Inductive Non-Termination Monads *)

(** There are two key downsides to both of the previous approaches: both require unusual syntax based on explicit calls to fixpoint combinators, and both generate immediate proof obligations about the bodies of recursive definitions.  In Chapter 5, we have already seen how co-inductive types support recursive definitions that exhibit certain well-behaved varieties of non-termination.  It turns out that we can leverage that co-induction support for encoding of general recursive definitions, by adding layers of co-inductive syntax.  In effect, we mix elements of shallow and deep embeddings.

   Our first example of this kind, proposed by Capretta%~\cite{Capretta}%, defines a silly-looking type of thunks; that is, computations that may be forced to yield results, if they terminate. *)

CoInductive thunk (A : Type) : Type :=
| Answer : A -> thunk A
| Think : thunk A -> thunk A.

(** A computation is either an immediate [Answer] or another computation wrapped inside [Think].  Since [thunk] is co-inductive, every [thunk] type is inhabited by an infinite nesting of [Think]s, standing for non-termination.  Terminating results are [Answer] wrapped inside some finite number of [Think]s.

   Why bother to write such a strange definition?  The definition of [thunk] is motivated by the ability it gives us to define a "bind" operation, similar to the one we defined in the previous section. *)

CoFixpoint TBind A B (m1 : thunk A) (m2 : A -> thunk B) : thunk B :=
  match m1 with
    | Answer x => m2 x
    | Think m1' => Think (TBind m1' m2)
  end.

(** Note that the definition would violate the co-recursion guardedness restriction if we left out the seemingly superfluous [Think] on the righthand side of the second [match] branch.

   We can prove that [Answer] and [TBind] form a monad for [thunk].  The proof is omitted here but present in the book source.  As usual for this sort of proof, a key element is choosing an appropriate notion of equality for [thunk]s. *)

(* begin hide *)
CoInductive thunk_eq A : thunk A -> thunk A -> Prop :=
| EqAnswer : forall x, thunk_eq (Answer x) (Answer x)
| EqThinkL : forall m1 m2, thunk_eq m1 m2 -> thunk_eq (Think m1) m2
| EqThinkR : forall m1 m2, thunk_eq m1 m2 -> thunk_eq m1 (Think m2).

Section thunk_eq_coind.
  Variable A : Type.
  Variable P : thunk A -> thunk A -> Prop.

  Hypothesis H : forall m1 m2, P m1 m2
    -> match m1, m2 with
         | Answer x1, Answer x2 => x1 = x2
         | Think m1', Think m2' => P m1' m2'
         | Think m1', _ => P m1' m2
         | _, Think m2' => P m1 m2'
       end.

  Theorem thunk_eq_coind : forall m1 m2, P m1 m2 -> thunk_eq m1 m2.
    cofix; intros;
      match goal with
        | [ H' : P _ _ |- _ ] => specialize (H H'); clear H'
      end; destruct m1; destruct m2; subst; repeat constructor; auto.
  Qed.
End thunk_eq_coind.
(* end hide *)

(** In the proofs to follow, we will need a function similar to one we saw in Chapter 5, to pull apart and reassemble a [thunk] in a way that provokes reduction of co-recursive calls. *)

Definition frob A (m : thunk A) : thunk A :=
  match m with
    | Answer x => Answer x
    | Think m' => Think m'
  end.

Theorem frob_eq : forall A (m : thunk A), frob m = m.
  destruct m; reflexivity.
Qed.

(* begin hide *)
Theorem thunk_eq_frob : forall A (m1 m2 : thunk A),
  thunk_eq (frob m1) (frob m2)
  -> thunk_eq m1 m2.
  intros; repeat rewrite frob_eq in *; auto.
Qed.

Ltac findDestr := match goal with
                    | [ |- context[match ?E with Answer _ => _ | Think _ => _ end] ] =>
                      match E with
                        | context[match _ with Answer _ => _ | Think _ => _ end] => fail 1
                        | _ => destruct E
                      end
                  end.

Theorem thunk_eq_refl : forall A (m : thunk A), thunk_eq m m.
  intros; apply (thunk_eq_coind (fun m1 m2 => m1 = m2)); crush; findDestr; reflexivity.
Qed.

Hint Resolve thunk_eq_refl.

Theorem tleft_identity : forall A B (a : A) (f : A -> thunk B),
  thunk_eq (TBind (Answer a) f) (f a).
  intros; apply thunk_eq_frob; crush.
Qed.

Theorem tright_identity : forall A (m : thunk A),
  thunk_eq (TBind m (@Answer _)) m.
  intros; apply (thunk_eq_coind (fun m1 m2 => m1 = TBind m2 (@Answer _))); crush;
    findDestr; reflexivity.
Qed.

Lemma TBind_Answer : forall (A B : Type) (v : A) (m2 : A -> thunk B),
  TBind (Answer v) m2 = m2 v.
  intros; rewrite <- (frob_eq (TBind (Answer v) m2));
    simpl; findDestr; reflexivity.
Qed.

Hint Rewrite TBind_Answer.

(** printing exists $\exists$ *)

Theorem tassociativity : forall A B C (m : thunk A) (f : A -> thunk B) (g : B -> thunk C),
  thunk_eq (TBind (TBind m f) g) (TBind m (fun x => TBind (f x) g)).
  intros; apply (thunk_eq_coind (fun m1 m2 => (exists m,
    m1 = TBind (TBind m f) g
    /\ m2 = TBind m (fun x => TBind (f x) g))
  \/ m1 = m2)); crush; eauto; repeat (findDestr; crush; eauto).
Qed.
(* end hide *)

(** As a simple example, here is how we might define a tail-recursive factorial function. *)

CoFixpoint fact (n acc : nat) : thunk nat :=
  match n with
    | O => Answer acc
    | S n' => Think (fact n' (S n' * acc))
  end.

(** To test our definition, we need an evaluation relation that characterizes results of evaluating [thunk]s. *)

Inductive eval A : thunk A -> A -> Prop :=
| EvalAnswer : forall x, eval (Answer x) x
| EvalThink : forall m x, eval m x -> eval (Think m) x.

Hint Rewrite frob_eq.

Lemma eval_frob : forall A (c : thunk A) x,
  eval (frob c) x
  -> eval c x.
  crush.
Qed.

Theorem eval_fact : eval (fact 5 1) 120.
  repeat (apply eval_frob; simpl; constructor).
Qed.

(** We need to apply constructors of [eval] explicitly, but the process is easy to automate completely for concrete input programs.

   Now consider another very similar definition, this time of a Fibonacci number function. *)

Notation "x <- m1 ; m2" :=
  (TBind m1 (fun x => m2)) (right associativity, at level 70).

(* begin hide *)
(* begin thide *)
Definition fib := pred.
(* end thide *)
(* end hide *)

(** %\vspace{-.3in}%[[
CoFixpoint fib (n : nat) : thunk nat :=
  match n with
    | 0 => Answer 1
    | 1 => Answer 1
    | _ => n1 <- fib (pred n);
      n2 <- fib (pred (pred n));
      Answer (n1 + n2)
  end.
]]

Coq complains that the guardedness condition is violated.  The two recursive calls are immediate arguments to [TBind], but [TBind] is not a constructor of [thunk].  Rather, it is a defined function.  This example shows a very serious limitation of [thunk] for traditional functional programming: it is not, in general, possible to make recursive calls and then make further recursive calls, depending on the first call's result.  The [fact] example succeeded because it was already tail recursive, meaning no further computation is needed after a recursive call.

%\medskip%

I know no easy fix for this problem of [thunk], but we can define an alternate co-inductive monad that avoids the problem, based on a proposal by Megacz%~\cite{Megacz}%.  We ran into trouble because [TBind] was not a constructor of [thunk], so let us define a new type family where "bind" is a constructor. *)

CoInductive comp (A : Type) : Type :=
| Ret : A -> comp A
| Bnd : forall B, comp B -> (B -> comp A) -> comp A.

(** This example shows off Coq's support for%\index{recursively non-uniform parameters}% _recursively non-uniform parameters_, as in the case of the parameter [A] declared above, where each constructor's type ends in [comp A], but there is a recursive use of [comp] with a different parameter [B].  Beside that technical wrinkle, we see the simplest possible definition of a monad, via a type whose two constructors are precisely the monad operators.

   It is easy to define the semantics of terminating [comp] computations. *)

Inductive exec A : comp A -> A -> Prop :=
| ExecRet : forall x, exec (Ret x) x
| ExecBnd : forall B (c : comp B) (f : B -> comp A) x1 x2, exec (A := B) c x1
  -> exec (f x1) x2
  -> exec (Bnd c f) x2.

(** We can also prove that [Ret] and [Bnd] form a monad according to a notion of [comp] equality based on [exec], but we omit details here; they are in the book source at this point. *)

(* begin hide *)
Hint Constructors exec.

Definition comp_eq A (c1 c2 : comp A) := forall r, exec c1 r <-> exec c2 r.

Ltac inverter := repeat match goal with
                          | [ H : exec _ _ |- _ ] => inversion H; []; crush
                        end.

Theorem cleft_identity : forall A B (a : A) (f : A -> comp B),
  comp_eq (Bnd (Ret a) f) (f a).
  red; crush; inverter; eauto.
Qed.

Theorem cright_identity : forall A (m : comp A),
  comp_eq (Bnd m (@Ret _)) m.
  red; crush; inverter; eauto.
Qed.

Lemma cassociativity1 : forall A B C (f : A -> comp B) (g : B -> comp C) r c,
  exec c r
  -> forall m, c = Bnd (Bnd m f) g
   -> exec (Bnd m (fun x => Bnd (f x) g)) r.
  induction 1; crush.
  match goal with
    | [ H : Bnd _ _ = Bnd _ _ |- _ ] => injection H; clear H; intros; try subst
  end.
  try (move H3 after A).
  try (move H2 after A).

  generalize dependent B.
  do 2 intro.
  subst.
  crush.
  inversion H; clear H; crush.
  eauto.
Qed.

Lemma cassociativity2 : forall A B C (f : A -> comp B) (g : B -> comp C) r c,
  exec c r
  -> forall m, c = Bnd m (fun x => Bnd (f x) g)
   -> exec (Bnd (Bnd m f) g) r.
  induction 1; crush.
  match goal with
    | [ H : Bnd _ _ = Bnd _ _ |- _ ] => injection H; clear H; intros; try subst
  end.
  move H2 after B.
  generalize dependent B.
  do 2 intro.
  subst.
  crush.
  inversion H0; clear H0; crush.
  eauto.
Qed.

Hint Resolve cassociativity1 cassociativity2.

Theorem cassociativity : forall A B C (m : comp A) (f : A -> comp B) (g : B -> comp C),
  comp_eq (Bnd (Bnd m f) g) (Bnd m (fun x => Bnd (f x) g)).
  red; crush; eauto.
Qed.
(* end hide *)

(** Not only can we define the Fibonacci function with the new monad, but even our running example of merge sort becomes definable.  By shadowing our previous notation for "bind," we can write almost exactly the same code as in our previous [mergeSort'] definition, but with less syntactic clutter. *)

Notation "x <- m1 ; m2" := (Bnd m1 (fun x => m2)).

CoFixpoint mergeSort'' A (le : A -> A -> bool) (ls : list A) : comp (list A) :=
  if le_lt_dec 2 (length ls)
    then let lss := split ls in
      ls1 <- mergeSort'' le (fst lss);
      ls2 <- mergeSort'' le (snd lss);
      Ret (merge le ls1 ls2)
    else Ret ls.

(** To execute this function, we go through the usual exercise of writing a function to catalyze evaluation of co-recursive calls. *)

Definition frob' A (c : comp A) :=
  match c with
    | Ret x => Ret x
    | Bnd _ c' f => Bnd c' f
  end.

Lemma exec_frob : forall A (c : comp A) x,
  exec (frob' c) x
  -> exec c x.
  destruct c; crush.
Qed.

(** Now the same sort of proof script that we applied for testing [thunk]s will get the job done. *)

Lemma test_mergeSort'' : exec (mergeSort'' leb (1 :: 2 :: 36 :: 8 :: 19 :: nil))
  (1 :: 2 :: 8 :: 19 :: 36 :: nil).
  repeat (apply exec_frob; simpl; econstructor).
Qed.

(** Have we finally reached the ideal solution for encoding general recursive definitions, with minimal hassle in syntax and proof obligations?  Unfortunately, we have not, as [comp] has a serious expressivity weakness.  Consider the following definition of a curried addition function: *)

Definition curriedAdd (n : nat) := Ret (fun m : nat => Ret (n + m)).

(** This definition works fine, but we run into trouble when we try to apply it in a trivial way.
[[
Definition testCurriedAdd := Bnd (curriedAdd 2) (fun f => f 3).
]]

<<
Error: Universe inconsistency.
>>

The problem has to do with rules for inductive definitions that we will study in more detail in Chapter 12.  Briefly, recall that the type of the constructor [Bnd] quantifies over a type [B].  To make [testCurriedAdd] work, we would need to instantiate [B] as [nat -> comp nat].  However, Coq enforces a %\emph{predicativity restriction}% that (roughly) no quantifier in an inductive or co-inductive type's definition may ever be instantiated with a term that contains the type being defined.  Chapter 12 presents the exact mechanism by which this restriction is enforced, but for now our conclusion is that [comp] is fatally flawed as a way of encoding interesting higher-order functional programs that use general recursion. *)

(** * Comparing the Alternatives *)

(** We have seen four different approaches to encoding general recursive definitions in Coq.  Among them there is no clear champion that dominates the others in every important way.  Instead, we close the chapter by comparing the techniques along a number of dimensions.  Every technique allows recursive definitions with termination arguments that go beyond Coq's built-in termination checking, so we must turn to subtler points to highlight differences.

   One useful property is automatic integration with normal Coq programming.  That is, we would like the type of a function to be the same, whether or not that function is defined using an interesting recursion pattern.  Only the first of the four techniques, well-founded recursion, meets this criterion.  It is also the only one of the four to meet the related criterion that evaluation of function calls can take place entirely inside Coq's built-in computation machinery.  The monad inspired by domain theory occupies some middle ground in this dimension, since generally standard computation is enough to evaluate a term once a high enough approximation level is provided.

   Another useful property is that a function and its termination argument may be developed separately.  We may even want to define functions that fail to terminate on some or all inputs.  The well-founded recursion technique does not have this property, but the other three do.

   One minor plus is the ability to write recursive definitions in natural syntax, rather than with calls to higher-order combinators.  This downside of the first two techniques is actually rather easy to get around using Coq's notation mechanism, though we leave the details as an exercise for the reader.  (For this and other details of notations, see Chapter 12 of the Coq 8.4 manual.)

   The first two techniques impose proof obligations that are more basic than termination arguments, where well-founded recursion requires a proof of extensionality and domain-theoretic recursion requires a proof of continuity.  A function may not be defined, and thus may not be computed with, until these obligations are proved.  The co-inductive techniques avoid this problem, as recursive definitions may be made without any proof obligations.

   We can also consider support for common idioms in functional programming.  For instance, the [thunk] monad effectively only supports recursion that is tail recursion, while the others allow arbitrary recursion schemes.

   On the other hand, the [comp] monad does not support the effective mixing of higher-order functions and general recursion, while all the other techniques do.  For instance, we can finish the failed [curriedAdd] example in the domain-theoretic monad. *)

Definition curriedAdd' (n : nat) := Return (fun m : nat => Return (n + m)).

Definition testCurriedAdd := Bind (curriedAdd' 2) (fun f => f 3).

(** The same techniques also apply to more interesting higher-order functions like list map, and, as in all four techniques, we can mix primitive and general recursion, preferring the former when possible to avoid proof obligations. *)

Fixpoint map A B (f : A -> computation B) (ls : list A) : computation (list B) :=
  match ls with
    | nil => Return nil
    | x :: ls' => Bind (f x) (fun x' =>
      Bind (map f ls') (fun ls'' =>
        Return (x' :: ls'')))
  end.

(** remove printing exists *)
Theorem test_map : run (map (fun x => Return (S x)) (1 :: 2 :: 3 :: nil))
  (2 :: 3 :: 4 :: nil).
  exists 1; reflexivity.
Qed.

(** One further disadvantage of [comp] is that we cannot prove an inversion lemma for executions of [Bind] without appealing to an _axiom_, a logical complication that we discuss at more length in Chapter 12.  The other three techniques allow proof of all the important theorems within the normal logic of Coq.

Perhaps one theme of our comparison is that one must trade off between, on one hand, functional programming expressiveness and compatibility with normal Coq types and computation; and, on the other hand, the level of proof obligations one is willing to handle at function definition time. *)


Require Import Fiat.Common Coq.Arith.Arith Coq.Bool.Bool Coq.Sets.Ensembles.

Class DecideableEnsemble {A} (P : Ensemble A) :=
  { dec : A -> bool;
    dec_decides_P : forall a, dec a = true <-> P a}.

Lemma Decides_false {A} :
  forall (P : Ensemble A)
         (P_dec : DecideableEnsemble P) a,
    dec a = false <-> ~ (P a).
Proof.
  split; unfold not; intros.
  + apply dec_decides_P in H0; congruence.
  + case_eq (dec a); intros; eauto.
    apply dec_decides_P in H0; intuition.
Qed.

Instance DecideableEnsemble_gt {A} (f f' : A -> nat)
  : DecideableEnsemble (fun a => f a > f' a) :=
  {| dec a := if le_lt_dec (f a) (f' a) then false else true |}.
Proof.
  intros; find_if_inside; intuition.
Defined.

Instance DecideableEnsemble_And
         {A : Type}
         {P P' : Ensemble A}
         {P_dec : DecideableEnsemble P}
         {P'_dec : DecideableEnsemble P'}
: DecideableEnsemble (fun a => P a /\ P' a) :=
  {| dec a := (@dec _ _ P_dec a) && (@dec _ _  P'_dec a) |}.
Proof.
  intros; rewrite <- (@dec_decides_P _ P),
          <- (@dec_decides_P _ P').
  setoid_rewrite andb_true_iff; reflexivity.
Defined.

(* Class used to overload equality test notation (==) in queries. *)
Class Query_eq (A : Type) :=
      {A_eq_dec : forall a a' : A, {a = a'} + {a <> a'}}.

Infix "==" := (A_eq_dec) (at level 1).

Instance DecideableEnsemble_NEqDec
         {A B : Type}
         {b_eq_dec : Query_eq B}
         (f f' : A -> B)
: DecideableEnsemble (fun a : A => f a <> f' a) :=
  {| dec a := if A_eq_dec (f a) (f' a) then false else true |}.
Proof.
  intros; find_if_inside; intuition.
Defined.

Instance DecideableEnsemble_EqDec {A B : Type}
         (B_eq_dec : Query_eq B)
         (f f' : A -> B)
: DecideableEnsemble (fun a => eq (f a) (f' a)) :=
  {| dec a := if A_eq_dec (f a) (f' a) then true else false |}.
Proof.
  intros; find_if_inside; split; congruence.
Defined.

Instance DecideableEnsemble_Not
         {A : Type}
         (P : Ensemble A)
         {P_dec : DecideableEnsemble P}
: DecideableEnsemble (fun a => ~ P a) :=
  {| dec a := negb (dec a) |}.
Proof.
  intros; case_eq (dec a); intros; intuition eauto.
  - discriminate.
  - rewrite dec_decides_P in H; intuition.
  - rewrite <- dec_decides_P in H1; congruence.
Defined.

Instance DecideableEnsemble_True
         {A : Type}
: DecideableEnsemble (fun a : A => True) :=
  {| dec a := true |}.
Proof.
  intros; intuition eauto.
Defined.

Instance DecideableEnsemble_False
         {A : Type}
: DecideableEnsemble (fun a : A => False) :=
  {| dec a := false |}.
Proof.
  intros; intuition eauto; discriminate.
Defined.

Instance DecideableEnsemble_Or
         {A : Type}
         (P P' : Ensemble A)
         {P_dec : DecideableEnsemble P}
         {P'_dec : DecideableEnsemble P'}
: DecideableEnsemble (fun a : A => P a \/ P' a) :=
  {| dec a := if dec (P := P) a then true else dec (P := P') a |}.
Proof.
  intros; case_eq (dec (P := P) a);
  [ rewrite dec_decides_P | rewrite Decides_false];
  intuition.
  setoid_rewrite dec_decides_P in H0; intuition.
  setoid_rewrite dec_decides_P; intuition.
Defined.


Require Import Coq.omega.Omega.
Require Coq.Setoids.Setoid.

(** This file defines some inductives, type-classes and tactics to
perform reflection on a small scale *)

(** Two inductives to perform case-based reasonning *)
Inductive reflect (P Q : Prop) : bool -> Type :=
| reflect_true : P -> reflect P Q true
| reflect_false : Q -> reflect P Q false.

Inductive semi_reflect (P : Prop) : bool -> Type :=
  | semi_reflect_true : P -> semi_reflect P true
  | semi_reflect_false : semi_reflect P false.

Lemma iff_to_reflect {A B} (P : A -> B -> Prop) (T : A -> B -> bool)  :
  (forall x y, T x y = true <-> P x y) ->
  (forall x y, reflect (P x y) (~P x y) (T x y)).
Proof.
  intros. case_eq (T x y); intros Hxy; constructor.
  rewrite <- H; auto.
  intros Hf;   rewrite <- H, Hxy in Hf; discriminate.
Qed.

Lemma impl_to_semireflect {A B} (P : A -> B -> Prop) (T : A -> B -> bool)  :
  (forall x y, T x y = true -> P x y) ->
  (forall x y, semi_reflect (P x y) (T x y)).
Proof.
  intros. case_eq (T x y); intros Hxy; constructor.
  apply H; auto.
Qed.

Lemma reflect_true_inv P Q : reflect P Q true -> P.
Proof.
  exact (fun x => match x in reflect _ _ b
                    return if b then P else ID
                 with | reflect_true H => H | reflect_false H => (fun _ x => x) end).
Qed.

Lemma reflect_false_inv P Q : reflect P Q false -> Q.
Proof.
  exact (fun x => match x in reflect _ _ b
                    return if b then ID else Q
                 with | reflect_true H => fun _ x => x | reflect_false H => H end).
Qed.

Lemma semi_reflect_true_inv P : semi_reflect P true -> P.
Proof.
  exact (fun x => match x in semi_reflect _ b
                    return if b then P else ID
                 with | semi_reflect_true H => H | semi_reflect_false => (fun _ x => x) end).
Qed.

Class Reflect (T : bool) (P Q : Prop) := _Reflect : reflect P Q T.
Class SemiReflect (T : bool) (P : Prop) := _SemiReflect : semi_reflect P T.

Section boolean_logic.
  Ltac t :=
    repeat match goal with
           | H: Reflect true ?P ?Q |- _ => apply (reflect_true_inv P Q) in H
           | H: Reflect false ?P ?Q |- _ => apply (reflect_false_inv P Q) in H
           end.

  Context {T1 T2 P1 Q1 P2 Q2} {R1 : Reflect T1 P1 Q1} {R2: Reflect T2 P2 Q2}.

  Global Instance Reflect_andb : Reflect (T1 && T2)%bool (P1 /\ P2) (Q1 \/ Q2).
  Proof.
    destruct T1; destruct T2; t; constructor; tauto.
  Qed.

  Global Instance Reflect_orb : Reflect (T1 || T2)%bool (P1 \/ P2) (Q1 /\ Q2).
  Proof.
    destruct T1; destruct T2; t; constructor; tauto.
  Qed.

  Global Instance Reflect_negb : Reflect (negb T1)%bool Q1 P1.
  Proof.
    destruct T1; t; constructor; tauto.
  Qed.

End boolean_logic.

Require Coq.Arith.Arith.
Section reflect_peano.

  Global Instance Reflect_eqb_nat x y : Reflect (EqNat.beq_nat x y) (x = y) (x <> y).
  Proof.
    apply iff_to_reflect.
    apply EqNat.beq_nat_true_iff.
  Qed.

  Global Instance Reflect_leb_nat x y : Reflect (NPeano.leb x y) (x <= y) (y < x).
  Proof.
    intros. case_eq (NPeano.leb x y); intros; constructor.
    apply NPeano.leb_le in H; auto.
    destruct (Compare_dec.le_lt_dec x y); auto.
    exfalso.
    apply NPeano.leb_le in l; auto. congruence.
  Qed.

  Global Instance Reflect_ltb_nat x y : Reflect (NPeano.ltb x y) (x < y) (y <= x).
  Proof.
    intros. case_eq (NPeano.ltb x y); intros; constructor.
    apply NPeano.ltb_lt in H; auto.
    destruct (Compare_dec.le_lt_dec y x); auto.
    exfalso.
    apply NPeano.ltb_lt in l; auto. congruence.
  Qed.
End reflect_peano.

(** The main tactic. [consider f] will perform case-analysis (using
[case]) on the function symbol [f] using a reflection-lemma that is
inferred by type-class resolution. *)

Ltac consider f :=
  let rec clean :=
    match goal with
      | |- true = true -> _ => intros _ ; clean
      | |- false = true -> _ => discriminate
      | |- ?P1 -> ?P2 =>
        let H := fresh in intros H ; clean; revert H
      | |- _ => idtac
    end
  in
  (repeat match goal with
            | [ H : context [ f ] |- _ ] =>
              revert H
          end) ;
  match type of f with
    | sumbool _ _ =>
      destruct f
    | _ =>
      match goal with
        | _ =>
          ((let c := constr:(_ : Reflect f _ _) in
            case c;
            let H := fresh in
            intros H; try rewrite H; revert H))
        | _ =>
          ((let c := constr:(_ : SemiReflect f _) in
            case c;
            let H := fresh in
            try (intros H; try rewrite H; revert H)))
        | _ =>
          (** default to remembering the equality **)
          case_eq f
      end
  end ; clean.

(**  Some tests *)
Section test.
  Require Import Coq.Numbers.Natural.Peano.NPeano Coq.Bool.Bool.

  Require Import Coq.omega.Omega.
  Goal forall x y z,  (ltb x y && ltb y z) = true ->
                 ltb x z = true.
  intros x y z.
  consider (ltb x y && ltb y z).
  consider (ltb x z); auto. intros. exfalso. omega.
  Qed.

  Goal forall x y z,
    ltb x y = true ->
    ltb y z = true ->
    ltb x z = true.
  Proof.
    intros. consider (ltb x y); consider (ltb y z); consider (ltb x z); intros; auto.
    exfalso; omega.
  Qed.

End test.

(** A more powerful tactic that takes as argument a tuple of functions
  symbols, and use the fact that some reflection lemmas have been declared for them *)

(* NOT YET PORTED
Ltac t L :=
  let rec foo l :=
      match l with
        | (?t,?q) => case (_test (t _)); foo q
        | (?t,?q) => case (_test (t _ _)); foo q
        | (?t,?q) => case (_test (t _ _ _)); foo q
        | (?t,?q) => case (_test (t _ _ _ _)); foo q

        | tt => idtac
      end  in
    foo L;
  intros;
  repeat match goal with
           | H : true = true |- _ => clear H
           | H : false = false |- _ => clear H
           | H : true = false |- _ => clear - H; discriminate
           | H : false = true |- _ => clear - H; discriminate
         end.
*)


Require Export SystemFR.Notations.
Require Export SystemFR.Evaluator.
Require Extraction.
Import Notations.UnTyped.

Definition ackermann_example := Eval compute in
  [|
   let ackermann :=
       def_rec ack m n =>
       match m with
       | 0 => (s n)
       | s m' => match n with
                | 0 => ack m' 1
                | s n' => ack m' (ack m n') end
       end
   in
   ackermann 2 2
    |].

Eval compute in eval ackermann_example 1000.

Example ackermann : (eval ackermann_example 1000) =  Some (succ (succ (succ (succ (succ (succ (succ zero))))))). (* 7 *)
Proof.
  native_compute; reflexivity. Qed.

(*
(* Extraction *)
Extraction Language Ocaml.
Set Extraction AccessOpaque.
Extraction "ackermann.ml" ackermann_example eval.
*)


Variable S : Set.

(* Using Theorem from 11.6.18 in Paper notes *)

Definition R X : Type := S -> X.
Definition W X : Type := S * X.

Definition R_fun {X Y} (f : X -> Y) (p : R X) : R Y :=
  fun s => f (p s).

Definition W_fun {X Y} (f : X -> Y) (p : W X) : W Y :=
  match p with (s, x) => (s, f x) end.

Definition eta {X} : X -> R (W X) :=
  fun x => (fun s => (s, x)).

Definition delta {X} : W (R X) -> R (W X) :=
  fun p => match p with (s, q) => (fun s' => (s', q(s))) end.

Definition epsilon' {X} : R (R (W X)) -> R X:=
  fun p => (fun s => match p s s with (s, x) => x end).

Require Import FunctionalExtensionality.

Lemma prop1 {X} (p : R X): (R_fun delta) (eta p) = R_fun eta p.
Proof.
  unfold R_fun, delta, eta. extensionality s. extensionality s'. reflexivity.
Qed.

Lemma prop2 {X} (p : R X) : epsilon' ((R_fun eta) p) = p.
Proof.
  unfold epsilon', R_fun, eta. extensionality s. reflexivity.
Qed.

Lemma prop3 {X} (p : R (W X)) : p = epsilon' (R_fun delta (R_fun (W_fun eta) p)).
Proof.
  unfold epsilon', R_fun, delta, W_fun, eta. extensionality s.
  destruct (p s). reflexivity.
Qed.

Definition mu {X} (p : R (W (R (W X)))) : R (W X) := epsilon' ( R_fun delta p).

Definition mu' {X} (p : R (W (R (W X)))) : R (W X).
  unfold R, W in *. intros. apply p in H. destruct H. apply p0 in s. apply s.
Defined.

Lemma mu_correct {X} (p : R (W (R (W X)))) : mu p = mu' p.
  extensionality s. unfold mu, mu', epsilon', R_fun, delta.
  destruct (p s). reflexivity.
Qed.


Module Overloading_of_notations.

Record myeq := Myeq {
  carrier : Set ;
  myequality : carrier -> carrier -> bool }.

About myequality.
(* take as a first argument a complete instance of a record myeq *)

Notation "a '===' b" := (myequality _ a b) (at level 70).

Fail Check (true === false).

Require Bool.

Print Bool.eqb.

Check (Myeq bool Bool.eqb : myeq).

(* register an instance of myeq for booleans as canonical: *)

Canonical Structure myeq_bool := Myeq bool Bool.eqb.

(* => Coq will insert Bool.eqb automatically based on type information *)

Check (true === false).
Unset Printing Notations.
Check (true === false).
Set Printing Notations.
Eval compute in (true === false).

(* the same with natural numbers *)

Fail Check (O === 1).

Require Arith.

Check EqNat.beq_nat.

(* exo15: register an instance of myeq for natual numbers as canonical
and check that one can still use the notation "==" *)

End Overloading_of_notations.

Module Eqtype_example.

(* overloading of notation + equivalence with Leibniz equality *)

Record myeq := Eqtype {
  carrier : Set ;
  myequality : carrier -> carrier -> bool ;
  Hmyequality : forall x y : carrier, myequality x y = true <-> x = y }.

Notation "a '===' b" := (myequality _ a b) (at level 70).

Canonical Structure eqtypenat := Eqtype _ _ EqNat.beq_nat_true_iff.

Canonical Structure eqtypebool := Eqtype _ _ Bool.eqb_true_iff.

Check O : nat.
Check (O : carrier _).

Coercion is_true : bool >-> Sortclass.

Require Import ssreflect.

Goal forall x y : bool, x === y -> x = y.
move=> x y.
by move/Bool.eqb_true_iff.
Undo 1.
move/Hmyequality.
done.
Qed.

Goal forall x y : nat, x === y -> x = y.
move=> x y.
Fail by move/Bool.eqb_true_iff.
by move/EqNat.beq_nat_true_iff.
Undo 1.
move/Hmyequality.
done.
Qed.

(* -> we have the same proof for booleans and natural numbers *)

End Eqtype_example.

Module unicity_of_identity_proofs.

(* in Coq, two proofs of the same Prop facts can be considered as equal
   (proof-irrelevance is admissible in Coq) *)
Variable H1 : O < 3.
Variable H2 : O < 3.
Goal H1 = H2.
Fail reflexivity.
Require ProofIrrelevance.
now apply ProofIrrelevance.proof_irrelevance.
Qed.

(* in Coq, we can prove the unicity of equality proofs when the type has a decidable
  equality, so that proof-irrelevance does not need to be admitted; for example, in the
  case of booleans: *)

Lemma eq_symK : forall (A : Type) (a b : A) (e : a = b), eq_sym (eq_sym e) = e.
Proof.
intros A a b e.
destruct e.
simpl.
reflexivity.
Qed.

Lemma buip : forall (b1 b2 : bool) (p1 p2 : (b1 = b2 : Prop)), p1 = p2.
Proof.
intros b1 b2 p1 p2.
destruct p1.
Fail destruct p2.
Undo 1.
pose (fun b (e : b1 = b) =>
        match Bool.bool_dec b1 b with
          | left H => H
          | right _ => e end) as test_against_b1.
cutrewrite (p1 = test_against_b1 b2 p1).
  cutrewrite (p2 = test_against_b1 b2 p2).
    unfold test_against_b1.
    destruct p1.
    destruct b1; simpl; reflexivity.
  destruct p2.
  unfold test_against_b1.
  destruct b1; simpl; reflexivity.
destruct p1.
unfold test_against_b1.
destruct b1; simpl; reflexivity.
Qed.

Variable lt : nat -> nat -> bool.
Check (lt 0 3) : bool.
Variable H1' : lt O 3 = true.
Variable H2' : lt O 3 = true.

Goal H1' = H2'.
Fail reflexivity.
apply buip.
Abort.

End unicity_of_identity_proofs.


Require Import stdpp.base.
Require Import stdpp.sets.
Require Import stdpp.list. (* has some list definitions *)
Require Import stdpp.decidable.
Require Import stdpp.tactics.

Require Import Coq.Logic.Eqdep_dec. (* logical facts *)
Require Import Coq.Lists.List.
Import ListNotations.

Require Import LocalTactics.

(* Several facts about decidable equality and list lookups

   I originally did this myself, as it has poor support in
   Coq's stdlib, especially for the set version, but

  eventually moved it over the Iris's std++, so this is mostly remapping names from my EqDecision to EqDecision *)

(* Type-level decidable equality *)
Definition decEq `{EqDecision X}: forall (x1 x2: X), {x1 = x2} + {x1 <> x2}
  :=
    fun x1 x2 => decide (x1 = x2).

Instance decEq_list {A} `(EqDecision A) : EqDecision (list A).
Proof.
  unfold EqDecision. intros.
  generalize dependent y.
  induction x; induction y; try solve [right; discriminate].
  - left. reflexivity.
  - destruct (decEq a a0) as [-> | a_neq]; destruct (IHx y) as [-> | rest_neq];
      solve [left; reflexivity] ||
            right; intro; inversion H; subst; contradiction.
Qed.

Instance decEq_nat : EqDecision nat.
Proof.
  unfold EqDecision. intro x.
  induction x; induction y.
  - left. reflexivity.
  - right. discriminate.
  - right. discriminate.
  - destruct (IHx y).
    + left. subst. reflexivity.
    + right. intro H. inversion H. contradiction.
Qed.

Definition dec_eq_to_prop : forall {X} {x1 x2: X},
    {x1 = x2} + {x1 <> x2} -> x1 = x2 \/ x1 <> x2.
Proof.
  intros. destruct H; auto.
Qed.

Theorem decEq_refl : forall {X} `{EqDecision X} (x: X),
    decEq x x = left eq_refl.
Proof.
  intros. destruct (decEq x x).
  - (* by Hedberg's Theorem *)
    f_equal.
    refine (K_dec _ (fun (e': x = x) => e' = eq_refl) eq_refl e).
    intros. apply dec_eq_to_prop.
    apply decide. apply EqDecision0.
  - contradiction.
Qed.

Lemma if_decEq_neq : forall {X T} `{EqDecision X} (x y: X),
    forall {t1 t2: T},
    x <> y ->
    (if decEq x y then t1 else t2) = t2.
Proof.
  intros.
  forced (decEq x y).
  reflexivity.
Qed.

Ltac elim_decEq :=
  match goal with
  | H : context [@decide (?x = ?x)] |- _ => rewrite (@decEq_refl _ _ x) in H
  | H : context [@decEq _ _ ?x ?x] |- _ => rewrite (@decEq_refl _ _ x) in H
  | |- context [@decide (?x = ?x)] => rewrite (@decEq_refl _ _ x)
  | |- context [@decEq _ _ ?x ?x] => rewrite (@decEq_refl _ _ x)
  | H : ?x <> ?y |- context [if @decEq _ _ ?x ?y then ?a else ?b] => rewrite -> (if_decEq_neq x y H)
  | H : ?y <> ?x |- context [if @decEq _ _ ?x ?y then ?a else ?b] => rewrite -> (if_decEq_neq x y (not_eq_sym H))
  | |- context [if @decEq _ _ ?x ?x then ?a else ?b] => rewrite -> (@decEq_refl _ _ x)
  end.

Hint Extern 2 => elim_decEq : decEq.

(*

List membership definitions and facts, especially for decidable data

*)

Definition member {X} `{EqDecision X}
           (x: X) (xs: list X): {In x xs} + {~ In x xs}.
Proof.
  intros.
  induction xs.
  - right. apply in_nil.
  - simpl. destruct (decEq a x).
    + left. left. assumption.
    + destruct IHxs.
      * left. right. assumption.
      * right. unfold not. intros []; contradiction.
Defined.

Instance search {X Y} `{EqDecision X} : Lookup X Y (list (X * Y))
  :=
    fix search (x: X) (ps: list (X * Y)) {struct ps} :=
    match ps with
    | nil => None
    | (x', y) :: ps' =>
      if decEq x x'
      then Some y
      else search x ps'
    end.

(* Not strictly related, but useful *)
Lemma In_map_fst {X Y} : forall (x: X) (y: Y) ps,
    In (x, y) ps ->
    In x (map fst ps).
Proof with eauto.
  intros.
  induction ps...
  destruct H; subst; simpl in *.
  - left...
  - right...
Qed.
Hint Resolve In_map_fst : searches.
Hint Extern 1 (_ !! _ = _) => unfold lookup : searches.
Hint Resolve -> elem_of_list_In : searches.
Hint Resolve <- elem_of_list_In : searches.

Lemma In_map_fst_In {X Y} : forall (x: X) (ps: list (X * Y)),
    In x (map fst ps) ->
    exists y, In (x, y) ps.
Proof with auto.
  intros.
  induction ps...
  simpl in H.
  { contradiction. }
  destruct a.
  destruct H; subst...
  - exists y. simpl...
  - destruct (IHps H) as [y' ?].
    exists y'. right...
Qed.

Theorem In_search {X Y} `{EqDecision X}:
  forall (x: X) (y: Y) ps,
    NoDup (map fst ps) ->
    In (x, y) ps ->
    search x ps = Some y.
Proof with eauto with searches.
  intros.
  induction ps.
  - contradiction.
  - simpl in *. destruct a.
    destruct (decEq x x0) as [-> | neq]; simpl in *.
    + destruct H0.
      * congruence.
      * inversion H; subst.
        -- rewrite <- elem_of_list_In in H0.
           absurd (elem_of x0 (map fst ps))...
    + inversion H; subst.
      apply IHps...
      (* x <> x0 *)
      forced H0...
Qed.

Theorem In_fst_search :
  forall {X Y} `{EqDecision X} x (ps: list (X * Y)),
    In x (map fst ps) -> { y : Y & search x ps = Some y }.
Proof.
  intros.
  induction ps.
  - contradiction.
  - simpl in *. destruct a.
    destruct (decEq x x0) as [-> | neq]; simpl in *.
    + eexists. reflexivity.
    + apply IHps. destruct H as [->|?]; done.
Qed.

Theorem In_fst_search_not_None :
  forall {X Y} `{EqDecision X} x (ps: list (X * Y)),
    In x (map fst ps) -> search x ps <> None.
Proof.
  intros.
  destruct (In_fst_search x ps H).
  congruence.
Qed.

Theorem search_In :
  forall {X Y} `{EqDecision X} x y (ps: list (X * Y)),
    search x ps = Some y -> In (x, y) ps.
Proof with eauto.
  intros.
  induction ps; simpl in *; try discriminate.
  destruct a; subst.
  destruct (decEq x x0) as [->|?]...
  simplify_eq. left...
Qed.

Theorem not_In_fst_search :
  forall {X Y} `{EqDecision X} x (ps: list (X * Y)),
    ~ In x (map fst ps) -> search x ps = None.
Proof with eauto.
  intros.
  destruct (search x ps) eqn:eqsearch...
  apply search_In in eqsearch.
  contradict H.
  eauto with searches.
Qed.

Hint Rewrite @In_search : searches.
Hint Resolve @In_search search_In : searches.
Hint Resolve @In_fst_search @In_fst_search_not_None @search_In : searches.
Hint Rewrite @not_In_fst_search : searches.

Theorem In_if_member :
  forall {X Y} `{EqDecision X}
    (x: X) (xs: list X) (et ef: Y),
    In x xs ->
    (if member x xs then et else ef) = et.
Proof.
  intros.
  destruct (member x xs); reflexivity || contradiction.
Qed.

Theorem not_In_if_member :
  forall {X Y} `{EqDecision X}
    (x: X) (xs: list X) (et ef: Y),
    (~ In x xs) ->
    (if member x xs then et else ef) = ef.
Proof.
  intros.
  destruct (member x xs); reflexivity || contradiction.
Qed.

Hint Rewrite @In_if_member : searches.
Hint Rewrite @not_In_if_member : searches.

(* useful tactic to prove In *)
Hint Resolve in_eq.
Hint Resolve in_eq : searches.

Lemma In_map_snd :
  forall {X Y},
    forall y (xs: list (X * Y)),
      In y (map snd xs) ->
      exists x,
        In (x, y) xs.
Proof with eauto.
  intros.
  induction xs.
  { destruct H. } (* otherwise eauto shelves *)
  simpl in *.
  destruct H.
  - destruct a as [a ?].
    simplify_eq.
    exists a...
  - destruct (IHxs H) as [x inx].
    exists x. right...
Qed.

Hint Resolve In_map_snd : searches.

Lemma Forall2_nth :
  forall {A B} (P: A -> B -> Prop) xs ys i x y,
    Forall2 P xs ys ->
    nth_error xs i = Some x ->
    nth_error ys i = Some y ->
    P x y.
Proof with eauto.
  intros. generalize dependent i.
  induction H; intros i xi yi.
  - destruct i; simpl in xi; discriminate.
  - destruct i; simpl nth_error in *.
    + simplify_eq...
    + eapply IHForall2...
Qed.

Hint Rewrite @Forall2_nth : searches.

Fixpoint map_option {X Y} (f: X -> option Y) (xs: list X):
  option (list Y)
  :=
    match xs with
    | [] => Some []
    | (x :: xs) =>
      match f x with
      | Some v =>
        match map_option f xs with
        | Some vs => Some (v :: vs)
        | None => None
        end
      | None => None
      end
    end.

Definition map_with_in {X Y} (xs: list X) (f: forall (x: X), In x xs -> Y): list Y.
  induction xs as [| x xs ].
  - exact [].
  - apply cons.
    + apply (f x); repeat constructor.
    + apply IHxs. intros.
      apply (f x0). simpl.
      right. assumption.
Defined.

Theorem map_option_all_some : forall
    {X Y} (f: X -> option Y) xs
    (getY: forall x,
        In x xs ->
        { y : Y &
              f x = Some y }),
    map_option f xs =
    Some (map_with_in xs (fun y i => projT1 (getY y i))).
Proof.
  intros.
  induction xs as [| x xs]; simpl.
  - reflexivity.
  - pose (fun x i0 => getY x (or_intror i0))
         as getY'.
    rewrite -> (IHxs getY').
    destruct (getY x _) as [ y fxy ].
    rewrite -> fxy.
    reflexivity.
Qed.

Fixpoint filter_map {X Y} (f: X -> option Y) (xs: list X): list Y
  :=
    match xs with
    | [] => []
    | (x :: xs) =>
      match f x with
      | Some y => y :: filter_map f xs
      | None => filter_map f xs
      end
    end.
Instance elem_of_filter_map {X Y} {f: X -> option Y} {xs: list X} : SetUnfoldElemOf (y:Y) (filter_map f xs : list Y) (exists x, elem_of x xs /\ f x = Some y).
Proof with eauto.
  intros. split.
  rewrite -> elem_of_list_In.
  split; intros.
  - induction xs; simpl in H.
    + contradiction.
    + destruct (f a) eqn:fa.
      * simpl in H. destruct H; subst...
        -- exists a. split... set_solver.
        -- destruct IHxs... deprod.
           exists x. split...
           set_solver.
      * destruct IHxs... deprod.
        exists x. split...
        set_solver.
  - deprod. rewrite -> elem_of_list_In in H.
    induction xs...
    simpl. destruct H; subst...
    + rewrite -> H0...
    + destruct (f a)...
      right...
Qed.

Lemma map_option_length {X Y Z}:
  forall (f: X -> option Y) (g: X -> option Z)
         xs ys1 ys2,
  map_option f xs = Some ys1 ->
  map_option g xs = Some ys2 ->
  length ys1 = length ys2.
Proof with eauto.
  intros f g xs.
  induction xs;
    simpl map_option;
    intros; simplify_eq...
  forced (f a).
  forced (map_option f xs).
  forced (g a).
  forced (map_option g xs).
  simplify_eq. simpl. f_equal.
  apply IHxs...
Qed.

Lemma filter_map_in {X Y} :
  forall (f: X -> option Y) x xs,
    In x (filter_map f xs) <->
    In (Some x) (map f xs).
Proof with eauto.
  intros.
  split; induction xs; simpl; intros...
  (* -> cons *)
  - destruct (f a)...
    + destruct H; subst...
  (* <- cons *)
  - destruct H.
    + rewrite -> H...
    + destruct (f a)...
      right...
Qed.
Hint Resolve -> filter_map_in : searches.
Hint Resolve <- filter_map_in : searches.

Lemma map_compose {X Y Z}:
  forall (f: Y -> Z) (g: X -> Y) xs,
    map f (map g xs) = map (fun x => f (g x)) xs.
Proof with eauto.
  intros.
  induction xs; simpl; f_equal...
Qed.

Lemma in_map_option_retract {X Y}:
  forall (f: X -> option Y) (g: Y -> X),
    (forall x y,
        f x = Some y ->
        x = g y) ->
    forall y xs,
    In (Some y) (map f xs) ->
    In (g y) xs.
Proof with eauto.
  intros.
  induction xs; simpl in H0 |- *...
  destruct H0.
  - left. apply H...
  - right...
Qed.

Lemma search_app :
  forall {X Y} `{EqDecision X} (ps1 ps2 : list (X * Y)) x y,
    search x ps1 = Some y ->
    search x (ps1 ++ ps2) = Some y.
Proof with eauto.
  intros.
  induction ps1; simpl in *...
  - discriminate.
  - destruct a.
    destruct (decEq x x0)...
Qed.
Hint Resolve search_app : searches.

Lemma In_pair_unique :
  forall {X Y} (ps : list (X * Y)) x y1 y2,
    NoDup (map fst ps) ->
    In (x, y1) ps ->
    In (x, y2) ps ->
    y1 = y2.
Proof with eauto.
  intros.
  induction ps.
  - contradiction H0.
  - simpl in H0, H1.
    inversion H; subst.
    destruct H0, H1.
    + congruence.
    + simplify_eq.
      contradict H4; eauto with searches.
    + simplify_eq.
      contradict H4; eauto with searches.
    + apply IHps...
Qed.

Hint Resolve In_pair_unique : searches.

Lemma In_submseteq :
  forall {X} (l1 l2 : list X) (x: X),
    submseteq l1 l2 ->
    In x l1 ->
    In x l2.
Proof with auto.
  intros.
  repeat rewrite <- elem_of_list_In in *.
  apply elem_of_submseteq with l1...
Qed.

Lemma In_sublist :
  forall {X} (l1 l2 : list X) (x: X),
    sublist l1 l2 ->
    In x l1 ->
    In x l2.
Proof with auto.
  intros.
  apply In_submseteq with l1...
  apply sublist_submseteq...
Qed.

Lemma In_drop :
  forall {X} (l : list X) (x: X) (n: nat),
    In x (drop n l) -> In x l.
Proof with auto.
  intros.
  apply In_sublist with (drop n l)...
  apply sublist_drop.
Qed.

Lemma ix_In :
  forall {X} (l: list X) (i: nat) (x: X),
    l !! i = Some x ->
    In x l.
Proof.
  intros. rewrite <- elem_of_list_In.
  apply elem_of_list_lookup_2 with i.
  exact H.
Qed.

Lemma NoDup_drop :
  forall {X} (l: list X) (n: nat),
    NoDup l ->
    NoDup (drop n l).
Proof with auto.
  intros. generalize dependent l.
  induction n; intros.
  - rewrite -> drop_0...
  - replace (S n) with (1 + n) by reflexivity.
    rewrite <- (drop_drop l n 1).
    apply IHn...
    inversion H...
    simpl. constructor.
Qed.

Lemma map_drop :
  forall {X Y} (f: X -> Y) (l: list X) (n: nat),
    map f (drop n l) = drop n (map f l).
Proof with auto.
  intros.
  generalize dependent n.
  induction l; intros.
  - destruct n...
  - destruct n.
    + rewrite -> drop_0...
    + simpl...
Qed.

Hint Resolve ix_In : searches.

Lemma take_S_exists :
  forall {X} (xs: list X) (n: nat),
    length xs >= S n ->
    { x: X & xs = take n xs ++ [x] ++ drop (S n) xs }.
Proof with eauto.
  intros. generalize dependent xs.
  induction n; intros xs len.
  - simpl. destruct xs... exfalso. inversion len.
  - destruct xs.
    + exfalso. inversion len.
    + simpl in *.
      apply le_S_n in len.
      destruct (IHn xs len).
      exists x0.
      f_equal. assumption.
Qed.

Definition searches {X V} `{EqDecision X} (xs: list X) (e : list (X * V)) : option (list V)
  := map_option (flip search e) xs.

Lemma In_searches {X V} `{EqDecision X} xs (e: list (X * V)) vs v :
  searches xs e = Some vs ->
  In v vs ->
  exists (x : X), In x xs /\ e !! x = Some v.
Proof with eauto.
  intros.
  unfold searches in *.
  generalize dependent vs.
  induction xs; intros; simpl...
  - inversion H; subst; contradiction.
  - simpl in H.
    forced (search a e).
    forced (map_option (flip search e) xs).
    simplify_eq.
    destruct H0...
    + subst. exists a. eauto.
    + destruct (IHxs l eq_refl H).
      deprod. exists x...
Qed.

Lemma filter_map_ext_in {X Y} (f g: X -> option Y) (xs: list X) :
  forall (ext: forall x, In x xs -> f x = g x), filter_map f xs = filter_map g xs.
Proof with eauto.
  intros.
  induction xs...
  simpl.
  replace (g a) with (f a).
  rewrite -> IHxs.
  reflexivity.
  - intros. apply ext. right...
  - apply ext...
Qed.