(** * Basics: Functional Programming in Coq *)
Print LoadPath.
(* REMINDER:

          #####################################################
          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###
          #####################################################

   (See the [Preface] for why.)
*)

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

(** The functional programming style is founded on simple, everyday
    mathematical intuition: If a procedure or method has no side
    effects, then (ignoring efficiency) all we need to understand
    about it is how it maps inputs to outputs -- that is, we can think
    of it as just a concrete method for computing a mathematical
    function.  This is one sense of the word "functional" in
    "functional programming."  The direct connection between programs
    and simple mathematical objects supports both formal correctness
    proofs and sound informal reasoning about program behavior.

    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, included in
    data structures, etc.  The recognition that functions can be
    treated as data gives rise to a host of useful and powerful
    programming idioms.

    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_ supporting abstraction and code reuse.
    Coq offers all of these features.

    The first half of this chapter introduces the most essential
    elements of Coq's functional programming language, called
    _Gallina_.  The second half introduces some basic _tactics_ that
    can be used to prove properties of Coq programs. *)

(* ################################################################# *)
(** * Data and Functions *)
(* ================================================================= *)
(** ** Enumerated Types *)

(** One notable 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 a powerful mechanism for defining new
    data types from scratch, with all these familiar types as
    instances.

    Naturally, the Coq distribution comes preloaded 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.  To
    illustrate this, we will explicitly recapitulate all the
    definitions we need in this course, rather than just getting them
    implicitly from the library. *)

(* ================================================================= *)
(** ** Days of the Week *)

(** To see how this definition mechanism works, let's start with
    a very simple example.  The following declaration tells Coq that
    we are defining a new set of data values -- a _type_. *)

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

(** The type is called [day], and its members are [monday],
    [tuesday], 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 figure out these types for
    itself when they are not given explicitly -- i.e., it can do _type
    inference_ -- but we'll generally 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 [Compute] to evaluate a
    compound expression involving [next_weekday]. *)

Compute (next_weekday friday).
(* ==> monday : day *)

Compute (next_weekday (next_weekday saturday)).
(* ==> tuesday : day *)

(** (We show Coq's responses in comments, but, if you have a
    computer handy, this 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 Coq sources, find the above example, submit it to
    Coq, and observe the result.) *)

(** 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 our [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 go from proved-correct algorithms written in Gallina to
    efficient machine code.  (Of course, we are trusting the
    correctness of the OCaml/Haskell/Scheme compiler, and of Coq's
    extraction facility itself, but this is still a big step forward
    from the way most software is developed today.) Indeed, this is
    one of the main uses for which Coq was developed.  We'll come back
    to this topic in later chapters. *)

(* ================================================================= *)
(** ** Homework Submission Guidelines *)

(** If you are using _Software Foundations_ in a course, your
    instructor may use automatic scripts to help grade your homework
    assignments.  In order for these scripts to work correctly (so
    that you get full credit for your work!), please be careful to
    follow these rules:
      - The grading scripts work by extracting marked regions of the
        [.v] files that you submit.  It is therefore important that
        you do not alter the "markup" that delimits exercises: the
        Exercise header, the name of the exercise, the "empty square
        bracket" marker at the end, etc.  Please leave this markup
        exactly as you find it.
      - Do not delete exercises.  If you skip an exercise (e.g.,
        because it is marked Optional, or because you can't solve it),
        it is OK to leave a partial proof in your [.v] file, but in
        this case please make sure it ends with [Admitted] (not, for
        example [Abort]).
      - It is fine to use additional definitions (of helper functions,
        useful lemmas, etc.) in your solutions.  You can put these
        between the exercise header and the theorem you are asked to
        prove.

    You will also notice that each chapter (like [Basics.v]) is
    accompanied by a _test script_ ([BasicsTest.v]) that automatically
    calculates points for the finished homework problems in the
    chapter.  These scripts are mostly for the auto-grading
    infrastructure that your instructor may use to help process
    assignments, but you may also like to use them to double-check
    that your file is well formatted before handing it in.  In a
    terminal window either type [make BasicsTest.vo] or do the
    following:

       coqc -Q . LF Basics.v
       coqc -Q . LF BasicsTest.v

    There is no need to hand in [BasicsTest.v] itself (or [Preface.v]).

    _If your class is using the Canvas system to hand in assignments_:
      - If you submit multiple versions of the assignment, you may
        notice that they are given different names.  This is fine: The
        most recent submission is the one that will be graded.
      - To hand in multiple files at the same time (if more than one
        chapter is assigned in the same week), you need to make a
        single submission with all the files at once using the button
        "Add another file" just above the comment box. *)

(* ================================================================= *)
(** ** Booleans *)

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

Inductive bool : Type :=
  | true
  | false.

(** 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, 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 of these illustrate Coq's syntax for
    multi-argument function definitions.  The corresponding
    multi-argument application syntax is illustrated by the following
    "unit tests," which constitute a complete specification -- a truth
    table -- for the [orb] function: *)

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

(** We can also introduce some familiar syntax for the boolean
    operations we have just defined. The [Notation] command defines a new
    symbolic notation for an existing definition. *)

Notation "x && y" := (andb x y).
Notation "x || y" := (orb x y).

Example test_orb5:  false || false || true = true.
Proof. simpl. reflexivity. Qed.

(** _A note on notation_: In [.v] files, we use square brackets
    to delimit fragments of Coq code within comments; 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 command [Admitted] can be used as a placeholder for an
    incomplete proof.  We'll use it in exercises, to indicate the
    parts that we're leaving for you -- i.e., your job is to replace
    [Admitted]s with real proofs. *)

(** **** Exercise: 1 star, standard (nandb)

    Remove "[Admitted.]" and complete the definition of the following
    function; then make sure that the [Example] assertions below can
    each be verified by Coq.  (I.e., fill in each proof, following the
    model of the [orb] tests above.) The 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 .

  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *)

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

(** **** Exercise: 1 star, standard (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 :=
  match b1 with
  | false => false
  | true => andb b2 b3
end.

  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *)

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

(* ================================================================= *)
(** ** Types *)

(** Every expression in Coq has a type, describing what sort of
    thing it computes. The [Check] command asks Coq to print the type
    of an expression. *)

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 *)

Check andb.

(** 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]." *)

(* ================================================================= *)
(** ** New Types from Old *)

(** The types we have defined so far are examples of "enumerated
    types": their definitions explicitly enumerate a finite set of
    elements, each of which is just a bare constructor.  Here is a
    more interesting type definition, where one of the constructors
    takes an argument: *)

Inductive rgb : Type :=
  | red
  | green
  | blue.

Inductive color : Type :=
  | black
  | white
  | primary (p : rgb).

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

    Every inductively defined type ([day], [bool], [rgb], [color],
    etc.) contains a set of _constructor expressions_ built from
    _constructors_ like [red], [primary], [true], [false], [monday],
    etc.

    The definitions of [rgb] and [color] say how expressions in the
    sets [rgb] and [color] can be built:

    - [red], [green], and [blue] are the constructors of [rgb];
    - [black], [white], and [primary] are the constructors of [color];
    - the expression [red] belongs to the set [rgb], as do the
      expressions [green] and [blue];
    - the expressions [black] and [white] belong to the set [color];
    - if [p] is an expression belonging to the set [rgb], then
      [primary p] (pronounced "the constructor [primary] applied to
      the argument [p]") is an expression belonging to the set
      [color]; and
    - expressions formed in these ways are the _only_ ones belonging
      to the sets [rgb] and [color]. *)

(** We can define functions on colors using pattern matching just as
    we have done for [day] and [bool]. *)

Definition monochrome (c : color) : bool :=
  match c with
  | black => true
  | white => true
  | primary q => false
  end.

(** Since the [primary] constructor takes an argument, a pattern
    matching [primary] should include either a variable (as above --
    note that we can choose its name freely) or a constant of
    appropriate type (as below). *)

Definition isred (c : color) : bool :=
  match c with
  | black => false
  | white => false
  | primary red => true
  | primary _ => false
  end.

(** The pattern [primary _] here is shorthand for "[primary] applied
    to any [rgb] constructor except [red]."  (The wildcard pattern [_]
    has the same effect as the dummy pattern variable [p] in the
    definition of [monochrome].) *)

(* ================================================================= *)
(** ** Tuples *)

(** A single constructor with multiple parameters can be used
    to create a tuple type. As an example, consider representing
    the four bits in a nybble (half a byte). We first define
    a datatype [bit] that resembles [bool] (using the
    constructors [B0] and [B1] for the two possible bit values),
    and then define the datatype [nybble], which is essentially
    a tuple of four bits. *)

Inductive bit : Type :=
  | B0
  | B1.

Inductive nybble : Type :=
  | bits (b0 b1 b2 b3 : bit).

Check (bits B1 B0 B1 B0).
(* ==> bits B1 B0 B1 B0 : nybble *)

(** The [bits] constructor acts as a wrapper for its contents.
    Unwrapping can be done by pattern-matching, as in the [all_zero]
    function which tests a nybble to see if all its bits are O.
    Note that we are using underscore (_) as a _wildcard pattern_ to
    avoid inventing variable names that will not be used. *)

Definition all_zero (nb : nybble) : bool :=
  match nb with
    | (bits B0 B0 B0 B0) => true
    | (bits _ _ _ _) => false
  end.

Compute (all_zero (bits B1 B0 B1 B0)).
(* ===> false : bool *)
Compute (all_zero (bits B0 B0 B0 B0)).
(* ===> true : bool *)

(* ================================================================= *)
(** ** Modules *)

(** Coq provides a _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 are referred to by
    names like [X.foo] instead of just [foo].  We will use this
    feature to introduce the definition of the type [nat] in an inner
    module so that it does not interfere with the one from the
    standard library (which we want to use in the rest because it
    comes with a tiny bit of convenient special notation).  *)

Module NatPlayground.

(* ================================================================= *)
(** ** Numbers *)

(** The types we have defined so far, "enumerated types" such as
    [day], [bool], and [bit], and tuple types such as [nybble] built
    from them, share the property that each type has a finite set of
    values. The natural numbers are an infinite set, and we need to
    represent all of them in a datatype with a finite number of
    constructors. There are many representations of numbers to choose
    from. We are most familiar with decimal notation (base 10), using
    the digits 0 through 9, for example, to form the number 123.  You
    may have encountered hexadecimal notation (base 16), in which the
    same number is represented as 7B, or octal (base 8), where it is
    173, or binary (base 2), where it is 1111011. Using an enumerated
    type to represent digits, we could use any of these to represent
    natural numbers. There are circumstances where each of these
    choices can be useful.

    Binary is valuable in computer hardware because it can in turn be
    represented with two voltage levels, resulting in simple
    circuitry. Analogously, we wish here to choose a representation
    that makes _proofs_ simpler.

    Indeed, there is a representation of numbers that is even simpler
    than binary, namely unary (base 1), in which only a single digit
    is used (as one might do while counting days in prison by scratching
    on the walls). To represent unary with a Coq datatype, we use
    two constructors. The capital-letter [O] constructor represents zero.
    When the [S] constructor is applied to the representation of the
    natural number _n_, the result is the representation of _n+1_.
    ([S] stands for "successor", or "scratch" if one is in prison.)
    Here is the complete datatype definition. *)

Inductive nat : Type :=
  | O
  | S (n : nat).

(** With this definition, 0 is represented by [O], 1 by [S O],
    2 by [S (S O)], and so on. *)

(** 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] can be put in front of a natural number to yield another
        one -- if [n] is a natural number, then [S n] is too. *)

(** Again, let's look at this in a little more detail.  The definition
    of [nat] says how expressions in the set [nat] can be built:

    - [O] and [S] are constructors;
    - 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], [bool],
    [color], etc.

    The above 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 built
    from data constructors, like [true], [andb true false], [S (S
    false)], and [O (O (O S))] do not.

    A critical point here is that what we've done so far is just to
    define a _representation_ of numbers: a way of writing them down.
    The names [O] and [S] are arbitrary, and at this point they have
    no special meaning -- they are just two different marks that we
    can use to write down numbers (together with a rule that says any
    [nat] will be written as some string of [S] marks followed by an
    [O]).  If we like, we can write essentially the same definition
    this way: *)

