(** * Basics: Functional Programming in Coq *)

(* This library definition is included here temporarily
   for backward compatibility with Coq 8.3.
   Please ignore. *)
Definition admit {T: Type} : T.  Admitted.

(* ###################################################################### *)
(** * Introduction *)

(** The functional programming style brings programming closer to
    mathematics: If a procedure or method has no side effects, then
    pretty much all you need to understand about it is how it maps
    inputs to outputs -- that is, you can think of its behavior as
    just computing a mathematical function.  This is one reason for
    the word "functional" in "functional programming."  This direct
    connection between programs and simple mathematical objects
    supports both sound informal reasoning and formal proofs of
    correctness.

    The other sense in which functional programming is "functional" is
    that it emphasizes the use of functions (or methods) as
    _first-class_ values -- i.e., values that can be passed as
    arguments to other functions, returned as results, stored in data
    structures, etc.  The recognition that functions can be treated as
    data in this way enables a host of useful idioms, as we will see.

    Other common features of functional languages include _algebraic
    data types_ and _pattern matching_, which make it easy to construct
    and manipulate rich data structures, and sophisticated
    _polymorphic type systems_ that support abstraction and code
    reuse.  Coq shares all of these features.
*)

(* ###################################################################### *)
(** * Enumerated Types *)

(** One unusual aspect of Coq is that its set of built-in
    features is _extremely_ small.  For example, instead of providing
    the usual palette of atomic data types (booleans, integers,
    strings, etc.), Coq offers an extremely powerful mechanism for
    defining new data types from scratch -- so powerful that all these
    familiar types arise as instances.

    Naturally, the Coq distribution comes with an extensive standard
    library providing definitions of booleans, numbers, and many
    common data structures like lists and hash tables.  But there is
    nothing magic or primitive about these library definitions: they
    are ordinary user code.

    To see how this works, let's start with a very simple example. *)

(* ###################################################################### *)
(** ** Days of the Week *)

(** The following declaration tells Coq that we are defining
    a new set of data values -- a _type_. *)

Inductive day : Type :=
  | monday : day
  | tuesday : day
  | wednesday : day
  | thursday : day
  | friday : day
  | saturday : day
  | sunday : day.

(** The type is called [day], and its members are [monday],
    [tuesday], etc.  The second through eighth lines of the definition
    can be read "[monday] is a [day], [tuesday] is a [day], etc."

    Having defined [day], we can write functions that operate on
    days. *)

Definition next_weekday (d:day) : day :=
  match d with
  | monday    => tuesday
  | tuesday   => wednesday
  | wednesday => thursday
  | thursday  => friday
  | friday    => monday
  | saturday  => monday
  | sunday    => monday
  end.

(** One thing to note is that the argument and return types of
    this function are explicitly declared.  Like most functional
    programming languages, Coq can often work out these types even if
    they are not given explicitly -- i.e., it performs some _type
    inference_ -- but we'll always include them to make reading
    easier. *)

(** Having defined a function, we should check that it works on
    some examples.  There are actually three different ways to do this
    in Coq.  First, we can use the command [Eval compute] to evaluate a
    compound expression involving [next_weekday].  *)

Eval compute in (next_weekday friday).
   (* ==> monday : day *)
Eval compute in (next_weekday (next_weekday saturday)).
   (* ==> tuesday : day *)

(** If you have a computer handy, now would be an excellent
    moment to fire up the Coq interpreter under your favorite IDE --
    either CoqIde or Proof General -- and try this for yourself.  Load
    this file ([Basics.v]) from the book's accompanying Coq sources,
    find the above example, submit it to Coq, and observe the
    result. *)

(** The keyword [compute] tells Coq precisely how to
    evaluate the expression we give it.  For the moment, [compute] is
    the only one we'll need; later on we'll see some alternatives that
    are sometimes useful. *)

(** Second, we can record what we _expect_ the result to be in
    the form of a Coq example: *)

Example test_next_weekday:
  (next_weekday (next_weekday saturday)) = tuesday.

(** This declaration does two things: it makes an
    assertion (that the second weekday after [saturday] is [tuesday]),
    and it gives the assertion a name that can be used to refer to it
    later. *)
(** Having made the assertion, we can also ask Coq to verify it,
    like this: *)

Proof. simpl. reflexivity.  Qed.

(** The details are not important for now (we'll come back to
    them in a bit), but essentially this can be read as "The assertion
    we've just made can be proved by observing that both sides of the
    equality evaluate to the same thing, after some simplification." *)

(** Third, we can ask Coq to "extract," from a [Definition], a
    program in some other, more conventional, programming
    language (OCaml, Scheme, or Haskell) with a high-performance
    compiler.  This facility is very interesting, since it gives us a
    way to construct _fully certified_ programs in mainstream
    languages.  Indeed, this is one of the main uses for which Coq was
    developed.  We'll come back to this topic in later chapters.
    More information can also be found in the Coq'Art book by Bertot
    and Casteran, as well as the Coq reference manual. *)

(* ###################################################################### *)
(** ** Booleans *)

(** In a similar way, we can define the type [bool] of booleans,
    with members [true] and [false]. *)

Inductive bool : Type :=
  | true : bool
  | false : bool.

(** Although we are rolling our own booleans here for the sake
    of building up everything from scratch, Coq does, of course,
    provide a default implementation of the booleans in its standard
    library, together with a multitude of useful functions and
    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library
    documentation if you're interested.)  Whenever possible, we'll
    name our own definitions and theorems so that they exactly
    coincide with the ones in the standard library. *)

(** Functions over booleans can be defined in the same way as
    above: *)

Definition negb (b:bool) : bool :=
  match b with
  | true => false
  | false => true
  end.

Definition andb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => b2
  | false => false
  end.

Definition orb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => true
  | false => b2
  end.

(** The last two illustrate the syntax for multi-argument
    function definitions. *)

(** The following four "unit tests" constitute a complete
    specification -- a truth table -- for the [orb] function: *)

Example test_orb1:  (orb true  false) = true.
Proof. reflexivity.  Qed.
Example test_orb2:  (orb false false) = false.
Proof. reflexivity.  Qed.
Example test_orb3:  (orb false true)  = true.
Proof. reflexivity.  Qed.
Example test_orb4:  (orb true  true)  = true.
Proof. reflexivity.  Qed.

(** (Note that we've dropped the [simpl] in the proofs.  It's not
    actually needed because [reflexivity] will automatically perform
    simplification.) *)

(** _A note on notation_: We use square brackets to delimit
    fragments of Coq code in comments in .v files; this convention,
    also used by the [coqdoc] documentation tool, keeps them visually
    separate from the surrounding text.  In the html version of the
    files, these pieces of text appear in a [different font]. *)

(** The values [Admitted] and [admit] can be used to fill
    a hole in an incomplete definition or proof.  We'll use them in the
    following exercises.  In general, your job in the exercises is
    to replace [admit] or [Admitted] with real definitions or proofs. *)

(** **** Exercise: 1 star (nandb) *)
(** Complete the definition of the following function, then make
    sure that the [Example] assertions below can each be verified by
    Coq.  *)

(** This function should return [true] if either or both of
    its inputs are [false]. *)

Definition nandb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => negb b2
  | false => true
  end.

(** Remove "[Admitted.]" and fill in each proof with
    "[Proof. reflexivity. Qed.]" *)

Example test_nandb1:               (nandb true false) = true.
Proof. reflexivity.  Qed.
Example test_nandb2:               (nandb false false) = true.
Proof. reflexivity.  Qed.
Example test_nandb3:               (nandb false true) = true.
Proof. reflexivity.  Qed.
Example test_nandb4:               (nandb true true) = false.
Proof. reflexivity.  Qed.
(** [] *)

(** **** Exercise: 1 star (andb3) *)
(** Do the same for the [andb3] function below. This function should
    return [true] when all of its inputs are [true], and [false]
    otherwise. *)

Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  andb (andb b1 b2) b3.

Example test_andb31:                 (andb3 true true true) = true.
Proof. reflexivity.  Qed.
Example test_andb32:                 (andb3 false true true) = false.
Proof. reflexivity.  Qed.
Example test_andb33:                 (andb3 true false true) = false.
Proof. reflexivity.  Qed.
Example test_andb34:                 (andb3 true true false) = false.
Proof. reflexivity.  Qed.
(** [] *)

(* ###################################################################### *)
(** ** Function Types *)

(** The [Check] command causes Coq to print the type of an
    expression.  For example, the type of [negb true] is [bool]. *)

Check true.
(* ===> true : bool *)
Check (negb true).
(* ===> negb true : bool *)

(** Functions like [negb] itself are also data values, just like
    [true] and [false].  Their types are called _function types_, and
    they are written with arrows. *)

Check negb.
(* ===> negb : bool -> bool *)

(** The type of [negb], written [bool -> bool] and pronounced
    "[bool] arrow [bool]," can be read, "Given an input of type
    [bool], this function produces an output of type [bool]."
    Similarly, the type of [andb], written [bool -> bool -> bool], can
    be read, "Given two inputs, both of type [bool], this function
    produces an output of type [bool]." *)

(* ###################################################################### *)
(** ** Numbers *)

(** _Technical digression_: Coq provides a fairly sophisticated
    _module system_, to aid in organizing large developments.  In this
    course we won't need most of its features, but one is useful: If
    we enclose a collection of declarations between [Module X] and
    [End X] markers, then, in the remainder of the file after the
    [End], these definitions will be referred to by names like [X.foo]
    instead of just [foo].  Here, we use this feature to introduce the
    definition of the type [nat] in an inner module so that it does
    not shadow the one from the standard library. *)

Module Playground1.

(** The types we have defined so far are examples of "enumerated
    types": their definitions explicitly enumerate a finite set of
    elements.  A more interesting way of defining a type is to give a
    collection of "inductive rules" describing its elements.  For
    example, we can define the natural numbers as follows: *)

Inductive nat : Type :=
  | O : nat
  | S : nat -> nat.

(** The clauses of this definition can be read:
      - [O] is a natural number (note that this is the letter "[O]," not
	the numeral "[0]").
      - [S] is a "constructor" that takes a natural number and yields
	another one -- that is, if [n] is a natural number, then [S n]
	is too.

    Let's look at this in a little more detail.

    Every inductively defined set ([day], [nat], [bool], etc.) is
    actually a set of _expressions_.  The definition of [nat] says how
    expressions in the set [nat] can be constructed:

    - the expression [O] belongs to the set [nat];
    - if [n] is an expression belonging to the set [nat], then [S n]
      is also an expression belonging to the set [nat]; and
    - expressions formed in these two ways are the only ones belonging
      to the set [nat].

    The same rules apply for our definitions of [day] and [bool]. The
    annotations we used for their constructors are analogous to the
    one for the [O] constructor, and indicate that each of those
    constructors doesn't take any arguments. *)

(** These three conditions are the precise force of the
    [Inductive] declaration.  They imply that the expression [O], the
    expression [S O], the expression [S (S O)], the expression
    [S (S (S O))], and so on all belong to the set [nat], while other
    expressions like [true], [andb true false], and [S (S false)] do
    not.

    We can write simple functions that pattern match on natural
    numbers just as we did above -- for example, the predecessor
    function: *)

Definition pred (n : nat) : nat :=
  match n with
    | O => O
    | S n' => n'
  end.

(** The second branch can be read: "if [n] has the form [S n']
    for some [n'], then return [n']."  *)

End Playground1.

Definition minustwo (n : nat) : nat :=
  match n with
    | O => O
    | S O => O
    | S (S n') => n'
  end.

(** Because natural numbers are such a pervasive form of data,
    Coq provides a tiny bit of built-in magic for parsing and printing
    them: ordinary arabic numerals can be used as an alternative to
    the "unary" notation defined by the constructors [S] and [O].  Coq
    prints numbers in arabic form by default: *)

Check (S (S (S (S O)))).
Eval simpl in (minustwo 4).

(** The constructor [S] has the type [nat -> nat], just like the
    functions [minustwo] and [pred]: *)

Check S.
Check pred.
Check minustwo.

(** These are all things that can be applied to a number to yield a
    number.  However, there is a fundamental difference: functions
    like [pred] and [minustwo] come with _computation rules_ -- e.g.,
    the definition of [pred] says that [pred 2] can be simplified to
    [1] -- while the definition of [S] has no such behavior attached.
    Although it is like a function in the sense that it can be applied
    to an argument, it does not _do_ anything at all! *)

(** For most function definitions over numbers, pure pattern
    matching is not enough: we also need recursion.  For example, to
    check that a number [n] is even, we may need to recursively check
    whether [n-2] is even.  To write such functions, we use the
    keyword [Fixpoint]. *)

Fixpoint evenb (n:nat) : bool :=
  match n with
  | O        => true
  | S O      => false
  | S (S n') => evenb n'
  end.

(** We can define [oddb] by a similar [Fixpoint] declaration, but here
    is a simpler definition that will be a bit easier to work with: *)

Definition oddb (n:nat) : bool   :=   negb (evenb n).

Example test_oddb1:    (oddb (S O)) = true.
Proof. reflexivity.  Qed.
Example test_oddb2:    (oddb (S (S (S (S O))))) = false.
Proof. reflexivity.  Qed.

(** Naturally, we can also define multi-argument functions by
    recursion.  (Once again, we use a module to avoid polluting the
    namespace.) *)

Module Playground2.

Fixpoint plus (n : nat) (m : nat) : nat :=
  match n with
    | O => m
    | S n' => S (plus n' m)
  end.

(** Adding three to two now gives us five, as we'd expect. *)

Eval simpl in (plus (S (S (S O))) (S (S O))).

(** The simplification that Coq performs to reach this conclusion can
    be visualized as follows: *)

(*  [plus (S (S (S O))) (S (S O))]
==> [S (plus (S (S O)) (S (S O)))] by the second clause of the [match]
==> [S (S (plus (S O) (S (S O))))] by the second clause of the [match]
==> [S (S (S (plus O (S (S O)))))] by the second clause of the [match]
==> [S (S (S (S (S O))))]          by the first clause of the [match]
*)

(** As a notational convenience, if two or more arguments have
    the same type, they can be written together.  In the following
    definition, [(n m : nat)] means just the same as if we had written
    [(n : nat) (m : nat)]. *)

Fixpoint mult (n m : nat) : nat :=
  match n with
    | O => O
    | S n' => plus m (mult n' m)
  end.

Example test_mult1: (mult 3 3) = 9.
Proof. reflexivity.  Qed.

(** You can match two expressions at once by putting a comma
    between them: *)

Fixpoint minus (n m:nat) : nat :=
  match n, m with
  | O   , _    => O
  | S _ , O    => n
  | S n', S m' => minus n' m'
  end.

(** The _ in the first line is a _wildcard pattern_.  Writing _ in a
    pattern is the same as writing some variable that doesn't get used
    on the right-hand side.  This avoids the need to invent a bogus
    variable name. *)

End Playground2.

Fixpoint exp (base power : nat) : nat :=
  match power with
    | O => S O
    | S p => mult base (exp base p)
  end.

(** **** Exercise: 1 star (factorial) *)
(** Recall the standard factorial function:
<<
    factorial(0)  =  1
    factorial(n)  =  n * factorial(n-1)     (if n>0)
>>
    Translate this into Coq. *)

Fixpoint factorial (n:nat) : nat :=
  match n with
  | O => 1
  | S n' => mult n (factorial n')
  end.

Example test_factorial1:          (factorial 3) = 6.
Proof. reflexivity.  Qed.
Example test_factorial2:          (factorial 5) = (mult 10 12).
Proof. reflexivity.  Qed.
(** [] *)

(** We can make numerical expressions a little easier to read and
    write by introducing "notations" for addition, multiplication, and
    subtraction. *)

Notation "x + y" := (plus x y)
		       (at level 50, left associativity)
		       : nat_scope.
Notation "x - y" := (minus x y)
		       (at level 50, left associativity)
		       : nat_scope.
Notation "x * y" := (mult x y)
		       (at level 40, left associativity)
		       : nat_scope.

Check ((0 + 1) + 1).

(** (The [level], [associativity], and [nat_scope] annotations
   control how these notations are treated by Coq's parser.  The
   details are not important, but interested readers can refer to the
   "More on Notation" subsection in the "Optional Material" section at
   the end of this chapter.) *)

(** Note that these do not change the definitions we've already
    made: they are simply instructions to the Coq parser to accept [x
    + y] in place of [plus x y] and, conversely, to the Coq
    pretty-printer to display [plus x y] as [x + y]. *)

(** When we say that Coq comes with nothing built-in, we really
    mean it: even equality testing for numbers is a user-defined
    operation! *)
(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,
    yielding a [b]oolean.  Note the use of nested [match]es (we could
    also have used a simultaneous match, as we did in [minus].)  *)

Fixpoint beq_nat (n m : nat) : bool :=
  match n with
  | O => match m with
	 | O => true
	 | S m' => false
	 end
  | S n' => match m with
	    | O => false
	    | S m' => beq_nat n' m'
	    end
  end.

(** Similarly, the [ble_nat] function tests [nat]ural numbers for
    [l]ess-or-[e]qual, yielding a [b]oolean. *)

Fixpoint ble_nat (n m : nat) : bool :=
  match n with
  | O => true
  | S n' =>
      match m with
      | O => false
      | S m' => ble_nat n' m'
      end
  end.

Example test_ble_nat1:             (ble_nat 2 2) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat2:             (ble_nat 2 4) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat3:             (ble_nat 4 2) = false.
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars (blt_nat) *)
(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,
    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for
    this one, define it in terms of a previously defined function.

    Note: If you have trouble with the [simpl] tactic, try using
    [compute], which is like [simpl] on steroids.  However, there is a
    simple, elegant solution for which [simpl] suffices. *)

Definition blt_nat (n m : nat) : bool :=
  (andb (negb (beq_nat n m)) (ble_nat n m)).

Example test_blt_nat1:             (blt_nat 2 2) = false.
Proof. reflexivity.  Qed.
Example test_blt_nat2:             (blt_nat 2 4) = true.
Proof. reflexivity.  Qed.
Example test_blt_nat3:             (blt_nat 4 2) = false.
Proof. reflexivity.  Qed.
(** [] *)

(* ###################################################################### *)
(** * Proof by Simplification *)

(** Now that we've defined a few datatypes and functions, let's
    turn to the question of how to state and prove properties of their
    behavior.  Actually, in a sense, we've already started doing this:
    each [Example] in the previous sections makes a precise claim
    about the behavior of some function on some particular inputs.
    The proofs of these claims were always the same: use [reflexivity]
    to check that both sides of the [=] simplify to identical values.

    (By the way, it will be useful later to know that
    [reflexivity] actually does somewhat more than [simpl] -- for
    example, it tries "unfolding" defined terms, replacing them with
    their right-hand sides.  The reason for this difference is that,
    when reflexivity succeeds, the whole goal is finished and we don't
    need to look at whatever expanded expressions [reflexivity] has
    found; by contrast, [simpl] is used in situations where we may
    have to read and understand the new goal, so we would not want it
    blindly expanding definitions.)

    The same sort of "proof by simplification" can be used to prove
    more interesting properties as well.  For example, the fact that
    [0] is a "neutral element" for [+] on the left can be proved
    just by observing that [0 + n] reduces to [n] no matter what
    [n] is, a fact that can be read directly off the definition of [plus].*)

Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof.
  intros n. reflexivity.  Qed.

(** (_Note_: You may notice that the above statement looks
    different in the original source file and the final html output. In Coq
    files, we write the [forall] universal quantifier using the
    "_forall_" reserved identifier. This gets printed as an
    upside-down "A", the familiar symbol used in logic.)  *)

(** The form of this theorem and proof are almost exactly the
    same as the examples above; there are just a few differences.

    First, we've used the keyword keyword [Theorem] instead of
    [Example].  Indeed, the latter difference is purely a matter of
    style; the keywords [Example] and [Theorem] (and a few others,
    including [Lemma], [Fact], and [Remark]) mean exactly the same
    thing to Coq.

    Secondly, we've added the quantifier [forall n:nat], so that our
    theorem talks about _all_ natural numbers [n].  In order to prove
    theorems of this form, we need to to be able to reason by
    _assuming_ the existence of an arbitrary natural number [n].  This
    is achieved in the proof by [intros n], which moves the quantifier
    from the goal to a "context" of current assumptions. In effect, we
    start the proof by saying "OK, suppose [n] is some arbitrary number."

    The keywords [intros], [simpl], and [reflexivity] are examples of
    _tactics_.  A tactic is a command that is used between [Proof] and
    [Qed] to tell Coq how it should check the correctness of some
    claim we are making.  We will see several more tactics in the rest
    of this lecture, and yet more in future lectures. *)

(** Step through these proofs in Coq and notice how the goal and
    context change. *)

Theorem plus_1_l : forall n:nat, 1 + n = S n.
Proof.
  intros n. reflexivity.  Qed.

Theorem mult_0_l : forall n:nat, 0 * n = 0.
Proof.
  intros n. reflexivity.  Qed.

(** The [_l] suffix in the names of these theorems is
    pronounced "on the left." *)

(* ###################################################################### *)
(** * Proof by Rewriting *)

(** Here is a slightly more interesting theorem: *)

Theorem plus_id_example : forall n m:nat,
  n = m ->
  n + n = m + m.

(** Instead of making a completely universal claim about all numbers
    [n] and [m], this theorem talks about a more specialized property
    that only holds when [n = m].  The arrow symbol is pronounced
    "implies."

    As before, we need to be able to reason by assuming the existence
    of some numbers [n] and [m].  We also need to assume the hypothesis
    [n = m]. The [intros] tactic will serve to move all three of these
    from the goal into assumptions in the current context.

    Since [n] and [m] are arbitrary numbers, we can't just use
    simplification to prove this theorem.  Instead, we prove it by
    observing that, if we are assuming [n = m], then we can replace
    [n] with [m] in the goal statement and obtain an equality with the
    same expression on both sides.  The tactic that tells Coq to
    perform this replacement is called [rewrite]. *)

Proof.
  intros n m.   (* move both quantifiers into the context *)
  intros H.     (* move the hypothesis into the context *)
  rewrite -> H. (* Rewrite the goal using the hypothesis *)
  reflexivity.  Qed.

(** The first line of the proof moves the universally quantified
    variables [n] and [m] into the context.  The second moves the
    hypothesis [n = m] into the context and gives it the (arbitrary)
    name [H].  The third tells Coq to rewrite the current goal ([n + n
    = m + m]) by replacing the left side of the equality hypothesis
    [H] with the right side.

    (The arrow symbol in the [rewrite] has nothing to do with
    implication: it tells Coq to apply the rewrite from left to right.
    To rewrite from right to left, you can use [rewrite <-].  Try
    making this change in the above proof and see what difference it
    makes in Coq's behavior.) *)

(** **** Exercise: 1 star (plus_id_exercise) *)
(** Remove "[Admitted.]" and fill in the proof. *)

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
  intros n m o H1 H2.
  rewrite -> H1.
  rewrite -> H2.
  reflexivity.  Qed.
(** [] *)

(** As we've seen in earlier examples, the [Admitted] command
    tells Coq that we want to skip trying to prove this theorem and
    just accept it as a given.  This can be useful for developing
    longer proofs, since we can state subsidiary facts that we believe
    will be useful for making some larger argument, use [Admitted] to
    accept them on faith for the moment, and continue thinking about
    the larger argument until we are sure it makes sense; then we can
    go back and fill in the proofs we skipped.  Be careful, though:
    every time you say [Admitted] (or [admit]) you are leaving a door
    open for total nonsense to enter Coq's nice, rigorous, formally
    checked world! *)

(** We can also use the [rewrite] tactic with a previously proved
    theorem instead of a hypothesis from the context. *)

Theorem mult_0_plus : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  rewrite -> plus_O_n.
  reflexivity.  Qed.

(** **** Exercise: 2 stars (mult_S_1) *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  intros n m H.
  rewrite -> plus_1_l.
  rewrite <- H.
  reflexivity.  Qed.
(** [] *)

(* ###################################################################### *)
(** * Proof by Case Analysis *)

(** Of course, not everything can be proved by simple
    calculation: In general, unknown, hypothetical values (arbitrary
    numbers, booleans, lists, etc.) can block the calculation.
    For example, if we try to prove the following fact using the
    [simpl] tactic as above, we get stuck. *)

Theorem plus_1_neq_0_firsttry : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n.
  simpl.  (* does nothing! *)
Abort.

(** The reason for this is that the definitions of both
    [beq_nat] and [+] begin by performing a [match] on their first
    argument.  But here, the first argument to [+] is the unknown
    number [n] and the argument to [beq_nat] is the compound
    expression [n + 1]; neither can be simplified.

    What we need is to be able to consider the possible forms of [n]
    separately.  If [n] is [O], then we can calculate the final result
    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].
    And if [n = S n'] for some [n'], then, although we don't know
    exactly what number [n + 1] yields, we can calculate that, at
    least, it will begin with one [S], and this is enough to calculate
    that, again, [beq_nat (n + 1) 0] will yield [false].

    The tactic that tells Coq to consider, separately, the cases where
    [n = O] and where [n = S n'] is called [destruct]. *)

Theorem plus_1_neq_0 : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n. destruct n as [| n'].
    reflexivity.
    reflexivity.  Qed.

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem as
    proved.  (No special command is needed for moving from one subgoal
    to the other.  When the first subgoal has been proved, it just
    disappears and we are left with the other "in focus.")  In this
    proof, each of the subgoals is easily proved by a single use of
    [reflexivity].

    The annotation "[as [| n']]" is called an _intro pattern_.  It
    tells Coq what variable names to introduce in each subgoal.  In
    general, what goes between the square brackets is a _list_ of
    lists of names, separated by [|].  Here, the first component is
    empty, since the [O] constructor is nullary (it doesn't carry any
    data).  The second component gives a single name, [n'], since [S]
    is a unary constructor.

    The [destruct] tactic can be used with any inductively defined
    datatype.  For example, we use it here to prove that boolean
    negation is involutive -- i.e., that negation is its own
    inverse. *)

Theorem negb_involutive : forall b : bool,
  negb (negb b) = b.
Proof.
  intros b. destruct b.
    reflexivity.
    reflexivity.  Qed.

(** Note that the [destruct] here has no [as] clause because
    none of the subcases of the [destruct] need to bind any variables,
    so there is no need to specify any names.  (We could also have
    written [as [|]], or [as []].)  In fact, we can omit the [as]
    clause from _any_ [destruct] and Coq will fill in variable names
    automatically.  Although this is convenient, it is arguably bad
    style, since Coq often makes confusing choices of names when left
    to its own devices. *)

(** **** Exercise: 1 star (zero_nbeq_plus_1) *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.
Proof.
  intros n. destruct n as [| n'].
    reflexivity.
    reflexivity.  Qed.
(** [] *)

(* ###################################################################### *)
(** * More Exercises *)

(** **** Exercise: 2 stars (boolean functions) *)
(** Use the tactics you have learned so far to prove the following
    theorem about boolean functions. *)

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros f H b.
  rewrite -> H.
  rewrite -> H.
  reflexivity.  Qed.

(** Now state and prove a theorem [negation_fn_applied_twice] similar
    to the previous one but where the second hypothesis says that the
    function [f] has the property that [f x = negb x].*)

Theorem negation_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = negb x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros f H b.
  rewrite -> H.
  rewrite -> H.
  rewrite -> negb_involutive.
  reflexivity.  Qed.

(** **** Exercise: 2 stars (andb_eq_orb) *)
(** Prove the following theorem.  (You may want to first prove a
    subsidiary lemma or two.) *)

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  intros b c. destruct b as [| b'].
    simpl. intros H. rewrite -> H. reflexivity.
    simpl. intros H. rewrite -> H. reflexivity.  Qed.

(** **** Exercise: 3 stars (binary) *)
(** Consider a different, more efficient representation of natural
    numbers using a binary rather than unary system.  That is, instead
    of saying that each natural number is either zero or the successor
    of a natural number, we can say that each binary number is either

      - zero,
      - twice a binary number, or
      - one more than twice a binary number.

    (a) First, write an inductive definition of the type [bin]
	corresponding to this description of binary numbers.

    (Hint: Recall that the definition of [nat] from class,
    Inductive nat : Type :=
      | O : nat
      | S : nat -> nat.
    says nothing about what [O] and [S] "mean."  It just says "[O] is
    in the set called [nat], and if [n] is in the set then so is [S
    n]."  The interpretation of [O] as zero and [S] as successor/plus
    one comes from the way that we _use_ [nat] values, by writing
    functions to do things with them, proving things about them, and
    so on.  Your definition of [bin] should be correspondingly simple;
    it is the functions you will write next that will give it
    mathematical meaning.)

    (b) Next, write an increment function for binary numbers, and a
	function to convert binary numbers to unary numbers.

    (c) Write some unit tests for your increment and binary-to-unary
	functions. Notice that incrementing a binary number and
	then converting it to unary should yield the same result as first
	converting it to unary and then incrementing.
*)

Inductive bin : Type :=
  | Z : bin
  | T : bin -> bin
  | M : bin -> bin.

Fixpoint inc (b : bin) : bin :=
  match b with
  | Z    => M Z         (* 0      -> 1        *)
  | T b' => M b'        (* 2n     -> 2n + 1   *)
  | M b' => T (inc b')  (* 2n + 1 -> 2(n + 1) *)
  end.

Fixpoint bin2nat (b : bin) : nat :=
  match b with
  | Z    => O
  | T b' => (bin2nat b') * 2
  | M b' => S ((bin2nat b') * 2)
  end.

Example test_bin1: bin2nat (inc (T (M (M Z)))) = 7.
Proof. reflexivity.  Qed.
Example test_bin2: bin2nat (inc (T (M (T (T Z))))) = S (bin2nat (T (M (T (T Z))))).
Proof. reflexivity.  Qed.
(** [] *)

(* ###################################################################### *)
(** * Optional Material *)

(** ** More on Notation *)

Notation "x + y" := (plus x y)
		       (at level 50, left associativity)
		       : nat_scope.
Notation "x * y" := (mult x y)
		       (at level 40, left associativity)
		       : nat_scope.

(** For each notation-symbol in Coq we can specify its _precedence level_
    and its _associativity_. The precedence level n can be specified by the
    keywords [at level n] and it is helpful to disambiguate
    expressions containing different symbols. The associativity is helpful
    to disambiguate expressions containing more occurrences of the same
    symbol. For example, the parameters specified above for [+] and [*]
    say that the expression [1+2*3*4] is a shorthand for the expression
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.

    Each notation-symbol in Coq is also active in a _notation scope_.
    Coq tries to guess what scope you mean, so when you write [S(O*O)]
    it guesses [nat_scope], but when you write the cartesian
    product (tuple) type [bool*bool] it guesses [type_scope].
    Occasionally you have to help it out with percent-notation by
    writing [(x*y)%nat], and sometimes in Coq's feedback to you it
    will use [%nat] to indicate what scope a notation is in.

    Notation scopes also apply to numeral notation (3,4,5, etc.), so you
    may sometimes see [0%nat] which means [O], or [0%Z] which means the
    Integer zero.
*)

(** ** [Fixpoint]s and Structural Recursion *)

Fixpoint plus' (n : nat) (m : nat) : nat :=
  match n with
    | O => m
    | S n' => S (plus' n' m)
  end.

(** When Coq checks this definition, it notes that [plus'] is
    "decreasing on 1st argument."  What this means is that we are
    performing a _structural recursion_ over the argument [n] -- i.e.,
    that we make recursive calls only on strictly smaller values of
    [n].  This implies that all calls to [plus'] will eventually
    terminate.  Coq demands that some argument of _every_ [Fixpoint]
    definition is "decreasing".

    This requirement is a fundamental feature of Coq's design: In
    particular, it guarantees that every function that can be defined
    in Coq will terminate on all inputs.  However, because Coq's
    "decreasing analysis" is not very sophisticated, it is sometimes
    necessary to write functions in slightly unnatural ways. *)

(** **** Exercise: 2 stars, optional (decreasing) *)
(** To get a concrete sense of this, find a way to write a sensible
    [Fixpoint] definition (of a simple function on numbers, say) that
    _does_ terminate on all inputs, but that Coq will _not_ accept
    because of this restriction. *)

(*
Fixpoint plus'' (n m : nat) : nat :=
  match n with
  | O => m
  | S n' => S (plus'' (n - 1) m)
  end.
*)
(** [] *)

(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)


(**************************************************************************
* TLC: A library for Coq                                                  *
* Reflection between booleans and propositions                            *
**************************************************************************)

Set Implicit Arguments.
From TLC Require Import LibTactics.
From TLC Require Export LibBool LibLogic.

Implicit Type P : Prop.
Implicit Type b : bool.

(* ********************************************************************** *)
(** * Reflection between booleans and propositions *)

(** - [istrue b] produces a proposition that is [True] if and only if
      the boolean [b] is equal to [true].

    - [isTrue P] produces a boolean expression that is [true] if and only
      if the proposition [P] is equal to [True]. *)

(* ---------------------------------------------------------------------- *)
(** ** Translation from booleans into propositions *)

(** Any boolean [b] can be viewed as a proposition through the
    relation [b = true]. *)

Coercion istrue (b : bool) : Prop := (b = true).

(** Specification *)

Lemma istrue_eq_eq_true : forall b,
  istrue b = (b = true).
Proof using. reflexivity. Qed.

Lemma istrue_true_eq :
  istrue true = True.
Proof using. rewrite istrue_eq_eq_true. extens*. Qed.

Lemma istrue_false_eq :
  istrue false = False.
Proof using. rewrite istrue_eq_eq_true. extens. iff; auto_false. Qed.

Global Opaque istrue.

(** Proving the goals [true] and [~ false] *)

Lemma istrue_true : istrue true. (* [true] *)
Proof using. reflexivity. Qed.

Lemma not_istrue_false : ~ (istrue false). (* ~ false. *)
Proof using. rewrite istrue_false_eq. intuition. Qed.

(** Equivalence of [false] and [False] *)

Lemma false_of_False :
  False ->
  false.
Proof using. intros K. false. Qed.

Lemma False_of_false :
  false ->
  False.
Proof using. intros K. rewrite~ istrue_false_eq in K. Qed.

(** Hints for proving [false] and [False] *)

Hint Resolve istrue_true not_istrue_false.

Hint Extern 1 (istrue false) =>
  apply false_of_False.

Hint Extern 1 (False) => match goal with
  | H: istrue false |- _ => apply (not_istrue_false H) end.

(* ---------------------------------------------------------------------- *)
(** ** Translation from propositions into booleans *)

(** The expression [isTrue P] evaluates to [true] if and only if
    the proposition [P] is [True]. *)

Definition isTrue (P : Prop) : bool :=
  If P then true else false.

(** Specification *)

Lemma isTrue_eq_if : forall P,
  isTrue P = If P then true else false.
Proof using. reflexivity. Qed.

Lemma isTrue_True :
  isTrue True = true.
Proof using. unfolds. case_if; auto_false~. Qed.

Lemma isTrue_False :
  isTrue False = false.
Proof using. unfolds. case_if; auto_false~. Qed.

Global Opaque isTrue.

(** Lemmas *)

Lemma isTrue_eq_true : forall P,
  P ->
  isTrue P = true.
Proof using. intros. rewrite isTrue_eq_if. case_if*. Qed.

Lemma isTrue_eq_false : forall P,
  ~ P ->
  isTrue P = false.
Proof using. intros. rewrite isTrue_eq_if. case_if*. Qed.

(* ---------------------------------------------------------------------- *)
(** ** Extensionality for boolean equality, stated using [istrue] *)

Lemma bool_ext : forall b1 b2,
  (b1 <-> b2) ->
  b1 = b2.
Proof using.
  destruct b1; destruct b2; intros; auto_false.
  destruct H. false H; auto.
  destruct H. false H0; auto.
Qed.

Lemma bool_ext_eq : forall b1 b2,
  (b1 = b2) = (b1 <-> b2).
Proof using.
  intros. extens. iff M. { subst*. } { applys* bool_ext. }
Qed.

Instance Extensionality_bool : Extensionality bool.
Proof using. apply (Extensionality_make bool_ext). Defined.

(* ********************************************************************** *)
(** * Rewriting rules *)

(* ---------------------------------------------------------------------- *)
(** ** Rewriting rules for distributing [istrue] *)

Lemma istrue_isTrue_eq : forall P,
  istrue (isTrue P) = P.
Proof using. extens. rewrite isTrue_eq_if. case_if; auto_false*. Qed.

Lemma istrue_neg_eq : forall b,
  istrue (!b) = ~ (istrue b).
Proof using. extens. tautob. Qed.

Lemma istrue_and_eq : forall b1 b2,
  istrue (b1 && b2) = (istrue b1 /\ istrue b2).
Proof using. extens. tautob. Qed.

Lemma istrue_or_eq : forall b1 b2,
  istrue (b1 || b2) = (istrue b1 \/ istrue b2).
Proof using. extens. tautob. Qed.

(** Corollary *)

Lemma istrue_neg_isTrue : forall P,
  istrue (! isTrue P) = ~ P.
Proof using. intros. rewrite istrue_neg_eq. rewrite~ istrue_isTrue_eq. Qed.

(** [istrue] and conditionals *)

Lemma If_istrue : forall b A (x y : A),
    (If istrue b then x else y)
  = (if b then x else y).
Proof using. intros. case_if as C; case_if as D; auto. Qed.

Lemma istrue_If_eq : forall P b1 b2,
    istrue (If P then b1 else b2)
  = (If P then istrue b1 else istrue b2).
Proof using. extens. case_if*. Qed.

Lemma istrue_if_eq : forall b1 b2 b3,
    istrue (if b1 then b2 else b3)
  = (If istrue b1 then istrue b2 else istrue b3).
Proof using. intros. do 2 case_if; auto. Qed.

(* ---------------------------------------------------------------------- *)
(** ** Rewriting rules for distributing [isTrue] *)

Lemma isTrue_istrue : forall b,
  isTrue (istrue b) = b.
Proof using. extens. rewrite* istrue_isTrue_eq. Qed.

Lemma isTrue_not : forall P,
  isTrue (~ P) = ! isTrue P.
Proof using. extens. do 2 rewrite isTrue_eq_if. do 2 case_if; auto_false*. Qed.

Lemma isTrue_and : forall P1 P2,
  isTrue (P1 /\ P2) = (isTrue P1 && isTrue P2).
Proof using. extens. do 3 rewrite isTrue_eq_if. do 3 case_if; auto_false*. Qed.

Lemma isTrue_or : forall P1 P2,
  isTrue (P1 \/ P2) = (isTrue P1 || isTrue P2).
Proof using. extens. do 3 rewrite isTrue_eq_if. do 3 case_if; auto_false*. Qed.

(** Corollary *)

Lemma isTrue_not_istrue : forall b,
  isTrue (~ istrue b) = !b.
Proof using. intros. rewrite isTrue_not. rewrite~ isTrue_istrue. Qed.

(** Simplification of equalities involving isTrue *)

Section IsTrueEqualities.

Ltac prove_isTrue_lemma :=
  intros; try extens; try iff; rewrite isTrue_eq_if in *; case_if; auto_false*.

Lemma true_eq_isTrue_eq : forall P,
  (true = isTrue P) = P.
Proof using. prove_isTrue_lemma. Qed.

Lemma isTrue_eq_true_eq : forall P,
  (isTrue P = true) = P.
Proof using. prove_isTrue_lemma. Qed.

Lemma false_eq_isTrue_eq : forall P,
  (false = isTrue P) = ~ P.
Proof using. prove_isTrue_lemma. Qed.

Lemma isTrue_eq_false_eq : forall P,
  (isTrue P = false) = ~ P.
Proof using. prove_isTrue_lemma. Qed.

Lemma isTrue_eq_isTrue_eq : forall P1 P2,
  (isTrue P1 = isTrue P2) = (P1 <-> P2).
Proof using.
  intros. extens. iff; repeat rewrite isTrue_eq_if in *;
  repeat case_if; auto_false*.
Qed.

End IsTrueEqualities.

(** [isTrue] and conditionals *)

Lemma if_isTrue : forall P A (x y : A),
    (if isTrue P then x else y)
  = (If P then x else y).
Proof using.
  intros. case_if as C; case_if as D; auto.
  { rewrite* isTrue_eq_true_eq in C. }
  { rewrite* isTrue_eq_false_eq in C. }
Qed.

Lemma isTrue_If : forall P1 P2 P3,
    isTrue (If P1 then P2 else P3)
  = If P1 then isTrue P2 else isTrue P3.
Proof using. extens. case_if*. Qed.

Lemma isTrue_If_eq_if_isTrue : forall P1 P2 P3,
    isTrue (If P1 then P2 else P3)
  = (if isTrue P1 then isTrue P2 else isTrue P3).
Proof using. intros. rewrite if_isTrue. rewrite~ isTrue_If. Qed.

(* ---------------------------------------------------------------------- *)
(** ** Lemmas for testing booleans *)

Lemma bool_inv_or : forall b,
  b \/ !b.
Proof using. tautob. Qed.

Lemma bool_inv_or_eq : forall b,
  b = true \/ b = false.
Proof using. tautob. Qed.

Lemma xor_inv_or : forall b1 b2,
  xor b1 b2 ->
     (b1 = true /\ b2 = false)
  \/ (b1 = false /\ b2 = true).
Proof using. tautob; auto_false*. Qed.

Arguments xor_inv_or [b1] [b2].

(* ---------------------------------------------------------------------- *)
(** ** Lemmas for normalizing [b = true] and [b = false] terms *)

Lemma bool_eq_true_eq : forall b,
  (b = true) = istrue b.
Proof using. extens. tautob. Qed.

Lemma bool_eq_false_eq : forall b,
  (b = false) = istrue (!b).
Proof using. extens. tautob. Qed.

Lemma true_eq_bool_eq : forall b,
  (true = b) = istrue b.
Proof using. extens. tautob. Qed.

Lemma false_eq_bool_eq : forall b,
  (false = b) = istrue (!b).
Proof using. extens. tautob. Qed.

(* ********************************************************************** *)
(** * Tactics *)

(* ---------------------------------------------------------------------- *)
(** ** Tactics [rew_istrue] to distribute [istrue] *)

(** [rew_istrue] distributes [istrue]. It is useful to replace all
    boolean operators with corresponding logical operators. *)

Hint Rewrite istrue_true_eq istrue_false_eq istrue_isTrue_eq
  istrue_neg_eq istrue_and_eq istrue_or_eq
  If_istrue istrue_If_eq istrue_if_eq: rew_istrue.

Tactic Notation "rew_istrue" :=
  autorewrite with rew_istrue.
Tactic Notation "rew_istrue" "in" hyp(H) :=
  autorewrite with rew_istrue in H.
Tactic Notation "rew_istrue" "in" "*" :=
  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_istrue).
  (* autorewrite with rew_istrue in *. *)

Tactic Notation "rew_istrue" "~" :=
  rew_istrue; auto_tilde.
Tactic Notation "rew_istrue" "~" "in" hyp(H) :=
  rew_istrue in H; auto_tilde.
Tactic Notation "rew_istrue" "~" "in" "*" :=
  rew_istrue in *; auto_tilde.

Tactic Notation "rew_istrue" "*" :=
  rew_istrue; auto_star.
Tactic Notation "rew_istrue" "*" "in" hyp(H) :=
  rew_istrue in H; auto_star.
Tactic Notation "rew_istrue" "*" "in" "*" :=
  rew_istrue in *; auto_star.

(* ---------------------------------------------------------------------- *)
(** ** Tactics [rew_isTrue] to distribute [isTrue] *)

(** [rew_isTrue] distributes [isTrue].
    This tactic is probably much less useful than [rew_istrue], since logical
    operators are often simpler to work with. *)

Hint Rewrite isTrue_True isTrue_False isTrue_istrue
  isTrue_not isTrue_and isTrue_or
  if_isTrue isTrue_If : rew_isTrue.

Tactic Notation "rew_isTrue" :=
  autorewrite with rew_isTrue.
Tactic Notation "rew_isTrue" "in" hyp(H) :=
  autorewrite with rew_isTrue in H.
Tactic Notation "rew_isTrue" "in" "*" :=
  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_isTrue).
  (* autorewrite with rew_isTrue in *. *)

Tactic Notation "rew_isTrue" "~" :=
  rew_isTrue; auto_tilde.
Tactic Notation "rew_isTrue" "~" "in" hyp(H) :=
  rew_isTrue in H; auto_tilde.
Tactic Notation "rew_isTrue" "~" "in" "*" :=
  rew_isTrue in *; auto_tilde.

Tactic Notation "rew_isTrue" "*" :=
  rew_isTrue; auto_star.
Tactic Notation "rew_isTrue" "*" "in" hyp(H) :=
  rew_isTrue in H; auto_star.
Tactic Notation "rew_isTrue" "*" "in" "*" :=
  rew_isTrue in *; auto_star.

(* ---------------------------------------------------------------------- *)
(** ** Tactics useful for program verification, when reasoning about
       the result of if-statements over boolean expressions, i.e.
       an expression of the form [b = ..] or [.. = b], which produces
       hypotheses of the form [true = ..] and [false = ..] or symmetric.
       It is used as post-treatment for tactic [case_if]. *)

Hint Rewrite
  true_eq_isTrue_eq isTrue_eq_true_eq
  false_eq_isTrue_eq isTrue_eq_false_eq
  isTrue_eq_isTrue_eq
  not_not_eq
  istrue_true_eq istrue_false_eq istrue_isTrue_eq
  istrue_neg_eq istrue_and_eq istrue_or_eq
  bool_eq_true_eq bool_eq_false_eq true_eq_bool_eq false_eq_bool_eq
  : rew_bool_eq.

Tactic Notation "rew_bool_eq" :=
  autorewrite with rew_bool_eq.
Tactic Notation "rew_bool_eq" "~" :=
  rew_bool_eq; auto_tilde.
Tactic Notation "rew_bool_eq" "*" :=
  rew_bool_eq; auto_star.

Tactic Notation "rew_bool_eq" "in" hyp(H) :=
  autorewrite with rew_bool_eq in H.
Tactic Notation "rew_bool_eq" "~" "in" hyp(H) :=
  rew_bool_eq in H; auto_tilde.
Tactic Notation "rew_bool_eq" "*" "in" hyp(H) :=
  rew_bool_eq in H; auto_star.

Tactic Notation "rew_bool_eq" "in" "*" :=
  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_bool_eq).
  (* autorewrite with rew_bool_eq in *. *)
Tactic Notation "rew_bool_eq" "~" "in" "*" :=
  rew_bool_eq; auto_tilde.
Tactic Notation "rew_bool_eq" "*" "in" "*" :=
  rew_bool_eq; auto_star.

(* ---------------------------------------------------------------------- *)
(** ** Tactics extended for reflection *)

(** Extension of the tactic [case_if] to automatically performs
    simplification using [logics].

    For less aggressive introduction of [istrue], consider rewriting
    without the lemmas:
    [bool_eq_true_eq bool_eq_false_eq true_eq_bool_eq false_eq_bool_eq]
*)

Ltac case_if_post H ::=
  rew_bool_eq in H; tryfalse.

(** Extension of the tactic [test_dispatch] from LibLogic.v, so as to
    be able to call the tactic [tests] directly on boolean expressions *)

Ltac tests_bool_base E H1 H2 :=
  tests_prop_base (istrue E) H1 H2.

Ltac tests_dispatch E H1 H2 ::=
  match type of E with
  | bool => tests_bool_base E H1 H2
  | Prop => tests_prop_base E H1 H2
  | {_}+{_} => tests_ssum_base E H1 H2
  end.

(** Extension of the tactic [apply_to_head_of] (see LibTactics). *)

Ltac apply_to_head_of E cont ::=
  let go E := let P := get_head E in cont P in
  match E with
  | istrue ?A => go A
  | istrue (neg ?A) => go A
  | ?A = ?B => first [ go A | go B ]
  | ?A => go A
  end.


(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.
From mathcomp Require Import finfun bigop prime binomial ssralg finset fingroup finalg matrix.
Require Import Reals Fourier.
Require Import Reals_ext ssr_ext Rssr log2 tuple_prod Rbigop.
Require Import proba entropy aep typ_seq channel.

Set Implicit Arguments.
Unset Strict Implicit.
Import Prenex Implicits.

Local Open Scope typ_seq_scope.
Local Open Scope channel_scope.
Local Open Scope entropy_scope.
Local Open Scope proba_scope.
(*Local Open Scope tuple_ext_scope.*)

(** * Jointly typical sequences *)

(** Definition of jointly typical sequences: *)

Section joint_typ_seq_definition.

Variables A B : finType.
Variable P : dist A.
Variable W : `Ch_1(A, B).
Variable n : nat.
Variable epsilon : R.

Definition jtyp_seq (t : 'rV[A * B]_n) :=
  typ_seq P epsilon (tuple_prod t).1 &&
  typ_seq (`O(P , W)) epsilon (tuple_prod t).2 &&
  typ_seq (`J(P , W)) epsilon t.

Definition set_jtyp_seq : {set 'rV[A * B]_n} := [set tab | jtyp_seq tab].

Local Notation "'`JTS'" := (set_jtyp_seq).

(** JTS(n,e) is a subset of TS_{P,W}(n,e) such that
   (x,y) \in JTS(n,e) <-> x \in TS_P(n,e) /\ y \in TS_{PW}(n,e) *)

Lemma typical_sequence1_JTS x : prod_tuple x \in `JTS ->
  exp2 (- INR n * (`H P + epsilon)) <= P `^ n x.1 <= exp2 (- INR n * (`H P - epsilon)).
Proof.
rewrite inE.
case/andP=> /andP [].
case/andP=> /RleP JTS11 /RleP JTS12.
move=> _ _.
by rewrite prod_tupleK in JTS11, JTS12.
Qed.

Lemma typical_sequence1_JTS' x : prod_tuple x \in `JTS ->
  exp2 (- INR n * (`H (`O( P , W)) + epsilon)) <= (`O( P , W)) `^ n x.2 <=
  exp2 (- INR n * (`H (`O( P , W)) - epsilon)).
Proof.
rewrite inE.
case/andP => /andP [].
move=> _.
case/andP=> /RleP JTS11 /RleP JTS12.
move=> _.
by rewrite prod_tupleK in JTS11, JTS12.
Qed.

End joint_typ_seq_definition.

Notation "'`JTS'" := (set_jtyp_seq) : jtyp_seq_scope.
Local Open Scope jtyp_seq_scope.

(** Upper-bound for the set of jointly typical sequences: *)

Section jtyp_seq_upper.

Variables A B : finType.
Variable P : dist A.
Variable W : `Ch_1(A, B).
Variable n : nat.
Variable epsilon : R.

Lemma JTS_sup : INR #| `JTS P W n epsilon| <= exp2 (INR n * (`H(P , W) + epsilon)).
Proof.
have H : INR #|`JTS P W n epsilon| <= INR #|`TS (`J(P , W)) n epsilon|.
  have H : `JTS P W n epsilon \subset `TS (`J(P , W)) n epsilon.
    apply/subsetP => tab.
    rewrite /set_jtyp_seq inE /jtyp_seq.
    case/andP => /andP [] _ _.
    by rewrite inE.
  apply le_INR.
  apply/leP.
  by apply subset_leq_card.
eapply Rle_trans; first by apply H.
by apply (@TS_sup _ (`J(P , W)) epsilon n).
Qed.

End jtyp_seq_upper.

Section jtyp_seq_transmitted.

Variable A B : finType.
Variable P : dist A.
Variable W : `Ch_1(A, B).
Variable epsilon : R.

Definition JTS_1_bound :=
  maxn (Zabs_nat (up (aep_bound P (epsilon / 3))))
 (maxn (Zabs_nat (up (aep_bound (`O(P , W)) (epsilon / 3))))
       (Zabs_nat (up (aep_bound (`J(P , W)) (epsilon / 3))))).

Variable n : nat.
Hypothesis He : 0 < epsilon.

(** ## *)

Lemma JTS_1 : (JTS_1_bound <= n)%nat ->
  Pr (`J(P , W) `^ n) (`JTS P W n epsilon) >= 1 - epsilon.
Proof.
have : (JTS_1_bound <= n)%nat ->
  Pr ( `J( P `^ n , W ``^ n) )
    [set x | x.1 \notin `TS P n epsilon] +
  Pr ( `J( P `^ n , W ``^ n) )
    [set x | x.2 \notin `TS (`O(P , W)) n epsilon] +
  Pr ( `J( P `^ n , W ``^ n))
    [set x | prod_tuple x \notin `TS ( `J( P , W) ) n epsilon] <= epsilon.
have H1 m :
  Pr (`J(P , W) `^ m) [set x | (tuple_prod x).1 \notin `TS P m epsilon ] =
  Pr (P `^ m) [set x | x \notin `TS P m epsilon].
  rewrite {1}/Pr.
  rewrite rsum_rV_prod /=.
  rewrite -(@pair_big_fst _ _ _ _ [pred x | x \notin `TS P m epsilon]) //; last first.
    move=> t /=.
    rewrite SetDef.pred_of_setE /= SetDef.finsetE /= ffunE.
    do 2 f_equal.
    apply/matrixP => a b; rewrite {a}(ord1 a).
    by rewrite !mxE.
  rewrite /=.
  transitivity (\rsum_(i | i \notin `TS P m epsilon)
    (P `^ m i * (\rsum_(j in 'rV[B]_m) W ``^ m (j | i)))).
    apply eq_bigr => ta Hta.
    rewrite mulRC big_distrl /=.
    apply eq_bigr => tb _ /=.
    rewrite /DMC.c; unlock => /=.
    rewrite -[in X in _ = X]big_split /=.
    apply eq_bigr => j _.
    rewrite /JointDist.d /= /JointDist.f /=.
    by rewrite -fst_tnth_prod_tuple -snd_tnth_prod_tuple.
  transitivity (\rsum_(i | i \notin `TS P m epsilon) P `^ _ i).
    apply eq_bigr => i Hi.
    by rewrite (pmf1 ( W ``^ m (| i) )) mulR1.
  rewrite /Pr.
  apply eq_bigl => t; by rewrite !inE.
have {H1}H1 : forall n, Pr (`J(P , W) `^ n) [set x | (tuple_prod x).1 \notin `TS P n epsilon ] <=
  Pr (P `^ n) [set x | x \notin `TS P n (epsilon / 3)].
  move=> m.
  have : 1 <= 3 by fourier.
  move/(set_typ_seq_incl P m (Rlt_le _ _ He)) => Hincl.
  apply Rle_trans with (Pr (P `^ m) [set x | x \notin `TS P m epsilon]); last first.
    apply Pr_incl.
    apply/subsetP => i /=; rewrite !inE.
    apply contra.
    move/subsetP in Hincl.
    move: (Hincl i).
    by rewrite !inE.
  rewrite H1.
  by apply Req_le.
have {H1}HnP : forall n, (Zabs_nat (up (aep_bound P (epsilon / 3))) <= n)%nat ->
  Pr (`J(P , W) `^ n) [set x | (tuple_prod x).1 \notin `TS P n epsilon ] <= epsilon /3.
  move=> n0 Hn0.
  eapply Rle_trans; first by apply (H1 n0).
  have n0_prednK : n0.-1.+1 = n0.
    rewrite prednK //.
    apply/ltP.
    apply lt_le_trans with (Zabs_nat (up (aep_bound P (epsilon / 3)))); last first.
      by apply/leP.
    rewrite (_ : O = Zabs_nat 0) //.
    apply Zabs_nat_lt.
    split; first by done.
    apply up_pos, aep_bound_pos.
    fourier.
  have Htmp : Pr (P `^ n0) (`TS P n0 (epsilon/3)) >= 1 - (epsilon / 3).
    rewrite -n0_prednK.
    apply Pr_TS_1 => //.
    - apply Rlt_mult_inv_pos => //; fourier.
    - rewrite n0_prednK.
      move/leP in Hn0.
      apply le_INR in Hn0.
      apply Rle_trans with (INR (Zabs_nat (up (aep_bound P (epsilon / 3))))) => //.
      rewrite INR_Zabs_nat; last first.
        apply Zlt_le_weak, up_pos, aep_bound_pos => //.
        apply Rlt_mult_inv_pos => //; fourier.
      by apply Rlt_le, (proj1 (archimed _ )).
  rewrite Pr_to_cplt.
  set p1 := Pr _ _ in Htmp.
  rewrite (_ : Pr _ _ = p1); last first.
    rewrite /p1; apply Pr_ext; apply/setP => i /=; by rewrite !inE negbK.
  fourier.
have H1 m :
  Pr (`J(P , W) `^ m) [set x | (tuple_prod x).2 \notin `TS ( `O(P , W) ) m epsilon] =
  Pr (( `O(P , W) ) `^ m) (~: `TS ( `O(P , W) ) m epsilon).
  rewrite {1}/Pr rsum_rV_prod /=.
  rewrite -(@pair_big_snd _ _ _ _ [pred x | x \notin `TS (`O(P , W)) m epsilon]) //; last first.
    move=> tab /=.
    rewrite SetDef.pred_of_setE /= SetDef.finsetE /= ffunE. (* NB: clean *)
    do 3 f_equal.
    apply/matrixP => a b; rewrite {a}(ord1 a).
    by rewrite !mxE.
  rewrite /= /Pr /TupleDist.d /= /TupleDist.f /= exchange_big /=.
  apply eq_big => tb.
    by rewrite !inE.
  move=> Htb.
  rewrite bigA_distr_bigA /=.
(* TODO: move *)
Local Open Scope ring_scope.
Local Open Scope vec_ext_scope.
  rewrite (reindex_onto (fun p : 'rV[A]_m => [ffun x => p ord0 x])
    (fun y : {ffun 'I_m -> A} => \row_(i < m) y i)) /=; last first.
    move=> j _.
    apply/ffunP => /= m0.
    by rewrite ffunE mxE.
  apply eq_big => ta.
    rewrite inE; apply/esym.
    by apply/eqP/matrixP => a b; rewrite {a}(ord1 a) mxE ffunE.
  move=> k.
  apply eq_bigr => l _.
  by rewrite /JointDist.f -fst_tnth_prod_tuple -snd_tnth_prod_tuple ffunE.
have {H1}H1 : forall n,
  Pr (`J(P , W) `^ n) [set x | (tuple_prod x).2 \notin `TS ( `O(P , W) ) n epsilon ] <=
  Pr ( (`O( P , W) ) `^ n) (~: `TS ( `O( P , W) ) n (epsilon / 3)).
move=> m.
have : 1 <= 3 by fourier.
move/(set_typ_seq_incl (`O(P , W)) m (Rlt_le _ _ He)) => Hincl.
apply Rle_trans with (Pr ((`O(P , W)) `^ m) (~: `TS (`O(P , W)) m epsilon)); last first.
  apply Pr_incl.
  apply/subsetP => i /=; rewrite !inE.
  apply contra.
  move/subsetP : Hincl.
  move/(_ i).
  by rewrite !inE.
  rewrite H1; by apply Req_le.
have {H1}HnPW : forall n, (Zabs_nat (up (aep_bound (`O(P , W)) (epsilon / 3))) <= n)%nat ->
  Pr (`J(P , W) `^ n) [set x | (tuple_prod x).2 \notin `TS (`O(P , W)) n epsilon] <= epsilon /3.
  move=> n0 Hn0.
  eapply Rle_trans; first by apply (H1 n0).
  have n0_prednK : n0.-1.+1 = n0.
    rewrite prednK //.
    apply/ltP.
    apply lt_le_trans with (Zabs_nat (up (aep_bound (`O(P , W)) (epsilon / 3)))); last first.
      by apply/leP.
    rewrite (_ : O = Zabs_nat 0) //.
    apply Zabs_nat_lt.
    split; first by done.
    apply up_pos, aep_bound_pos; fourier.
  have Htmp : Pr ((`O(P , W)) `^ n0) (`TS (`O(P , W)) n0 (epsilon / 3)) >=
    1 - epsilon / 3.
    rewrite -n0_prednK.
    apply Pr_TS_1 => //.
    - apply Rlt_mult_inv_pos => //; fourier.
    - move/leP in Hn0.
      apply le_INR in Hn0.
      apply Rle_trans with (INR (Zabs_nat (up (aep_bound (`O(P , W)) (epsilon / 3))))) => //.
      + rewrite INR_Zabs_nat; last first.
          apply Zlt_le_weak.
          apply up_pos, aep_bound_pos; fourier.
        apply Rlt_le.
        by apply (proj1 (archimed _ )).
      + by rewrite n0_prednK.
  rewrite Pr_to_cplt.
  set p1 := Pr _ _ in Htmp.
  rewrite (_ : Pr _ _ = p1); last first.
    rewrite /p1; apply Pr_ext; apply/setP => i /=; by rewrite !inE negbK.
  fourier.
have H1 : forall n,
  Pr (`J(P , W) `^ n) (~: `TS (`J(P , W)) n epsilon) <=
  Pr (( `J( P , W) ) `^ n) (~: `TS (`J( P , W)) n (epsilon / 3)).
  move=> m.
  have : 1 <= 3 by fourier.
  move/(set_typ_seq_incl (`J( P , W)) m (Rlt_le _ _ He)) => Hincl.
  apply Rle_trans with (Pr ((`J( P , W)) `^ m) (~: `TS (`J( P , W)) m epsilon)); last first.
    apply Pr_incl.
    apply/subsetP => i /=; rewrite !inE.
    apply contra.
    move/subsetP : Hincl.
    move/(_ i).
    by rewrite !inE.
  by apply Req_le.
have {H1}HnP_W : forall n, (Zabs_nat (up (aep_bound (`J(P , W)) (epsilon / 3))) <= n)%nat ->
  Pr (`J(P , W) `^ n) (~: `TS (`J( P , W)) n epsilon) <= epsilon /3.
  move=> n0 Hn0.
  eapply Rle_trans; first by apply (H1 n0).
  have n0_prednK : n0.-1.+1 = n0.
    rewrite prednK //.
    apply/ltP.
    apply lt_le_trans with (Zabs_nat (up (aep_bound (`J(P , W)) (epsilon / 3)))); last first.
      by apply/leP.
    rewrite (_ : O = Zabs_nat 0) //.
    apply Zabs_nat_lt.
    split; first by done.
    apply up_pos, aep_bound_pos; fourier.
  have Htmp : Pr ((`J( P , W)) `^ n0) (`TS (`J( P , W)) n0 (epsilon / 3)) >= 1 - epsilon / 3.
    rewrite -n0_prednK.
    apply Pr_TS_1 => //.
    - apply Rlt_mult_inv_pos => //; fourier.
    - rewrite n0_prednK.
      move/leP in Hn0.
      apply le_INR in Hn0.
      apply Rle_trans with (INR (Zabs_nat (up (aep_bound (`J(P , W)) (epsilon / 3))))) => //.
      rewrite INR_Zabs_nat; last first.
        apply Zlt_le_weak, up_pos, aep_bound_pos; fourier.
      by apply Rlt_le, (proj1 (archimed _ )).
  rewrite Pr_to_cplt.
  set p1 := Pr _ _ in Htmp.
  rewrite (_ : Pr _ _ = p1); last first.
    rewrite /p1; apply Pr_ext; apply/setP => i /=; by rewrite !inE negbK.
  fourier.
move=> Hn.
rewrite [in X in _ <= X] (_ : epsilon = epsilon / 3 + epsilon / 3 + epsilon / 3)%R; last by field.
rewrite 2!geq_max in Hn.
case/andP : Hn => Hn1; case/andP => Hn2 Hn3.
rewrite !Pr_tuple_prod.
apply Rplus_le_compat.
  apply Rplus_le_compat; by [apply HnP | apply HnPW].
eapply Rle_trans; last by apply HnP_W, Hn3.
apply Req_le, Pr_ext.
apply/setP => /= tab.
by rewrite !inE tuple_prodK.

move=> n0n Hn0n0.
suff H : Pr (`J(P , W) `^ n ) (~: `JTS P W n epsilon) <= epsilon.
rewrite -(Pr_cplt (`J(P , W) `^ n) (`JTS P W n epsilon)).
have : forall a b r : R, a <= r -> b >= b + a - r by move=> *; fourier.
by apply.

rewrite (@Pr_ext _ (`J(P , W) `^ n) (~: _)
([set x | ((tuple_prod x).1 \notin `TS P n epsilon)] :|:
([set x | ((tuple_prod x).2 \notin `TS (`O( P , W)) n epsilon)] :|:
          (~: `TS (`J( P , W)) n epsilon)))); last first.
  apply/setP => xy.
  by rewrite !inE 2!negb_and orbA.
eapply Rle_trans; last by apply n0n.
apply Rle_trans with (
Pr (`J(P , W) `^ n) [set x | (tuple_prod x).1 \notin `TS P n epsilon] +
Pr (`J(P , W) `^ n) ([set x | ((tuple_prod x).2 \notin `TS (`O( P , W)) n epsilon)] :|:
               (~: `TS (`J( P , W)) n epsilon)))%R.
  by apply: Pr_union.
rewrite -addRA !Pr_tuple_prod.
apply Rplus_le_compat_l.
eapply Rle_trans; last by apply Pr_union.
apply Req_le, Pr_ext.
apply/setP => t.
by rewrite !inE tuple_prodK.
Qed.

End jtyp_seq_transmitted.

Section non_typicality.

Variables A B : finType.
Variable P : dist A.
Variable W : `Ch_1(A, B).
Variable n : nat.
Variable epsilon : R.

(** ## *)

Lemma non_typical_sequences :
  Pr ((P `^ n) `x ((`O(P , W)) `^ n))
    [set x | prod_tuple x \in `JTS P W n epsilon] <= exp2 (- INR n * (`I( P ; W) - 3 * epsilon)).
Proof.
rewrite /Pr /=.
apply Rle_trans with
  (\rsum_(i | i \in `JTS P W n epsilon)
    (exp2 (- INR n * (`H P - epsilon)) * exp2 (- INR n * (`H( P `o W ) - epsilon)))) => /=.
  rewrite (reindex_onto (fun y => prod_tuple y) (fun x => tuple_prod x)) /=; last first.
    move=> ? ?; by rewrite tuple_prodK.
  apply: Rle_big_P_Q_f_g => i Hi.
  - rewrite inE in Hi.
    apply Rmult_le_compat.
    apply Rle_0_big_mult => j; by apply Rle0f.
    apply Rle_0_big_mult => j.
    apply Rle_big_0_P_g => k _.
    apply Rmult_le_pos; by apply Rle0f.
    by apply (proj2 (typical_sequence1_JTS Hi)).
    by apply (typical_sequence1_JTS' Hi).
  - apply Rmult_le_pos; by apply Rlt_le, exp2_pos.
  - rewrite inE in Hi.
    by rewrite prod_tupleK eqxx andbC.
rewrite (_ : \rsum_(_ | _) _ =
  INR #| `JTS P W n epsilon| *
  exp2 (- INR n * (`H P - epsilon)) * exp2 (- INR n * (`H( P `o W) - epsilon))); last first.
  rewrite big_const_seq /= (_ : count _ _ = #|`JTS P W n epsilon|); last first.
    by rewrite -size_filter filter_index_enum -cardE.
  by rewrite iter_Rplus -mulRA.
apply Rle_trans with (exp2 (INR n * (`H( P , W ) + epsilon)) *
  exp2 (- INR n * (`H P - epsilon)) * exp2 (- INR n * (`H( P `o W ) - epsilon))).
  apply: Rmult_le_compat _ (Rle_refl _).
  - apply: Rmult_le_pos (pos_INR _) _; by apply Rlt_le, exp2_pos.
  - by apply Rlt_le, exp2_pos.
  - apply: Rmult_le_compat _ (pos_INR _) _ _ (Rle_refl _).
    by apply Rlt_le, exp2_pos.
    by apply JTS_sup.
apply Req_le.
rewrite -2!exp2_plus.
congr (exp2 _).
rewrite /mut_info !mulRDr 2!Rmult_opp_opp (_ : 3 * epsilon = epsilon + epsilon + epsilon); by field.
Qed.

End non_typicality.


From Coq Require Import ZArith String Program.Equality.
From WiSE Require Import relations.

(** * IMPREC, An extension of IMP with procedures and recursion *)

(** ** Syntax *)

Definition ident := string.

Inductive variable :=
  | Local (x : ident)
  | Global (x : ident).

(** Expressions *)
Inductive aexpr : Type :=
  | Var : variable -> aexpr
  | Cst : Z -> aexpr
  | Add : aexpr -> aexpr -> aexpr
  | Sub : aexpr -> aexpr -> aexpr.

Inductive bexpr : Type :=
  | Bcst  : bool -> bexpr
  | Ble   : aexpr -> aexpr -> bexpr
  | Beq   : aexpr -> aexpr -> bexpr
  | Bnot  : bexpr -> bexpr
  | Band  : bexpr -> bexpr -> bexpr.

Definition Bor (b1 b2 : bexpr) := Band (Bnot b1) (Bnot b2).

(** Commands *)
Inductive stmt : Type :=
  | Skip  : stmt
  | Ite   : bexpr -> stmt -> stmt -> stmt
  | Seq   : stmt -> stmt -> stmt
  | Aff   : string -> aexpr -> stmt
  | Err   : stmt
  | Loop  : bexpr -> stmt -> stmt
  .

Definition Assert c := Ite c Skip Err.

Fixpoint alocals (e : aexpr) (x : ident) : Prop :=
  match e with
  | Var (Local y) => y = x
  | Var (Global _) | Cst _ => False
  | Add e1 e2 | Sub e1 e2 => alocals e1 x \/ alocals e2 x
  end.

Fixpoint blocals (b : bexpr) (x : ident) : Prop :=
  match b with
  | Bcst _ => False
  | Bnot b => blocals b x
  | Ble e1 e2 | Beq e1 e2 => alocals e1 x \/ alocals e2 x
  | Band b1 b2 =>  blocals b1 x \/ blocals b2 x
  end.

Fixpoint locals (s : stmt) (x : ident) : Prop :=
  match s with
  | Skip => False
  | Ite b s1 s2 => blocals b x \/ locals s1 x \/ locals s2 x
  | Seq s1 s2 =>  locals s1 x \/ locals s2 x
  | Aff y e => x = y \/ alocals e x
  | Err => False
  | Loop b s => blocals b x \/ locals s x
  end.

Record declaration := {
  params : list ident;
  body : stmt;
  Hlocals : forall x, locals body x -> List.In x params
}.

Record IMPREC := {
  decls : list declaration;
  main  : stmt;
}.

(** NOTE :
    Option 1 : assume programs are well formed
      - No undefined local variables
      - No references to undefined procedures
    Option 2 : Semantics fail if undefined variable....

    Opinion :
    - option1 is an approach that works well for static languages
    - option2 models more dynamic languages (python, js)
*)

(** ** Semantics *)

Definition global_store := ident -> Z.
Definition local_store := ident -> Z.

(** *** Denotational semantics for expressions *)

(** Semantics of Arithmetic expressions *)
Fixpoint aeval (gs : global_store) (ls : local_store) (e : aexpr) : Z :=
  match e with
  | Var (Global x) => gs x
  | Var (Local x) => ls x
  | Cst c => c
  | Add e1 e2 => aeval gs ls e1 + aeval gs ls e2
  | Sub e1 e2 => aeval gs ls e1 - aeval gs ls e2
  end.

(* Fixpoint asubst (e : aexpr) (x : ident) (e' : aexpr) :=
  match e with
  | Var y => if (string_dec y x) then e' else e
  | Cst _ => e
  | Add e1 e2 => Add (asubst e1 x e') (asubst e2 x e')
  | Sub e1 e2 => Sub (asubst e1 x e') (asubst e2 x e')
  end.

Definition ainst (e : aexpr) (x : ident) (vx : Z) :=
  asubst e x (Cst vx).

Fixpoint beval (s : store) (e : bexpr) : bool :=
  match e with
  | Bcst b      => b
  | Ble e1 e2   => (aeval s e1 <? aeval s e2)%Z
  | Beq e1 e2   => (aeval s e1 =? aeval s e2)%Z
  | Band e1 e2  => beval s e1 && beval s e2
  | Bnot e      => negb (beval s e)
  end.

Fixpoint bsubst (e : bexpr) (x : ident) (e' : aexpr) :=
  match e with
  | Bcst _      => e
  | Beq e1 e2   => Beq (asubst e1 x e') (asubst e2 x e')
  | Ble e1 e2   => Ble (asubst e1 x e') (asubst e2 x e')
  | Band e1 e2  => Band (bsubst e1 x e') (bsubst e2 x e')
  | Bnot e      => Bnot (bsubst e x e')
  end.

Definition binst (e : bexpr) (x : ident) (vx : Z) :=
  bsubst e x (Cst vx).

(** *** Operational semantics of IMP *)

(** Updating a store *)
Definition update (s : store) (x : ident) (v : Z) : store :=
  fun y => if string_dec y x then v else s y.

(** Subtitution lemma (for arithmetic expressions) *)
Lemma aeval_asubst :
  forall s e x e',
    aeval s (asubst e x e') = aeval (update s x (aeval s e')) e.
Proof.
  induction e; intros; simpl in *; auto.
  - unfold update.
    destruct (string_dec i x) eqn:E; auto.
  - now rewrite IHe1, IHe2.
  - now rewrite IHe1, IHe2.
Qed.

(** Subtitution lemma (for boolean expressions) *)
Lemma beval_bsubst :
  forall s c x e,
    beval s (bsubst c x e) = beval (update s x (aeval s e)) c.
Proof.
  intros. induction c; simpl in *; auto.
  all: try now do 2 rewrite <- aeval_asubst.
  now rewrite IHc.
  now rewrite IHc1, IHc2.
Qed.

Lemma aeval_inst:
  forall s e x vx, aeval (update s x vx) e = aeval s (ainst e x vx).
Proof.
  intros. unfold ainst.
  now rewrite aeval_asubst.
Qed.

Lemma beval_inst:
  forall s c x vx, beval (update s x vx) c = beval s (binst c x vx).
Proof.
  intros. induction c; simpl; auto.
  all: try now do 2 rewrite aeval_inst.
  now rewrite IHc.
  now rewrite IHc1, IHc2.
Qed.

(** Big step semantics *)
Inductive exec : store -> IMP -> store -> Prop :=
  | exec_Skip s :
    exec s Skip s
  | exec_Aff s x e ve :
    aeval s e = ve ->
    exec s (Aff x e) (update s x ve)
  | exec_Seq s s' s'' c1 c2 :
    exec s c1 s' ->
    exec s' c2 s'' ->
    exec s (Seq c1 c2) s''
  | exec_Ite_true s s' e c1 c2 :
    beval s e = true ->
    exec s c1 s' ->
    exec s (Ite e c1 c2) s'
  | exec_Ite_false s s' e c1 c2 :
    beval s e = false ->
    exec s c2 s' ->
    exec s (Ite e c1 c2) s'
  | exec_loop_true s s' s'' e c :
    beval s e = true ->
    exec s c s' ->
    exec s' (Loop e c) s'' ->
    exec s (Loop e c) s''
  | exec_loop_false s e c :
    beval s e = false ->
    exec s (Loop e c) s.

(** Small step semantics *)
Inductive step : (store * IMP) -> (store * IMP) -> Prop :=
  | step_Aff s x e ve :
    aeval s e = ve -> step (s, Aff x e) (update s x ve, Skip)
  | step_Seq s1 s2 c1 c2 c3 :
    step (s1, c1) (s2, c2) -> step (s1, Seq c1 c3) (s2, Seq c2 c3)
  | step_Seq_Skip s c :
    step (s, Seq Skip c) (s, c)
  | step_Ite_true s e c1 c2 :
    beval s e = true -> step (s, Ite e c1 c2) (s, c1)
  | step_Ite_false s e c1 c2 :
    beval s e = false -> step (s, Ite e c1 c2) (s, c2)
  | step_Loop_true s e c :
    beval s e = true -> step (s, Loop e c) (s, Seq c (Loop e c))
  | step_Loop_false s e c :
    beval s e = false -> step (s, Loop e c) (s, Skip).

Lemma aeval_stable:
  forall env1 env2 e,
    (forall x, env1 x = env2 x) ->
    aeval env1 e = aeval env2 e.
Proof.
  intros.
  induction e; simpl; auto.
  - now rewrite IHe1, IHe2.
  - now rewrite IHe1, IHe2.
Qed.

(** Sequences of steps *)
Definition steps := star step.

(** Taking several steps to the left of a sequence *)
Lemma steps_seq :
  forall s1 s2 c1 c2 c3,
    steps (s1, c1) (s2, c2) -> steps (s1, Seq c1 c3) (s2, Seq c2 c3).
Proof.
  intros * H. dependent induction H.
  * reflexivity.
  * destruct y as [s1' c1'].
    eapply star_step. apply step_Seq, H.
    now apply IHstar.
Qed.

(**
  If a program [p] starting in state [s] terminates in
  state [s'] then [p] can take a sequence of steps
  from [s] to [s']
*)
Theorem exec_steps :
  forall p s s', exec s p s' -> steps (s, p) (s', Skip).
Proof.
  induction 1.
  - reflexivity.
  - eapply star_step.
    + apply (step_Aff _ _ _ _ H).
    + reflexivity.
  - etransitivity. apply steps_seq, IHexec1.
    eapply star_step. apply step_Seq_Skip.
    apply IHexec2.
  - eapply star_step. eapply (step_Ite_true _ _ _ _ H).
    apply IHexec.
  - eapply star_step. eapply (step_Ite_false _ _ _ _ H).
    apply IHexec.
  - eapply star_step. eapply (step_Loop_true _ _ _ H).
    etransitivity. eapply (steps_seq _ _ _ _ _ IHexec1).
    eapply star_step. eapply step_Seq_Skip. apply IHexec2.
  - eapply star_step. eapply (step_Loop_false _ _ _ H).
    reflexivity.
Qed.

Theorem step_exec_exec :
  forall c1 c2 s1 s2 s3,
    step (s1, c1) (s2, c2) ->
    exec s2 c2 s3 ->
    exec s1 c1 s3.
Proof.
  intros * H1. generalize s3. clear s3.
  dependent induction H1; intros.
  - inversion_clear H.
    now apply exec_Aff.
  - inversion_clear H.
    eapply exec_Seq; eauto.
  - eapply exec_Seq; eauto using exec.
  - eapply exec_Ite_true; eauto.
  - eapply exec_Ite_false; eauto.
  - inversion_clear H0.
    eapply exec_loop_true; eauto.
  - inversion H0; subst.
    eapply exec_loop_false; eauto.
Qed.

(**
  If a program [p] can take a sequence of steps
  from [s] to [s'] then [p] terminates in
  state [s'] when executed in [s]
*)
Theorem steps_exec :
  forall p s s', steps (s, p) (s', Skip) -> exec s p s'.
Proof.
  intros. dependent induction H.
  - apply exec_Skip.
  - destruct y as [s1 p1].
    eapply step_exec_exec; eauto.
Qed.

(** ** Progression and Erroneous States  *)

(** A configuration is said to [progress] if it is a [Skip] statement or
    if it can take a [step]
*)
Definition progress '((s, p) : (store * IMP)) : Prop :=
  p = Skip \/ exists s' p', step (s, p) (s', p').

(** An error state is a state that can't progress *)
Definition error_state (st : (store * IMP)) : Prop :=
  ~progress st.

(** [Skip] can progress *)
Theorem progress_Skip:
  forall env, progress (env, Skip).
Proof.
  now left.
Qed.

(** [Ite] can progress *)
Theorem progress_Ite:
  forall env b p1 p2, progress (env, Ite b p1 p2).
Proof.
  intros *. right.
  destruct (beval env b) eqn:Hsat.
  * exists env, p1. now econstructor.
  * exists env, p2. now econstructor.
Qed.

(** [Aff] can progress *)
Theorem progress_Aff:
  forall env x e, progress (env, Aff x e).
Proof.
  intros *. right.
  repeat econstructor.
Qed.

(** [Aff] can progress *)
Theorem progress_Seq:
  forall env p1 p2, progress (env, p1) -> progress (env, Seq p1 p2).
Proof.
  intros * [-> | (s' & p' & H)].
  - right. exists env, p2. econstructor.
  - right. exists s', (Seq p' p2). now econstructor.
Qed.

(** [Loop] can progress *)
Theorem progress_Loop:
  forall env b p, progress (env, Loop b p).
Proof.
  intros *. right.
  destruct (beval env b) eqn:Hsat.
  - exists env. now repeat econstructor.
  - exists env, Skip. now repeat econstructor.
Qed.

(** If a sequence [Seq p1 p2] can't progress, then [p1] can't progress *)
Theorem error_state_seq:
  forall s p1 p2, error_state (s, Seq p1 p2) -> error_state (s, p1).
Proof.
  intros * H Hcontr.
  apply H, progress_Seq, Hcontr.
Qed.

(** Syntactic characterization of error states *)
Inductive error : IMP -> Prop :=
  | error_Err : error Err
  | error_Seq p1 p2 : error p1 -> error (Seq p1 p2).

Theorem error_state_error :
  forall s p, error_state (s, p) <-> error p.
Proof.
  intros. split.
  - intros Hcontr.
    induction p; try easy.
    + now specialize (Hcontr (progress_Skip s)).
    + now specialize (Hcontr (progress_Ite s _ _ _)).
    + apply error_state_seq in Hcontr.
      specialize (IHp1 Hcontr). now econstructor.
    + now specialize (Hcontr (progress_Aff s _ _)).
    + econstructor.
    + now specialize (Hcontr (progress_Loop s _ _)).
  - induction 1.
    + intros [H | (s' & p' & H)]; try easy.
    + intros [H' | (s' & p' & H')]; try easy.
      inversion H'; subst.
      assert (Hprog : progress (s, p1)) by (right; repeat econstructor; eauto).
      apply (IHerror Hprog).
      inversion H.
Qed.

(** Executable check for erroneous state *)
Fixpoint is_error (p : IMP) : bool :=
  match p with
  | Err => true
  | Seq p _ => is_error p
  | _ => false
  end.

Theorem is_error_correct:
  forall p, is_error p = true <-> error p.
Proof.
  induction p; try easy.
  - split.
    + intros H%IHp1. now econstructor.
    + intros. inversion H; subst.
      simpl. now apply IHp1.
  - repeat econstructor.
Qed. *)


(** **** SNU 4190.310, 2016 Spring *)

(** Assignment 02 *)
(** Due: 2016/10/10 23:59 *)

(* Important:
   - You are NOT allowed to use the [admit] tactic.

   - You are NOT allowed to use the following tactics.
     [tauto], [intuition], [firstorder], [omega].

   - Just leave [exact FILL_IN_HERE] for those problems that you fail to prove.
*)

Require Import Basics.

Definition FILL_IN_HERE {T: Type} : T.  Admitted.

(** The following function doubles its argument: *)

Fixpoint double (n:nat) :=
  match n with
  | O => O
  | S n' => S (S (double n'))
  end.

Inductive natprod : Type :=
  pair : nat -> nat -> natprod.

Notation "( x , y )" := (pair x y).

Definition fst :=
  fun (p : natprod) =>
  match p with
  | (x, y) => x
  end.

Definition snd (p : natprod) : nat :=
  match p with
  | (x, y) => y
  end.

Definition swap_pair (p : natprod) : natprod :=
  match p with
  | (x,y) => (y,x)
  end.

(***
   See the chapter "Lists" for explanations of the following.
 ***)

Inductive natlist : Type :=
  | nil : natlist
  | cons : nat -> natlist -> natlist.

Notation "x :: l" := (cons x l) (at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y nil) ..).

Fixpoint app (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil    => l2
  | h :: t => h :: (app t l2)
  end.

Notation "x ++ y" := (app x y)
                     (right associativity, at level 60).

Definition hd (default:nat) (l:natlist) : nat :=
  match l with
  | nil => default
  | h :: t => h
  end.

Theorem app_assoc : forall l1 l2 l3 : natlist,
  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).
Proof.
  intros l1 l2 l3. induction l1 as [| n l1'].
  - reflexivity.
  - simpl. rewrite -> IHl1'. reflexivity.
Qed.

Fixpoint snoc (l:natlist) (v:nat) : natlist :=
  match l with
  | nil    => [v]
  | h :: t => h :: (snoc t v)
  end.

Fixpoint rev (l:natlist) : natlist :=
  match l with
  | nil    => nil
  | h :: t => snoc (rev t) h
  end.