Inductive nat' : Type :=
  | stop
  | tick (foo : nat').

(** The _interpretation_ of these marks comes from how we use them to
    compute. *)

(** We can do this by writing functions that pattern match on
    representations of natural numbers just as we did above with
    booleans and days -- for example, here is 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 NatPlayground.

(** 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 decimal numerals can be used as an alternative to
    the "unary" notation defined by the constructors [S] and [O].  Coq
    prints numbers in decimal form by default: *)

Check (S (S (S (S O)))).
  (* ===> 4 : nat *)

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

Compute (minustwo 4).
  (* ===> 2 : nat *)

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

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 between the
    first one and the other two: 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!  It is just a way of
    writing down numbers.  (Think about standard decimal numerals: the
    numeral [1] is not a computation; it's a piece of data.  When we
    write [111] to mean the number one hundred and eleven, we are
    using [1], three times, to write down a concrete representation of
    a number.)

    For most function definitions over numbers, just 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: *)

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

Example test_oddb1:    oddb 1 = true.
Proof. simpl. reflexivity.  Qed.
Example test_oddb2:    oddb 4 = false.
Proof. simpl. reflexivity.  Qed.

(** (You will notice if you step through these proofs that
    [simpl] actually has no effect on the goal -- all of the work is
    done by [reflexivity].  We'll see more about why that is shortly.)

    Naturally, we can also define multi-argument functions by
    recursion.  *)

Module NatPlayground2.

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. *)

Compute (plus 3 2).

(** 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. simpl. 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.

End NatPlayground2.

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

Compute (exp 3 2).
Example test1: (exp 3 2) = 9.
Proof. simpl. reflexivity. Qed.

(** **** Exercise: 1 star, standard (factorial)

    Recall the standard mathematical 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
  | 0 => 1
  | S p => mult n (factorial p)
end.

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

(** Again, we can make numerical expressions 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 for our purposes, but interested readers
    can refer to the "More on Notation" 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 almost nothing built-in, we really
    mean it: even equality testing is a user-defined operation!

    Here is a function [eqb], which tests natural 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 eqb (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' => eqb n' m'
            end
  end.

(** Similarly, the [leb] function tests whether its first argument is
    less than or equal to its second argument, yielding a boolean. *)

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

Example test_leb1:             (leb 2 2) = true.
Proof. simpl. reflexivity.  Qed.
Example test_leb2:             (leb 2 4) = true.
Proof. simpl. reflexivity.  Qed.
Example test_leb3:             (leb 4 2) = false.
Proof. simpl. reflexivity.  Qed.

(** Since we'll be using these (especially [eqb]) a lot, let's give
    them infix notations. *)

Notation "x =? y" := (eqb x y) (at level 70) : nat_scope.
Notation "x <=? y" := (leb x y) (at level 70) : nat_scope.

Example test_leb3':             (4 <=? 2) = false.
Proof. simpl. reflexivity.  Qed.

(** **** Exercise: 1 star, standard (ltb)

    The [ltb] function tests natural 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.  (It can be done with just one previously defined
    function, but you can use two if you need to.) *)

Definition ltb (n m : nat) : bool :=
  match leb n m with
  | true => match eqb n m with
            | true => false
            | false => true
          end
  | false => false
  end.

Notation "x <? y" := (ltb x y) (at level 70) : nat_scope.

Example test_ltb1:             (ltb 2 2) = false.
Proof. simpl. reflexivity. Qed.
Example test_ltb2:             (ltb 2 4) = true.
Proof. simpl. reflexivity. Qed.
Example test_ltb3:             (ltb 4 2) = false.
Proof. simpl. reflexivity. Qed.
(** [] *)

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

(** Now that we've defined a few datatypes and functions, let's
    turn to stating and proving properties of their behavior.
    Actually, 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 [simpl] to simplify both sides of the
    equation, then use [reflexivity] to check that both sides contain
    identical values.

    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. simpl. reflexivity.  Qed.

(** (You may notice that the above statement looks different in
    the [.v] file in your IDE than it does in the HTML rendition in
    your browser, if you are viewing both. In [.v] files, we write the
    [forall] universal quantifier using the reserved identifier
    "forall."  When the [.v] files are converted to HTML, this gets
    transformed into an upside-down-A symbol.)

    This is a good place to mention that [reflexivity] is a bit
    more powerful than we have admitted. In the examples we have seen,
    the calls to [simpl] were actually not needed, because
    [reflexivity] can perform some simplification automatically when
    checking that two sides are equal; [simpl] was just added so that
    we could see the intermediate state -- after simplification but
    before finishing the proof.  Here is a shorter proof of the
    theorem: *)

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

(** Moreover, it will be useful later to know that [reflexivity]
    does somewhat _more_ simplification than [simpl] does -- for
    example, it tries "unfolding" defined terms, replacing them with
    their right-hand sides.  The reason for this difference is that,
    if reflexivity succeeds, the whole goal is finished and we don't
    need to look at whatever expanded expressions [reflexivity] has
    created by all this simplification and unfolding; by contrast,
    [simpl] is used in situations where we may have to read and
    understand the new goal that it creates, so we would not want it
    blindly expanding definitions and leaving the goal in a messy
    state.

    The form of the theorem we just stated and its proof are almost
    exactly the same as the simpler examples we saw earlier; there are
    just a few differences.

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

    Second, we've added the quantifier [forall n:nat], so that our
    theorem talks about _all_ natural numbers [n].  Informally, to
    prove theorems of this form, we generally start by saying "Suppose
    [n] is some number..."  Formally, this is achieved in the proof by
    [intros n], which moves [n] from the quantifier in the goal to a
    _context_ of current assumptions.

    The keywords [intros], [simpl], and [reflexivity] are examples of
    _tactics_.  A tactic is a command that is used between [Proof] and
    [Qed] to guide the process of checking some claim we are making.
    We will see several more tactics in the rest of this chapter and
    yet more in future chapters. *)

(** Other similar theorems can be proved with the same pattern. *)

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." *)

(** It is worth stepping through these proofs to observe how the
    context and the goal change.  You may want to add calls to [simpl]
    before [reflexivity] to see the simplifications that Coq performs
    on the terms before checking that they are equal. *)

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

(** This theorem is a bit more interesting than the others we've
    seen: *)

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

(** Instead of making a universal claim about all numbers [n] and [m],
    it 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 we are given such
    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.
  (* move both quantifiers into the context: *)
  intros n m.
  (* move the hypothesis into the context: *)
  intros H.
  (* rewrite the goal using the hypothesis: *)
  rewrite -> H.
  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 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.) *)

(** **** Exercise: 1 star, standard (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.
  intros H.
  intros M.
  rewrite -> H.
  rewrite -> M.
  reflexivity.
Qed.
(** [] *)

(** 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
    lemmas that we believe will be useful for making some larger
    argument, use [Admitted] to accept them on faith for the moment,
    and continue working on the main 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] 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. If the statement
    of the previously proved theorem involves quantified variables,
    as in the example below, Coq tries to instantiate them
    by matching with the current goal. *)

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, standard (mult_S_1)  *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  intros n m.
  intros H.
  rewrite -> H.
  reflexivity.
Qed.

  (* (N.b. This proof can actually be completed with tactics other than
     [rewrite], but please do use [rewrite] for the sake of the exercise.)

    [] *)

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

(** Of course, not everything can be proved by simple
    calculation and rewriting: In general, unknown, hypothetical
    values (arbitrary numbers, booleans, lists, etc.) can block
    simplification.  For example, if we try to prove the following
    fact using the [simpl] tactic as above, we get stuck.  (We then
    use the [Abort] command to give up on it for the moment.)*)

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

(** The reason for this is that the definitions of both
    [eqb] 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 [eqb] is the compound
    expression [n + 1]; neither can be simplified.

    To make progress, we need to consider the possible forms of [n]
    separately.  If [n] is [O], then we can calculate the final result
    of [(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, [(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,
  (n + 1) =? 0 = false.
Proof.
  intros n. destruct n as [| n'] eqn:E.
  - reflexivity.
  - reflexivity.   Qed.

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem.

    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 [|].  In this case, the first
    component is empty, since the [O] constructor is nullary (it
    doesn't have any arguments).  The second component gives a single
    name, [n'], since [S] is a unary constructor.

    In each subgoal, Coq remembers the assumption about [n] that is
    relevant for this subgoal -- either [n = 0] or [n = S n'] for some
    n'.  The [eqn:E] annotation tells [destruct] to give the name [E] to
    this equation.  (Leaving off the [eqn:E] annotation causes Coq to
    elide these assumptions in the subgoals.  This slightly
    streamlines proofs where the assumptions are not explicitly used,
    but it is better practice to keep them for the sake of
    documentation, as they can help keep you oriented when working
    with the subgoals.)

    The [-] signs on the second and third lines are called _bullets_,
    and they mark the parts of the proof that correspond to each
    generated subgoal.  The proof script that comes after a bullet is
    the entire proof for a subgoal.  In this example, each of the
    subgoals is easily proved by a single use of [reflexivity], which
    itself performs some simplification -- e.g., the second one
    simplifies [(S n' + 1) =? 0] to [false] by first rewriting [(S n'
    + 1)] to [S (n' + 1)], then unfolding [eqb], and then simplifying
    the [match].

    Marking cases with bullets is entirely optional: if bullets are
    not present, Coq simply asks you to prove each subgoal in
    sequence, one at a time. But it is a good idea to use bullets.
    For one thing, they make the structure of a proof apparent, making
    it more readable. Also, bullets instruct Coq to ensure that a
    subgoal is complete before trying to verify the next one,
    preventing proofs for different subgoals from getting mixed
    up. These issues become especially important in large
    developments, where fragile proofs lead to long debugging
    sessions.

    There are no hard and fast rules for how proofs should be
    formatted in Coq -- in particular, where lines should be broken
    and how sections of the proof should be indented to indicate their
    nested structure.  However, if the places where multiple subgoals
    are generated are marked with explicit bullets at the beginning of
    lines, then the proof will be readable almost no matter what
    choices are made about other aspects of layout.

    This is also a good place to mention one other piece of somewhat
    obvious advice about line lengths.  Beginning Coq users sometimes
    tend to the extremes, either writing each tactic on its own line
    or writing entire proofs on one line.  Good style lies somewhere
    in the middle.  One reasonable convention is to limit yourself to
    80-character lines.

    The [destruct] tactic can be used with any inductively defined
    datatype.  For example, we use it next 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 eqn:E.
  - 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.  This is generally considered bad style, since Coq
    often makes confusing choices of names when left to its own
    devices.

    It is sometimes useful to invoke [destruct] inside a subgoal,
    generating yet more proof obligations. In this case, we use
    different kinds of bullets to mark goals on different "levels."
    For example: *)

Theorem andb_commutative : forall b c, andb b c = andb c b.
Proof.
  intros b c. destruct b eqn:Eb.
  - destruct c eqn:Ec.
    + reflexivity.
    + reflexivity.
  - destruct c eqn:Ec.
    + reflexivity.
    + reflexivity.
Qed.

(** Each pair of calls to [reflexivity] corresponds to the
    subgoals that were generated after the execution of the [destruct c]
    line right above it. *)

(** Besides [-] and [+], we can use [*] (asterisk) as a third kind of
    bullet.  We can also enclose sub-proofs in curly braces, which is
    useful in case we ever encounter a proof that generates more than
    three levels of subgoals: *)

Theorem andb_commutative' : forall b c, andb b c = andb c b.
Proof.
  intros b c. destruct b eqn:Eb.
  { destruct c eqn:Ec.
    { reflexivity. }
    { reflexivity. } }
  { destruct c eqn:Ec.
    { reflexivity. }
    { reflexivity. } }
Qed.

(** Since curly braces mark both the beginning and the end of a
    proof, they can be used for multiple subgoal levels, as this
    example shows. Furthermore, curly braces allow us to reuse the
    same bullet shapes at multiple levels in a proof: *)

Theorem andb3_exchange :
  forall b c d, andb (andb b c) d = andb (andb b d) c.
Proof.
  intros b c d. destruct b eqn:Eb.
  - destruct c eqn:Ec.
    { destruct d eqn:Ed.
      - reflexivity.
      - reflexivity. }
    { destruct d eqn:Ed.
      - reflexivity.
      - reflexivity. }
  - destruct c eqn:Ec.
    { destruct d eqn:Ed.
      - reflexivity.
      - reflexivity. }
    { destruct d eqn:Ed.
      - reflexivity.
      - reflexivity. }
Qed.

(** Before closing the chapter, let's mention one final
    convenience.  As you may have noticed, many proofs perform case
    analysis on a variable right after introducing it:

       intros x y. destruct y as [|y] eqn:E.

    This pattern is so common that Coq provides a shorthand for it: we
    can perform case analysis on a variable when introducing it by
    using an intro pattern instead of a variable name. For instance,
    here is a shorter proof of the [plus_1_neq_0] theorem
    above.  (You'll also note one downside of this shorthand: we lose
    the equation recording the assumption we are making in each
    subgoal, which we previously got from the [eqn:E] annotation.) *)

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

(** If there are no arguments to name, we can just write [[]]. *)

Theorem andb_commutative'' :
  forall b c, andb b c = andb c b.
Proof.
  intros [] [].
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
Qed.

(** **** Exercise: 2 stars, standard (andb_true_elim2)

    Prove the following claim, marking cases (and subcases) with
    bullets when you use [destruct]. *)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
intros b c .
 simpl.
 destruct c eqn:Ec.
 {
  destruct b eqn:Eb.
  -  simpl. reflexivity.
  - reflexivity.
}
{
  destruct b eqn:Eb.
  - simpl. intros H.
  rewrite -> H.
  reflexivity.
 - simpl. intros H.
  rewrite -> H.
  reflexivity.
}
Qed.
(** [] *)

(** **** Exercise: 1 star, standard (zero_nbeq_plus_1)  *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  0 =? (n + 1) = false.
Proof.
  intros [| n].
  {
    reflexivity.
  }
  {
    reflexivity.
  }
Qed.
(** [] *)

(* ================================================================= *)
(** ** More on Notation (Optional) *)

(** (In general, sections marked Optional are not needed to follow the
    rest of the book, except possibly other Optional sections.  On a
    first reading, you might want to skim these sections so that you
    know what's there for future reference.)

    Recall the notation definitions for infix plus and times: *)

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] is
    specified by writing [at level n]; this helps Coq parse compound
    expressions.  The associativity setting helps to disambiguate
    expressions containing multiple occurrences of the same
    symbol. For example, the parameters specified above for [+] and
    [*] say that the expression [1+2*3*4] is shorthand for
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.  We will see more examples
    of this later, e.g., in the [Lists]
    chapter.

    Each notation symbol is also associated with a _notation scope_.
    Coq tries to guess what scope is meant from context, so when it
    sees [S(O*O)] it guesses [nat_scope], but when it sees the
    cartesian product (tuple) type [bool*bool] (which we'll see in
    later chapters) it guesses [type_scope].  Occasionally, it is
    necessary to help it out with percent-notation by writing
    [(x*y)%nat], and sometimes in what Coq prints 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] (the
    natural number [0] that we're using in this chapter), or [0%Z],
    which means the Integer zero (which comes from a different part of
    the standard library).

    Pro tip: Coq's notation mechanism is not especially powerful.
    Don't expect too much from it! *)

(* ================================================================= *)
(** ** Fixpoints and Structural Recursion (Optional) *)

(** Here is a copy of the definition of addition: *)

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, standard, 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 reject because
    of this restriction.  (If you choose to turn in this optional
    exercise as part of a homework assignment, make sure you comment
    out your solution so that it doesn't cause Coq to reject the whole
    file!) *)

(*

Fixpoint test' (x:nat) : nat :=
  match x with
  | 0 =>  0
  | S _ =>  match evenb(x) with
          | true => match x with
                    | S (S k') => test' k'
                    | _ => 0
                  end
          | false => test' (S x)
        end
  end.

    [] *)

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

(** Each SF chapter comes with a tester file (e.g.  [BasicsTest.v]),
    containing scripts that check most of the exercises. You can run
    [make BasicsTest.vo] in a terminal and check its output to make
    sure you didn't miss anything. *)

(** **** Exercise: 1 star, standard (indentity_fn_applied_twice)

    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 X Y.
  rewrite -> X.
  rewrite -> X.
  trivial.
Qed.
(** [] *)

(** **** Exercise: 1 star, standard (negation_fn_applied_twice)

    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 nengation_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x: bool), f x = negb x) ->
  forall (b: bool), f(f b) =b.
Proof.
  intros f X Y.
  rewrite -> X.
  rewrite -> X.
  rewrite -> negb_involutive.
  trivial.
Qed.

(* The [Import] statement on the next line tells Coq to use the
   standard library String module.  We'll use strings more in later
   chapters, but for the moment we just need syntax for literal
   strings for the grader comments. *)
From Coq Require Export String.

(* Do not modify the following line: *)
Definition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.
(** [] *)

(** **** Exercise: 3 stars, standard, optional (andb_eq_orb)

    Prove the following theorem.  (Hint: This one can be a bit tricky,
    depending on how you approach it.  You will probably need both
    [destruct] and [rewrite], but destructing everything in sight is
    not the best way.) *)

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

Definition andb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true ⇒ b2
  | false ⇒ false
  end.
*)
Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  intros b c.
 destruct b  eqn:E.
{ simpl. intro. rewrite -> H. trivial. }
{ simpl. intro. rewrite -> H. reflexivity. }
Qed.
(** [] *)

(** **** Exercise: 3 stars, standard (binary)

    We can generalize our unary representation of natural numbers to
    the more efficient binary representation by treating a binary
    number as a sequence of constructors [A] and [B] (representing 0s
    and 1s), terminated by a [Z]. For comparison, in the unary
    representation, a number is a sequence of [S]s terminated by an
    [O].

    For example:

        decimal            binary                           unary
           0                   Z                              O
           1                 B Z                            S O
           2              A (B Z)                        S (S O)
           3              B (B Z)                     S (S (S O))
           4           A (A (B Z))                 S (S (S (S O)))
           5           B (A (B Z))              S (S (S (S (S O))))
           6           A (B (B Z))           S (S (S (S (S (S O)))))
           7           B (B (B Z))        S (S (S (S (S (S (S O))))))
           8        A (A (A (B Z)))    S (S (S (S (S (S (S (S O)))))))

    Note that the low-order bit is on the left and the high-order bit
    is on the right -- the opposite of the way binary numbers are
    usually written.  This choice makes them easier to manipulate. *)

Inductive bin : Type :=
  | Z
  | A (n : bin)
  | B (n : bin).

(** (a) Complete the definitions below of an increment function [incr]
        for binary numbers, and a function [bin_to_nat] to convert
        binary numbers to unary numbers. *)

Fixpoint incr (m:bin) : bin
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Fixpoint bin_to_nat (m:bin) : nat
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

(**    (b) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.
        for your increment and binary-to-unary functions.  (A "unit
        test" in Coq is a specific [Example] that can be proved with
        just [reflexivity], as we've done for several of our
        definitions.)  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. *)

(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_binary : option (nat*string) := None.
(** [] *)

(* Wed Jan 9 12:02:44 EST 2019 *)


Inductive unit : Set :=
| tt
.

Lemma unit_singleton : forall (x:unit), x = tt.
Proof. intros x. destruct x. reflexivity. Qed.

Inductive Empty_set : Set :=.

(*
Check Empty_set_ind.
*)

Lemma the_sky_is_falling : forall (x:Empty_set), 2 + 2 = 5.
Proof. intros x. destruct x. Qed.

Definition e2u (e:Empty_set) : unit := match e with end.

Inductive bool : Set :=
| true
| false
.

Definition negb(b:bool) : bool := if b then false else true.

Lemma negb_inverse : forall (b:bool), negb (negb b) = b.
Proof. intros b. destruct b; reflexivity. Qed.

Lemma negb_ineq : forall (b:bool), negb b <> b.
Proof. destruct b; discriminate. Qed.

(*
Check bool_ind.
*)

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

Definition isZero (n:nat) : bool :=
    match n with
    | O     => true
    | S _   => false
    end.

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

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

Lemma plus_O_n : forall (n:nat), plus O n = n.
Proof. intros n. reflexivity. Qed.

Lemma plus_n_O : forall (n:nat), plus n O = n.
Proof.
    intros n. induction n as [|n IH].
    - reflexivity.
    - simpl. rewrite IH. reflexivity.
Qed.

Lemma S_inj : forall (n m:nat), S n = S m -> n = m.
Proof. intros n m H. injection H. trivial. Qed.

Inductive list (a:Set) : Set :=
| Nil  : list a
| Cons : a -> list a -> list a
.

Arguments Nil {a}.
Arguments Cons {a} _ _.

Fixpoint length (a:Set) (xs:list a) : nat :=
    match xs with
    | Nil       => O
    | Cons x ys => S (length a ys)
    end.

Arguments length {a} _.

Lemma length_test :
    length (Cons 0 (Cons 1 (Cons 2 Nil))) = S (S (S O)).
Proof. reflexivity. Qed.

Fixpoint append (a:Set) (xs ys:list a) : list a :=
    match xs with
    | Nil        => ys
    | Cons x xs' => Cons x (append a xs' ys)
    end.

Arguments append {a} _ _.

Lemma length_append : forall (a:Set) (xs ys:list a),
    length (append xs ys) = plus (length xs) (length ys).
Proof.
    intros a xs. induction xs as [|x xs IH]; intros ys; simpl.
    - reflexivity.
    - rewrite IH. reflexivity.
Qed.

Inductive btree (a:Set) : Set :=
| Leaf : btree a
| Node : btree a -> a -> btree a -> btree a
.

Arguments Leaf {a}.
Arguments Node {a} _ _ _.

Fixpoint size (a:Set) (t:btree a) : nat :=
    match t with
    | Leaf          => S O
    | Node t1 _ t2  => plus (size _ t1) (size _ t2)
    end.

Arguments size {a}.

Fixpoint splice (t1 t2:btree nat) : btree nat :=
    match t1 with
    | Leaf          => Node t2 O Leaf
    | Node s1 n s2  => Node (splice s1 t2) n s2
    end.

Lemma plus_assoc : forall (n m p:nat), plus (plus n m) p = plus n (plus m p).
Proof.
    intros n. induction n as [|n IH]; intros m p; simpl.
    - reflexivity.
    - rewrite IH. reflexivity.
Qed.

Lemma plus_n_Sm : forall (n m:nat), plus n (S m) = S (plus n m).
Proof.
    intros n. induction n as [|n IH]; intros m; simpl.
    - reflexivity.
    - rewrite IH. reflexivity.
Qed.

Lemma plus_comm : forall (n m:nat), plus n m = plus m n.
Proof.
    intros n. induction n as [|n IH]; intros m; simpl.
    - symmetry. apply plus_n_O.
    - rewrite IH. symmetry. apply plus_n_Sm.
Qed.

Lemma size_splice : forall (t1 t2:btree nat),
    size (splice t1 t2) = plus (size t1) (size t2).
Proof.
    intros t1. induction t1 as [|s1 IH1 n s2 IH2]; intros t2; simpl.
    - rewrite plus_n_Sm. rewrite plus_n_O. reflexivity.
    - rewrite IH1. rewrite plus_assoc.
      remember (plus (size t2) (size s2)) as e eqn:H.
      rewrite plus_comm in H. rewrite H. symmetry. apply plus_assoc.
Qed.

Inductive even_list (a:Set) : Set :=
| ENil  : even_list a
| ECons : a -> odd_list a -> even_list a
with odd_list (a:Set) : Set :=
| OCons : a -> even_list a -> odd_list a
.

Inductive list0 (a:Set) : Set :=
| Nil0  : list0 a
| Cons0 : a -> list2 a -> list0 a
with list1 (a:Set) : Set :=
| Cons1 : a -> list0 a -> list1 a
with list2 (a:Set) : Set :=
| Cons2 : a -> list1 a -> list2 a
.

Arguments Nil0 {a}.
Arguments Cons0 {a}.
Arguments Cons1 {a}.
Arguments Cons2 {a}.

Fixpoint length0 (a:Set) (xs: list0 a) : nat :=
    match xs with
    | Nil0       => O
    | Cons0 _ xs => S (length2 a xs)
    end
with length1 (a:Set) (xs:list1 a) : nat :=
    match xs with
    | Cons1 _ xs => S (length0 a xs)
    end
with length2 (a:Set) (xs:list2 a) : nat :=
    match xs with
    | Cons2 _ xs => S (length1 a xs)
    end
.

Arguments length0 {a}.
Arguments length1 {a}.
Arguments length2 {a}.


(* START: C *)
Definition C (A:Set) (P:A -> nat -> Prop) : Set :=
   {a : A | exists (an:nat), (P a an)}.
(* STOP: C *)
Hint Unfold C.

(* START: ret *)
Definition ret (A:Set) (P:A -> nat -> Prop) (a:A) (Pa0:P a 0) : C A P.
(* STOP: ret *)
Proof.
  exists a.
  exists 0.
  apply Pa0.
Defined.

(* START: bind *)
Definition bind (A:Set) (PA:A -> nat -> Prop)
                (B:Set) (PB:B -> nat -> Prop)
                (am:C A PA)
                (bf:forall (a:A) (pa:exists an, PA a an),
                  C B (fun b bn => forall an, PA a an -> PB b (an+bn)))
: C B PB.
(* STOP: bind *)
Proof.
  destruct am as [a Pa].
  edestruct (bf a Pa) as [b Pb].
  exists b.
  destruct Pa as [an Pa].
  destruct Pb as [bn Pb].
  exists (an + bn).
  eapply Pb.
  apply Pa.
Defined.

(* START: inc *)
Definition inc (A:Set) k (PA : A -> nat -> Prop)
           (xc:C A (fun x xn => forall xm, xn + k = xm -> PA x xm))
: C A PA.
(* STOP: inc *)
Proof.
  destruct xc as [x Px].
  exists x.
  destruct Px as [n Px].
  exists (n + k).
  apply Px.
  reflexivity.
Defined.

Notation "<== x" := (ret _ _ x _) (at level 55).
Notation "+= k ; c" := (inc _ k _ c) (at level 30, right associativity).
Notation "x <- y ; z" := (bind _ _ _ _ y (fun (x : _) (am : _) => z) )
                           (at level 30, right associativity).
Notation "x >>= y" := (bind _ _ _ _ x y) (at level 55).
Notation "x >> y" := (bind _ _ _ _ x (fun _ => y)) (at level 30, right associativity).

Notation "{! x !:! A !<! c !>!  P !}" := (C A (fun (x:A) (c:nat) => P)) (at level 55).


Require Import Blech.Defaults.

Require Import Coq.Setoids.Setoid.
Require Import Coq.Classes.SetoidClass.

Require Import Blech.Bishop.
Require Import Blech.Category.

Import BishopNotations.
Import CategoryNotations.

Open Scope bishop_scope.
Open Scope morphism_scope.

#[universes(cumulative)]
Inductive free {O} (S: O → O → Type): O → O → Type :=
| η {A B} (_: S A B): free S A B
| id A: free S A A
| compose {A B C} (f: free S B C) (g: free S A B): free S A C.

Arguments η {O S A B}.
Arguments id {O S}.
Arguments compose {O S A B C}.

Inductive equiv {O: Type} {S: O → O → Type} `{∀ A B, Setoid (S A B)} : forall {A B: O}, relation (free S A B) :=
| reflexive {A B}: reflexive _ (@equiv O S _ A B)
| symmetric {A B}: symmetric _ (@equiv O S _ A B)
| transitive {A B}: transitive _ (@equiv O S _ A B)

| η_compat {A B}: Proper (SetoidClass.equiv ==> @equiv O S _ A B) η

| compose_assoc {A B C D} (f: free S C D) (g: free S B C) (h: free S A B):
    equiv (compose f (compose g h)) (compose (compose f g) h)

| compose_id_left {A B} (f: free S A B): equiv (compose (id _) f) f
| compose_id_right {A B} (f: free S A B): equiv (compose f (id _)) f

| compose_compat {A B C}: Proper (@equiv O S _ B C ==> @equiv O S _ A B ==> @equiv O S _ A C) compose
.
Existing Instance η_compat.
Existing Instance compose_compat.

#[global]
#[program]
Instance free_Setoid O (S: O → O → Type) `(forall A B, Setoid (S A B)) A B: Setoid (@free O S A B) := {
  equiv := equiv ;
}.
Next Obligation.
Proof.
  exists.
  - apply reflexive.
  - apply symmetric.
  - apply transitive.
Qed.

Definition Free {O} (S: O → O → Type) `{∀ A B, Setoid (S A B)}: Category := {|
  Obj := O ;
  Mor A B := free S A B ;

  Mor_Setoid := free_Setoid O S _ ;

  Category.id := id ;
  Category.compose := @compose _ _ ;

  Category.compose_assoc := @compose_assoc _ _ _ ;
  Category.compose_id_left := @compose_id_left _ _ _ ;
  Category.compose_id_right := @compose_id_right _ _ _ ;
  Category.compose_compat := @compose_compat _ _ _ ;
|}.

Fixpoint ε {C: Category} {A B} (f: Free C A B): C A B :=
  match f with
  | η x => x
  | id _ => Category.id _
  | compose x y => ε x ∘ ε y
  end.


Set Implicit Arguments.

Definition default A def (x : option A) :=
  match x with
    | Some v => v
    | None => def
  end.

Definition option_dec A (x : option A) : {a | x = Some a} + {x = None}.
  destruct x.
  left.
  exists a.
  eauto.
  right.
  eauto.
Qed.

Lemma option_map_some_elim A B (f : A -> B) o b : option_map f o = Some b -> exists a, o = Some a /\ f a = b.
Proof.
  intros H.
  destruct (option_dec o) as [[a Ha]| Hn]; [rewrite Ha in H | rewrite Hn in H; discriminate]; simpl in *.
  injection H; intros; subst.
  exists a; eauto.
Qed.

Lemma option_map_some_intro A B (f : A -> B) o a b : o = Some a -> b = f a -> option_map f o = Some b.
Proof.
  intros Ho Hb.
  destruct (option_dec o) as [[a' Ha]| Hn]; [rewrite Ha in * | rewrite Hn in *; discriminate]; simpl in *.
  injection Ho; intros; subst.
  eauto.
Qed.


(*
  Copyright 2022 ZhengPu Shi
  This file is part of CoqMatrix. It is distributed under the MIT
  "expat license". You should have recieved a LICENSE file with it.

  purpose   : Signature of Vector Theory
  author    : ZhengPu Shi
  date      : 2022.06

  reference :
  1. Vector Calculus - Michael Corral
  2. https://github.com/coq/coq/blob/master/test-suite/success/Nsatz.v
     Note: there are geometrys in coq, including point, parallel, collinear, etc.
  3. (in Chinese) Higher Mathematics Study Manual - Xu Xiao Zhan, p173
     《高等数学学习手册》徐小湛，p173
 *)

Require Export BasicConfig TupleExt SetoidListListExt HierarchySetoid.
Require Export ElementType.

(* ######################################################################### *)
(** * Basic vector theory *)
Module Type BasicVectorTheory (E : ElementType).

  (* ==================================== *)
  (** ** Vector element type *)
  Export E.

  Infix "==" := (eqlistA Aeq) : list_scope.

  Open Scope nat_scope.
  Open Scope A_scope.
  Open Scope vec_scope.

  (* ==================================== *)
  (** ** Vector type and basic operations *)
  Parameter vec : nat -> Type.

  (** matrix equality *)
  Parameter veq : forall {n}, vec n -> vec n -> Prop.
  Infix "==" := veq : vec_scope.

  (** meq is equivalence relation *)
  Axiom veq_equiv : forall n, Equivalence (veq (n:=n)).

  (** Get n-th element *)
  Parameter vnth : forall {n} (v : vec n) (i : nat), A.

  (** veq and mnth should satisfy this constraint *)
  Axiom veq_iff_vnth : forall {n : nat} (v1 v2 : vec n),
      (v1 == v2) <-> (forall i, i < n -> (vnth v1 i == vnth v2 i)%A).

  (* ==================================== *)
  (** ** Convert between list and vector *)
  Parameter l2v : forall {n} (l : list A), vec n.
  Parameter v2l : forall {n}, vec n -> list A.

  Axiom v2l_length : forall {n} (v : vec n), length (v2l v) = n.

  Axiom v2l_l2v_id : forall {n} (l : list A), length l = n -> (@v2l n (@l2v n l) == l)%list.
  Axiom l2v_v2l_id : forall {n} (v : vec n), l2v (v2l v) == v.

  (* ==================================== *)
  (** ** Convert between tuples and vector *)
  Parameter t2v_2 : @T2 A -> vec 2.
  Parameter t2v_3 : @T3 A -> vec 3.
  Parameter t2v_4 : @T4 A -> vec 4.

  Parameter v2t_2 : vec 2 -> @T2 A.
  Parameter v2t_3 : vec 3 -> @T3 A.
  Parameter v2t_4 : vec 4 -> @T4 A.

  (* Axiom t2v_v2t_id_2 : forall (v : vec 2), t2v_2 (v2t_2 v) == v. *)
  (* Axiom v2t_t2v_id_2 : forall (t : A * A), v2t_2 (t2v_2 t) = t. *)

  (* ==================================== *)
  (** ** Mapping for vector *)

  (** Mapping a vector *)
  Parameter vmap : forall {n} (v : vec n) (f : A -> A), vec n.

  (** Fold a vector *)
  (*   Parameter vfold : forall {B : Type} {n} (v : vec n) (f : A -> B) (b : B), B. *)

  (** Mapping two vectors *)
  Parameter vmap2 : forall {n} (v1 v2 : vec n) (f : A -> A -> A), vec n.

End BasicVectorTheory.

(* ######################################################################### *)
(** * Ring vector theory *)

(** zero vector, vector addition, opposition, substraction, scalar multiplication,
    dot product *)
Module Type RingVectorTheory (E : RingElementType) <: BasicVectorTheory E.

  Export E.
  Include (BasicVectorTheory E).

  (** zero vector *)
  Parameter vec0 : forall n, vec n.

  (** *** Vector addition *)
  Parameter vadd : forall {n} (v1 v2 : vec n), vec n.
  Infix "+" := vadd : vec_scope.
  Axiom vadd_comm : forall {n} (v1 v2 : vec n), (v1 + v2) == (v2 + v1).
  Axiom vadd_assoc : forall {n} (v1 v2 v3 : vec n), (v1 + v2) + v3 == v1 + (v2 + v3).
  Axiom vadd_0_l : forall {n} (v : vec n), (vec0 n) + v == v.
  Axiom vadd_0_r : forall {n} (v : vec n), v + (vec0 n) == v.

  (** *** Vector opposition *)
  Parameter vopp : forall {n} (v : vec n), vec n.
  Notation "- v" := (vopp v) : vec_scope.
  Axiom vadd_opp_l : forall {n} (v : vec n), (- v) + v == vec0 n.
  Axiom vadd_opp_r : forall {n} (v : vec n), v + (- v) == vec0 n.

  (** *** Vector subtraction *)
  Parameter vsub : forall {n} (v1 v2 : vec n), vec n.
  Infix "-" := vsub : vec_scope.

  (** *** Vector scalar multiplication *)
  Parameter vcmul : forall {n} (a : A) (v : vec n), vec n.
  Parameter vmulc : forall {n} (v : vec n) (a : A), vec n.
  Infix "c*" := vcmul : vec_scope.
  Infix "*c" := vmulc : vec_scope.
  Axiom vmulc_eq_vcmul : forall {n} a (v : vec n), v *c a == a c* v.
  Axiom vcmul_assoc : forall {n} a b (v : vec n), a c* (b c* v) == (a * b)%A c* v.
  Axiom vcmul_perm : forall {n} a b (v : vec n), a c* (b c* v) == b c* (a c* v).
  Axiom vcmul_add_distr_l : forall {n} a b (v : vec n),
      (a + b)%A c* v == (a c* v) + (b c* v).
  Axiom vcmul_add_distr_r : forall {n} a (v1 v2 : vec n),
      a c* (v1 + v2) == (a c* v1) + (a c* v2).
  Axiom vcmul_0_l : forall {n} (v : vec n), A0 c* v == vec0 n.
  Axiom vcmul_1_l : forall {n} (v : vec n), A1 c* v == v.

  (** *** Vector dot product *)
  Parameter vdot : forall {n} (v1 v2 : vec n), A.

End RingVectorTheory.

(* ######################################################################### *)
(** * Decidable field vector theory *)

Module Type DecidableFieldVectorTheory (E : DecidableFieldElementType)
<: RingVectorTheory E.

  Export E.
  Include (RingVectorTheory E).

  (** veq is decidable *)
  Axiom veq_dec : forall (n : nat), Decidable (veq (n:=n)).

End DecidableFieldVectorTheory.

(** ** Others, later ... *)

(*
(** Assert that a vector is an zero vector. *)
Parameter vzero : forall {n} (v : vec n), Prop.

(** Assert that a vector is an non-zero vector. *)
Parameter vnonzero : forall {n} (v : vec n), Prop.

(** It is decidable that if a vector is zero vector. *)
Axiom vzero_dec : forall {n} (v : vec n), {vzero v} + {vnonzero v}.

(** vec0 is equal to mat0 with column 1 *)
(*   Lemma vec0_eq_mat0 : forall n, vec0 n = mat0 n 1.
  Proof. lma. Qed. *)

(** If two nonzero vectors has scalar multiplcation relation,
    then the scalar coefficient must non-zero *)
Axiom vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : vec n) k,
    vnonzero v1 -> vnonzero v2 -> (v1 = k c* v2) -> k <> A0.
 *)


Require Import Arith.
Require Import Relations.

Axiom prop_ext: forall P Q : Prop, P <-> Q -> P = Q.

(* ---------------------------------------------------------------------------- *)

(* The dual of [ultimately] is [often]. Whereas [ultimately x, P x] intuitively
   means that, once [x] is large enough, [P x] holds always, [often x, P x]
   means that it is not the case that, once [x] is large enough, [P x] is false
   always. In other words, [often x, P x] means that there exist arbitrarily
   large [x]'s such that [P x] holds. We use the positive formulation as a
   definition. The fact this is equivalent to the doubly-negated form can be
   proved by exploiting the principle of excluded middle. *)

Section Often.

Variable A : filterType.

Implicit Type P Q : pred A.

Definition often P :=
  forall Q, ultimately A Q -> exists a, P a /\ Q a.

Lemma often_characterization:
  forall P,
  ~ ultimately A (fun x => ~ P x) <-> often P.
Proof.
  unfold often. split.

  (* Left-to-right implication. *) {
  (* Reductio ad absurdum. If there did not exist [a] that satisfies [P /\ Q],
     then [~ (P /\ Q)] would hold everywhere. *)
  intros oftenP Q ultQ.
  apply not_all_not_ex. intros nPQ.
  (* Thus, [~ (P /\ Q)] would hold ultimately. *)
  specialize (filter_universe_alt nPQ). intro nPQ'.
  (* However, by hypothesis, [Q] holds ultimately. By combining these facts,
     we find that [~P] holds ultimately. *)
  assert (ultimately A (fun a => ~ P a)).
  { eapply filter_closed_under_intersection.
    - exact ultQ.
    - exact nPQ'.
    - eauto. }
  (* This contradicts the hypothesis [~ ultimately ~ P]. *)
  tauto. }

  (* Right-to-left implication. *)
  { intros H unP. destruct (H _ unP). tauto. }
Qed.

(* TEMPORARY the definition of [often] looks like a [limit] assertion. Is it one?
   Is there a connection? *)

End Often.

Arguments often : clear implicits.

(* ---------------------------------------------------------------------------- *)

(* Inclusion of filters. *)

Definition finer A (ult1 ult2 : filter A) :=
  forall P, ult2 P -> ult1 P.

(* ---------------------------------------------------------------------------- *)

(* The filter [on Q] represents validity everywhere in the set [Q].
   In other words, [on Q P] holds if and only if [Q] implies [P]. *)

Section On.

Variable A : Type.

Variable Q : pred A.

Hypothesis Qx : exists x, Q x.

Definition on : filter A :=
  fun P => forall x, Q x -> P x.

Definition mixin_on : filterMixin on.
Proof.
  unfold on.
  constructor; eauto.
  destruct Qx as [ x ? ]; exists x; eauto.
Qed.

Definition filter_on := FilterType mixin_on.

Goal ultimately filter_on = on.
Proof. reflexivity. Qed.

Lemma onP:
  forall P : pred A,
  ultimately filter_on P =
  forall x, Q x -> P x.
Proof. reflexivity. Qed.

End On.

(* ---------------------------------------------------------------------------- *)

(* As a special case, [on (fun _ => True)] is the universal quantifier. *)

Section Forall.

Variable A : Type.

Variable x : A.

Definition _forall :=
  on (fun (_: A) => True).

Definition filter_forall :=
  filter_on (ex_intro _ x I).

Goal ultimately filter_forall = _forall.
Proof. reflexivity. Qed.

Lemma forallP:
  forall P : pred A,
  ultimately filter_forall P =
  forall x, P x.
Proof.
  intros P. unfold filter_forall. rewrite onP.
  apply prop_ext. intuition.
Qed.

End Forall.

(* ---------------------------------------------------------------------------- *)

(* The (infinite) union of a decreasing family of filters is a filter. *)

Section Union.

Variable A : Type.

Variable ult : nat -> filter A.

Variable mixin : forall i, filterMixin (ult i).

Variable decreasing : forall i j, i <= j -> finer (ult j) (ult i).

Definition union : filter A :=
  fun P => exists i, ult i P.

Definition mixin_union : filterMixin union.
Proof.
  unfold union.
  constructor.
  { exists 0. destruct (mixin 0). eauto. }
  { intros P [ i ? ]. destruct (mixin i). eauto. }
  { intros P1 P2 P [ i1 h1 ] [ i2 h2 ] ?.
    exists (max i1 i2).
    destruct (mixin (max i1 i2)) as [ _ _ inter ].
    eapply inter; [| | eauto].
    { eapply decreasing; [ |eauto].
      apply Nat.le_max_l. }
    { eapply decreasing; [ |eauto].
      apply Nat.le_max_r. }
  }
Qed.

Definition filter_union := FilterType mixin_union.

Goal ultimately filter_union = union.
Proof. reflexivity. Qed.

Lemma unionP:
  forall P,
  ultimately filter_union P =
  exists i, ult i P.
Proof. reflexivity. Qed.

End Union.

(* ---------------------------------------------------------------------------- *)

(* Going up in an ordered set. *)

(* TEMPORARY maybe define [at_and_above i] first, then take the union? *)

Section Up.

Variable A : Type.

Variable le : A -> A -> Prop.

Hypothesis le_refl : reflexive A le.
Hypothesis le_trans : transitive A le.

Variable x : nat -> A.

Variable increasing : forall i j, i <= j -> le (x i) (x j).

Definition up : filter A :=
  union (fun i => on (le (x i))).

Definition mixin_up : filterMixin up.
Proof.
  apply mixin_union.
  { intros i. apply mixin_on. eauto. }
  { unfold on. intros i j ij P. eauto. }
Qed.

Definition filter_up := FilterType mixin_up.

Goal ultimately filter_up = up.
Proof. reflexivity. Qed.

Lemma upP:
  forall P,
  ultimately filter_up P =
  exists i, forall y, le (x i) y -> P y.
Proof. reflexivity. Qed.

(* TEMPORARY used? *)
Lemma prove_up:
  forall i,
  ultimately filter_up (fun y => le (x i) y).
Proof. intros i. unfold filter_up. exists i. unfold on. eauto. Qed.

End Up.

(* ---------------------------------------------------------------------------- *)

(* The standard filter on [nat]. *)

Definition up_nat : filter nat :=
  up le id.

Definition filter_up_nat :=
  filter_up le_refl le_trans (fun i j : nat => id).

Goal
  forall P : pred nat,
  (ultimately filter_up_nat P) =
  exists n, forall x, n <= x -> P x.
Proof.
  intros P. unfold filter_up_nat. rewrite upP. reflexivity.
Qed.

Goal ultimately filter_up_nat (fun x => 42 <= x).
Proof. exists 42. unfold on. tauto. Qed.

Goal ultimately filter_up_nat (fun x => 42 <= x).
Proof. unfold filter_up_nat. rewrite upP. exists 42. tauto. Qed.

(* ---------------------------------------------------------------------------- *)

(* Applying a function [f] to a filter [ult] produces another filter, known as
   the image of [ult] under [f]. *)

Section Image.

  Variables A B : Type.

  Variable f : A -> B.

  Variable ult : filter A.

  Definition image : filter B :=
    fun P => ult (fun x => P (f x)).

  Definition mixin_image : filterMixin ult -> filterMixin image.
  Proof.
    intros [ Huniverse Hnonempty Hclosed ].
    unfold image.
    econstructor; eauto.
    intros P H. pose proof (Hnonempty _ H) as [ ? ? ].
    eauto.
  Qed.

End Image.

Definition filter_image (A : filterType) B (f : A -> B) :=
  FilterType (mixin_image f (mixin A)).

Lemma imageP:
  forall (A : filterType) B (f : A -> B),
  forall P,
  ultimately (filter_image f) P =
  ultimately A (fun x => P (f x)).
Proof. reflexivity. Qed.

(* ---------------------------------------------------------------------------- *)

(* A notion of limit, or convergence, or divergence -- it all depends on which
   filters one uses. The assertion [limit f] states that any property [P] that
   is ultimately true of [y] is ultimately true of [f x]. If [f] is a function
   from [nat] to [nat], equipped with its standard filter, this means that [f x]
   tends to infinity as [x] tends to infinity. *)

(* [limit] could take two arguments of type [filter A] and [filter B]. Instead,
   we take two arguments of type [filterType]. *)

Section Limit.

Variables A B : filterType.

Variable f : A -> B.

Definition limit :=
  finer (ultimately (filter_image f)) (ultimately B).

Lemma limitP:
  limit =
  forall P,
  (ultimately B (fun y => P y)) ->
  (ultimately A (fun x => P (f x))).
Proof.
  reflexivity.
Qed.

End Limit.

Arguments limit : clear implicits.

Lemma limit_id:
  forall A : filterType,
  limit A A (fun a : A => a).
Proof.
  intros A. rewrite limitP. tauto.
Qed.

(* TEMPORARY how about proving on a lemma on the limit of a
   function composition? *)

Goal limit filter_up_nat filter_up_nat (fun x => x + 1).
Proof.
  intros P. unfold filter_up_nat. rewrite upP. rewrite imageP.
  intros [ n Px ]. exists n.
  intros x ?. apply Px.
  auto with arith.
Qed.

(* ---------------------------------------------------------------------------- *)

Section Within.

(* If we have a filter on [A], and if [P] is a subset of [A], then [within P] is
   also a filter on [A]. By definition, a formula [Q] is ultimately holds within
   [P] if and only if [P -> Q] is ultimately true. *)

(* There is a condition on [P], though. The formula [P] must not forbid `going
   to the limit' in the sense of [ultimately]. To take a concrete example, if
   our initial filter is [up_nat], then it would not make sense for [P] to be
   the property [fun n => n <= k]. If we did choose such a [P], then [within P]
   would be a filter that says ``when [n] tends towards infinity while remaining
   under [k]''. This makes no sense.

   What is an appropriate condition on [P]? We could require [ultimately P], but
   that would be too strong; if ultimately [P] holds, then ultimately [P -> Q]
   is equivalent to ultimately [Q]. (Another way to see that this is wrong is to
   take an example where [P] is [fun (i, n) => i <= n]. This property does not
   hold ultimately, yet it does make sense.)

   An appropriate condition seems to be [~ ultimately ~ P], also known as [often
   P]. Indeed, if [P] is ultimately false, this means that [P] `forbids going to
   the limit'. We can see that if [P] is ultimately false, then [P -> Q] is
   ultimately true, regardless of [Q], and that is not a good thing, as we
   expect [ultimately (P -> Q)] to imply something about [Q]. Technically, the
   condition [often P] seems to be exactly what is needed in order to prove that
   [within P] does not accept an empty [Q]. *)

Variable A : filterType.

Variable P : pred A.

Hypothesis oftenP : often A P.

Definition within : filter A :=
  fun Q => ultimately A (fun x => P x -> Q x).

Definition mixin_within : filterMixin within.
Proof.
  unfold within.
  constructor.
  { apply filter_universe_alt. tauto. }
  { intros Q hPQ. destruct (oftenP hPQ) as [x [? ?]].
    eauto. }
  { intros Q1 Q2 Q hPQ1 hPQ2 ?.
    eapply filter_closed_under_intersection.
    - exact hPQ1.
    - exact hPQ2.
    - eauto. }
Qed.

Definition filter_within := FilterType mixin_within.

Goal ultimately filter_within = within.
Proof. reflexivity. Qed.

Lemma withinP:
  forall Q,
  ultimately filter_within Q =
  ultimately A (fun x => P x -> Q x).
Proof. reflexivity. Qed.

End Within.

Arguments within : clear implicits.

Section FilterProduct.

(* ... *)

(* When the pair [a1, a2] goes to infinity, its components go to infinity. *)

Lemma limit_fst:
  limit filter_product A1 fst.
Proof.
  unfold limit. simpl. unfold image. unfold product. simpl. unfold finer.
  intros P1 ?.
  exists P1. exists (fun _ => True).
  repeat split; eauto. apply filter_universe.
Qed.

Lemma limit_snd:
  limit filter_product A2 snd.
Proof.
  unfold limit. simpl. unfold image. unfold product. simpl. unfold finer.
  intros P2 ?.
  exists (fun _ => True). exists P2.
  repeat split; eauto. apply filter_universe.
Qed.

(* When both components go to infinity, the pair goes to infinity. *)

(* The limit of a pair is a pair of the limits. *)

Lemma limit_pair :
  forall A : filterType,
  forall (f1 : A -> A1) (f2 : A -> A2),
  limit A A1 f1 ->
  limit A A2 f2 ->
  limit A filter_product (fun a => (f1 a, f2 a)).
Proof.
  unfold limit. simpl. unfold image. unfold product. unfold finer.
  intros A f1 f2 lf1 lf2 P (P1 & P2 & uP1 & uP2 & ?).
  eapply filter_closed_under_intersection.
  { apply lf1. apply uP1. }
  { apply lf2. apply uP2. }
  eauto.
Qed.

End FilterProduct.

(* ---------------------------------------------------------------------------- *)

(* The product of two [up]-filters is the [up]-filter for the product ordering. *)

Section FilterProductUp.

Variable A1 A2 : Type.

Variable le1 : A1 -> A1 -> Prop.
Variable le2 : A2 -> A2 -> Prop.

Hypothesis le_refl1 : reflexive A1 le1.
Hypothesis le_trans1 : transitive A1 le1.
Hypothesis le_refl2 : reflexive A2 le2.
Hypothesis le_trans2 : transitive A2 le2.

Variable x1 : nat -> A1.
Variable x2 : nat -> A2.

Variable increasing1 : forall i j, i <= j -> le1 (x1 i) (x1 j).
Variable increasing2 : forall i j, i <= j -> le2 (x2 i) (x2 j).

Notation filter1 := (filter_up le_refl1 le_trans1 increasing1).
Notation filter2 := (filter_up le_refl2 le_trans2 increasing2).
Notation filter  := (filter_product filter1 filter2).

(* TEMPORARY this is not the right place to define the product of two orderings
   and prove its basic properties. *)
Definition prod_le (x y : A1 * A2) : Prop :=
  let (x1, x2) := x in
  let (y1, y2) := y in
  le1 x1 y1 /\ le2 x2 y2.

Lemma prod_le_refl: reflexive (A1 * A2) prod_le.
Proof. intros [? ?]. unfold prod_le. split. apply le_refl1. apply le_refl2. Qed.

Lemma prod_le_trans: transitive (A1 * A2) prod_le.
Proof.
  do 3 (intros [ ? ? ]). unfold prod_le.
  intros [ h1 h2 ]. intros [ i1 i2 ].
  split; [eapply le_trans1 | eapply le_trans2]; eauto.
Qed.

Lemma prod_le_increasing:
  forall i j, i <= j -> prod_le (x1 i, x2 i) (x1 j, x2 j).
Proof. intros i j ?. unfold prod_le. eauto. Qed.

Lemma product_upP:
  forall Q : pred (A1 * A2),
  ultimately filter Q =
  ultimately (filter_up prod_le_refl prod_le_trans prod_le_increasing) Q.
Proof.
  intros Q.
  (* RHS. *)
  rewrite upP.
  (* LHS. *)
  unfold ultimately. simpl. unfold product.
  (* Split. *)
  apply prop_ext. split.

  (* Left to right. *)
  { intros (P1 & P2 & uP1 & uP2 & hQ).
    rewrite upP in uP1. destruct uP1 as [ i1 hP1 ].
    rewrite upP in uP2. destruct uP2 as [ i2 hP2 ].
    exists (max i1 i2).
    intros [ y1 y2 ].
    intros [ hy1 hy2 ].
    apply hQ.
    { apply hP1. apply (@le_trans1 _ (x1 (max i1 i2))).
      apply increasing1. apply Nat.le_max_l. assumption. }
    { apply hP2. apply (@le_trans2 _ (x2 (max i1 i2))).
      apply increasing2. apply Nat.le_max_r. assumption. }
  }

  (* Right to left. *)
  { intros [ i hQ ].
    exists (le1 (x1 i)).
    exists (le2 (x2 i)).
    repeat split; try (exists i; unfold on; tauto).
    intros a1 a2 ha1 ha2.
    apply hQ. split; [apply ha1 | apply ha2]. }
Qed.

End FilterProductUp.

Goal
  ultimately (filter_product filter_up_nat filter_up_nat)
    (fun p : nat * nat =>
      let (x, y) := p in
      (42 <= x) /\ (64 <= y)).
Proof.
  unfold filter_up_nat.
  rewrite product_upP. rewrite upP.
  exists 64.
  intros [ x y ].
  unfold prod_le.
  omega.
Qed.

Goal
  ultimately (filter_product filter_up_nat filter_up_nat)
    (fun p : nat * nat =>
      let (x, y) := p in
      (42 <= x) /\ (64 <= y)).
Proof.
  simpl. unfold product.
  exists (fun x	=> 42 <= x).
  exists (fun y => 64 <= y).
  unfold filter_up_nat.
  repeat split.
  { rewrite upP. eauto. }
  { rewrite upP. eauto. }
  eauto. eauto.
Qed.

(* ---------------------------------------------------------------------------- *)

(* Canonical filter for a preorder in a meet-semilattice. *)

(* TEMPORARY this should be defined somewhere else *)
Definition with_upper_bounds A (le: A -> A -> Prop) :=
  forall x y, exists z, le x z /\ le y z.

Arguments with_upper_bounds : clear implicits.

Definition inhab A :=
  exists (x: A), True.

Section Canonical.

Variable A : Type.

Hypothesis A_inhab: inhab A.

Variable le : A -> A -> Prop.

Hypothesis le_refl : reflexive A le.
Hypothesis le_trans : transitive A le.
Hypothesis le_ub : with_upper_bounds A le.

Definition canonical : filter A :=
  fun P => exists x0, forall x, le x0 x -> P x.

Definition mixin_canonical : filterMixin canonical.
Proof.
  unfold canonical.
  constructor.
  { destruct A_inhab as [ x0 _ ]. exists x0. tauto. }
  { intros P [ x0 H ]. exists x0. apply H. apply le_refl. }
  { intros P1 P2 P [ x0 H1 ] [ y0 H2 ] H.
    pose proof (le_ub x0 y0) as [z0 [le_x0_z0 le_y0_z0]].
    exists z0. intros.
    apply H; [apply H1 | apply H2]; apply (@le_trans _ z0); tauto. }
Qed.

Definition filter_canonical := FilterType mixin_canonical.

Goal ultimately filter_canonical = canonical.
Proof. reflexivity. Qed.

Lemma canonicalP:
  forall P,
  ultimately filter_canonical P =
  exists x0, forall x, le x0 x -> P x.
Proof. reflexivity. Qed.

End Canonical.

(* ---------------------------------------------------------------------------- *)

(* The standard filter on [nat], defined using [canonical]. *)

Definition canonical_nat : filter nat :=
  canonical le.

Lemma le_ub : with_upper_bounds nat le.
Proof.
  unfold with_upper_bounds. intros x y.
  exists (max x y). split.
  - apply Nat.le_max_l.
  - apply Nat.le_max_r.
Qed.

Definition filter_canonical_nat :=
  filter_canonical (ex_intro _ 0 I) le_refl le_trans le_ub.

Goal
  forall P : pred nat,
  (ultimately filter_canonical_nat P) =
  exists n, forall x, n <= x -> P x.
Proof.
  intros P. unfold filter_canonical_nat. rewrite canonicalP. reflexivity.
Qed.

Goal ultimately filter_canonical_nat (fun x => 42 <= x).
Proof. exists 42. tauto. Qed.

Goal ultimately filter_canonical_nat (fun x => 42 <= x).
Proof. unfold filter_canonical_nat. rewrite canonicalP. exists 42. tauto. Qed.

(* ---------------------------------------------------------------------------- *)

(* The product of two [canonical]-filters is the [canonical]-filter for the
   product ordering. *)

Section FilterProductCanonical.

Variable A1 A2 : Type.

Hypothesis A1_inhab : inhab A1.
Hypothesis A2_inhab : inhab A2.

Variable le1 : A1 -> A1 -> Prop.
Variable le2 : A2 -> A2 -> Prop.

Hypothesis le_refl1 : reflexive A1 le1.
Hypothesis le_trans1 : transitive A1 le1.
Hypothesis le_refl2 : reflexive A2 le2.
Hypothesis le_trans2 : transitive A2 le2.
Hypothesis le_ub1 : with_upper_bounds A1 le1.
Hypothesis le_ub2 : with_upper_bounds A2 le2.

Notation filter1 := (filter_canonical A1_inhab le_refl1 le_trans1 le_ub1).
Notation filter2 := (filter_canonical A2_inhab le_refl2 le_trans2 le_ub2).
Notation filter  := (filter_product filter1 filter2).

(* TEMPORARY this should be defined someplace else *)
Lemma A1A2_inhab : inhab (A1 * A2).
Proof.
  destruct A1_inhab as [ a1 _ ]. destruct A2_inhab as [ a2 _ ].
  exists (a1, a2). tauto.
Qed.

Lemma prod_le_ub : with_upper_bounds (A1 * A2) (prod_le le1 le2).
Proof.
  unfold with_upper_bounds.
  intros [x0 y0] [x1 y1].
  pose proof (le_ub1 x0 x1) as [zx [? ?]].
  pose proof (le_ub2 y0 y1) as [zy [? ?]].
  exists (zx, zy). unfold prod_le. eauto.
Qed.

Lemma product_canonicalP:
  forall Q : pred (A1 * A2),
  ultimately filter Q =
  ultimately
    (filter_canonical
       A1A2_inhab
       (prod_le_refl le_refl1 le_refl2)
       (prod_le_trans le_trans1 le_trans2)
       prod_le_ub)
    Q.
Proof.
  intros Q.
  (* RHS. *)
  rewrite canonicalP.
  (* LHS. *)
  unfold ultimately. simpl. unfold product.
  (* Split. *)
  apply prop_ext. split.

  (* Left to right. *)
  { intros (P1 & P2 & uP1 & uP2 & hQ).
    rewrite canonicalP in uP1. destruct uP1 as [ x0 hP1 ].
    rewrite canonicalP in uP2. destruct uP2 as [ y0 hP2 ].
    exists (x0, y0).
    intros [ x y ]. unfold prod_le.
    intros [ hx hy ].
    apply hQ; eauto. }

  (* Right to left. *)
  { intros [ [ x0 y0 ] hQ ].
    exists (le1 x0).
    exists (le2 y0).
    repeat split. rewrite canonicalP.
    - exists x0. tauto.
    - exists y0. tauto.
    - intros a1 a2 ha1 ha2.
      apply hQ. split; [apply ha1 | apply ha2]. }
Qed.

End FilterProductCanonical.

Goal
  ultimately (filter_product filter_canonical_nat filter_canonical_nat)
    (fun p : nat * nat =>
      let (x, y) := p in
      (42 <= x) /\ (64 <= y)).
Proof.
  unfold filter_canonical_nat.
  rewrite product_canonicalP. rewrite canonicalP.
  exists (42, 64).
  intros [ x y ].
  unfold prod_le.
  tauto.
Qed.

Goal
  ultimately (filter_product filter_canonical_nat filter_canonical_nat)
    (fun p : nat * nat =>
      let (x, y) := p in
      (42 <= x) /\ (64 <= y)).
Proof.
  simpl. unfold product.
  exists (fun x	=> 42 <= x).
  exists (fun y => 64 <= y).
  unfold filter_canonical_nat.
  repeat split.
  { rewrite canonicalP. eauto. }
  { rewrite canonicalP. eauto. }
  eauto. eauto.
Qed.

(* ---------------------------------------------------------------------------- *)

Module OrderedFilter.

Record mixin_of (A : filterType) : Type := Mixin {
  le : binary A;
  _ : forall x : A, ultimately A (fun y => le x y)
}.

Section ClassDef.

Record class_of (A : Type) : Type := Class {
  base : Filter.class_of A;
  mixin : mixin_of (Filter.Pack base)
}.

Structure type := Pack { sort : Type; class : class_of sort }.

Definition filterType (cT : type) := @Filter.Pack (sort cT) (base (class cT)).
(* TEMPORARY (?) this definition looks natural, but does not match (at least *)
(*    obviously) the way similar ones are written in ssreflect *)

End ClassDef.

Module Exports.
Coercion base : class_of >-> Filter.class_of.
Coercion mixin : class_of >-> mixin_of.
Coercion sort : type >-> Sortclass.
Coercion filterType : type >-> Filter.type.
Notation orderedFilterType := type.
Notation OrderedFilterType T m := (@Pack T m).
Notation OrderedFilterMixin := Mixin.
End Exports.

End OrderedFilter.
Export OrderedFilter.Exports.

Definition filter_le T := OrderedFilter.le (OrderedFilter.class T).
Arguments filter_le : clear implicits.

Section OrderedFilterLaws.

Variable A : orderedFilterType.

Lemma orderedFilterP :
  forall x, ultimately A (fun y => filter_le A x y).
Proof.
  destruct A as [? [? M]]. destruct M. eauto.
Qed.

End OrderedFilterLaws.

Arguments orderedFilterP : clear implicits.

Section OrderedFilterProduct.

Variable A1 A2 : orderedFilterType.

Definition product_orderedFilterMixin :
  OrderedFilter.mixin_of (product_filterType A1 A2).
Proof.
  eapply OrderedFilter.Mixin with
    (prod2 (filter_le A1) (filter_le A2)).
  intros [ x1 x2 ].
  forwards H1: orderedFilterP A1 x1.
  forwards H2: orderedFilterP A2 x2.
  rewrite productP. do 2 eexists. splits; [apply H1 | apply H2 | ..].
  unfold prod2. eauto.
Defined.

Definition product_orderedFilterClass :
  OrderedFilter.class_of (product_filterType A1 A2).
Proof.
  eapply OrderedFilter.Class with
    (Filter.class (product_filterType A1 A2)).
  apply product_orderedFilterMixin.
Defined.

Definition product_orderedFilterType :=
  OrderedFilterType (A1 * A2) product_orderedFilterClass.

End OrderedFilterProduct.

Lemma productOrdP :
  forall (A1 A2 : orderedFilterType) P,
  ultimately (product_orderedFilterType A1 A2) P =
  (exists P1 P2,
   ultimately A1 P1 /\
   ultimately A2 P2 /\
   (forall a1 a2, P1 a1 -> P2 a2 -> P (a1, a2))).
Proof. reflexivity. Qed.

Lemma productOrdLeP :
  forall A1 A2 p1 p2,
  filter_le (product_orderedFilterType A1 A2) p1 p2 =
  (filter_le A1 (fst p1) (fst p2) /\ filter_le A2 (snd p1) (snd p2)).
Proof. intros ? ? [? ?] [? ?]. reflexivity. Qed.


Require Export GeoCoq.Elements.OriginalProofs.lemma_TGsymmetric.

Section Euclid.

Context `{Ax:euclidean_neutral_ruler_compass}.

Lemma lemma_TTorder :
   forall A B C D E F G H,
   TT A B C D E F G H ->
   TT C D A B E F G H.
Proof.
intros.
let Tf:=fresh in
assert (Tf:exists J, (BetS E F J /\ Cong F J G H /\ TG A B C D E J)) by (conclude_def TT );destruct Tf as [J];spliter.
assert (TG C D A B E J) by (conclude lemma_TGsymmetric).
assert (TT C D A B E F G H) by (conclude_def TT ).
close.
Qed.

End Euclid.


Require Export D.

(** **** Problem #7 : 2 stars (split) *)
(** The function [split] is the right inverse of combine: it takes a
    list of pairs and returns a pair of lists.  In many functional
    programing languages, this function is called [unzip].

    Uncomment the material below and fill in the definition of
    [split].  Make sure it passes the given unit tests. *)

Fixpoint split
           {X Y : Type} (l : list (X*Y))
           : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | (a, b)::tl  => (a::fst(split tl), b::snd(split tl))
  end.

Example test_split:
  split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof. reflexivity.  Qed.

Theorem split_map: forall X Y (l: list (X*Y)),
   fst (split l) = map fst l.
Proof.
  intros. induction l. reflexivity. destruct x. simpl. rewrite->IHl. reflexivity.
Qed.