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

(* REMINDER:

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

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

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

(** The functional style of programming 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 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 _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 native functional programming language, called
	_Gallina_.  The second half introduces some basic _tactics_ that
	can be used to prove properties of Gallina 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 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, this course we will explicitly recapitulate
	(almost) all the definitions we need, rather than getting them
	from the standard 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 set of data values -- a _type_. *)

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

(** The new 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 point 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 next check that it
	works on some examples.  There are actually three different ways
	to do the examples 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 it 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 just now, 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."

	Third, we can ask Coq to _extract_, from our [Definition], a
	program in another, more conventional, programming
	language (OCaml, Scheme, or Haskell) with a high-performance
	compiler.  This facility is very interesting, since it gives us a
	path 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 (and
	give you 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; 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.
	  - If you introduce a helper lemma that you end up being unable
		to prove, hence end it with [Admitted], then make sure to also
		end the main theorem in which you use it with [Admitted], not
		[Qed].  That will help you get partial credit, in case you
		use that main theorem to solve a later exercise.

	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
	tools, but you may also want 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

	See the end of this chapter for more information about how to interpret
	the output of test scripts.

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

(** The [Require Export] statement on the next line tells Coq to use
	the [String] module from the standard library.  We'll use strings
	ourselves in later chapters, but we need to [Require] it here so
	that the grading scripts can use it for internal purposes. *)
From Coq Require Export String.

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

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

Inductive bool : Type :=
  | true
  | false.

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

(** (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.  Whenever possible,
	we'll name our own definitions and theorems so that they exactly
	coincide with the ones in the standard library.) *)

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

(** These examples are also an opportunity to introduce one more small
	feature of Coq's programming language: conditional expressions... *)

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

Definition andb' (b1:bool) (b2:bool) : bool :=
  if b1 then b2
  else false.

Definition orb' (b1:bool) (b2:bool) : bool :=
  if b1 then true
  else b2.

(** Coq's conditionals are exactly like those found in any other
	language, with one small generalization.  Since the [bool] type is
	not built in, Coq actually supports conditional expressions over
	_any_ inductively defined type with exactly two clauses in its
	definition.  The guard is considered true if it evaluates to the
	"constructor" of the first clause of the [Inductive]
	definition (which just happens to be called [true] in this case)
	and false if it evaluates to the second. *)

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

	The command [Admitted] can be used as a placeholder for an
	incomplete proof.  We 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.

	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, and make sure Coq accepts it.) The
	function should return [true] if either or both of its inputs are
	[false]. *)

Definition nandb (b1:bool) (b2:bool) : bool := negb (b1 && b2).

Example test_nandb1:               (nandb true false) = true.
Proof. auto. Qed.
Example test_nandb2:               (nandb false false) = true.
Proof. auto. Qed.
Example test_nandb3:               (nandb false true) = true.
Proof. auto. Qed.
Example test_nandb4:               (nandb true true) = false.
Proof. auto. 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 := b1 && b2 && b3.

Example test_andb31:                 (andb3 true true true) = true.
Proof. auto. Qed.
Example test_andb32:                 (andb3 false true true) = false.
Proof. auto. Qed.
Example test_andb33:                 (andb3 true false true) = false.
Proof. auto. Qed.
Example test_andb34:                 (andb3 true true false) = false.
Proof. auto. 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 *)

(** If the expression after [Check] is followed by a colon and a type,
	Coq will verify that the type of the expression matches the given
	type and halt with an error if not. *)

Check true
  : bool.
Check (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
  : bool -> bool.

(** The type of [negb], written [bool -> bool] and pronounced
	"[bool] arrow [bool]," can be read, "Given an input of type
	[bool], this function produces an output of type [bool]."
	Similarly, the type of [andb], written [bool -> bool -> bool], can
	be read, "Given two inputs, each 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, called _constructors_.  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.

	An [Inductive] definition does two things:

	- It defines a set of new _constructors_. E.g., [red],
	  [primary], [true], [false], [monday], etc. are constructors.

	- It groups them into a new named type, like [bool], [rgb], or
	  [color].

	_Constructor expressions_ are formed by applying a constructor
	to zero or more other constructors or constructor expressions,
	obeying the declared number and types of the constructor arguments.
	E.g.,
		- [red]
		- [true]
		- [primary red]
		- etc.
	But not
		- [red primary]
		- [true red]
		- [primary (primary red)]
		- etc.
*)

(** In particular, the definitions of [rgb] and [color] say
	which constructor expressions belong to the sets [rgb] and
	[color]:

	- [red], [green], and [blue] belong to the set [rgb];
	- [black] and [white] belong to the set [color];
	- if [p] is a constructor expression belonging to the set [rgb],
	  then [primary p] (pronounced "the constructor [primary] applied
	  to the argument [p]") is a constructor expression belonging to
	  the set [color]; and
	- constructor 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 did for [day] and [bool]. *)

Definition monochrome (c : color) : bool :=
  match c with
  | black => true
  | white => true
  | primary p => 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 "the constructor
	[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].) *)

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

(** Coq provides a _module system_ to aid in organizing large
	developments.  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 limit the scope of definitions, so that we are free to
	reuse names. *)

Module Playground.
  Definition b : rgb := blue.
End Playground.

Definition b : bool := true.

Check Playground.b : rgb.
Check b : bool.

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

Module TuplePlayground.

(** 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)
  : 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 [B0].  We
	use 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 *)

End TuplePlayground.

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

(** We put this section in a module so that our own definition of
	natural numbers does not interfere with the one from the
	standard library.  In the rest of the book, we'll want to use
	the standard library's. *)

Module NatPlayground.

(** All the types we have defined so far -- both "enumerated
	types" such as [day], [bool], and [bit] and tuple types such as
	[nybble] built from them -- are finite.  The natural numbers, on
	the other hand, are an infinite set, so we'll need to use a
	slightly richer form of type declaration to represent them.

	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 as our
	representation natural numbers. Indeed, there are circumstances
	where each of these choices would be useful.

	The binary representation is valuable in computer hardware because
	the digits can be represented with just two distinct voltage
	levels, resulting in simple circuitry. Analogously, we wish here
	to choose a representation that makes _proofs_ simpler.

	In fact, 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 to count days in prison by scratching on
	the walls). To represent unary numbers 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, where [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. *)

(** Informally, the clauses of the definition can be read:
	  - [O] is a natural number (remember 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:

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

(** These conditions are the precise force of the [Inductive]
	declaration.  They imply that the constructor expression [O], the
	constructor expression [S O], the constructor expression [S (S
	O)], the constructor expression [S (S (S O))], and so on all
	belong to the set [nat], while other constructor expressions, 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']."  *)

(** The following [End] command closes the current module, so
	[nat] will refer back to the type from the standard library. *)

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 functions
	such as [pred] and [minustwo]: *)

Check S        : nat -> nat.
Check pred     : nat -> nat.
Check minustwo : nat -> nat.

(** These are all things that can be applied to a number to yield a
	number.  However, there is a fundamental difference between [S]
	and the other two: functions like [pred] and [minustwo] are
	defined by giving _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.)

	Now let's go on and define some more functions over numbers.

	For most interesting computations involving numbers, simple
	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.  Such functions are
	introduced with the keyword [Fixpoint] instead of [Definition]. *)

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

(** We could define [odd] by a similar [Fixpoint] declaration, but
	here is a simpler way: *)

Definition odd (n:nat) : bool :=
  negb (even n).

Example test_odd1:    odd 1 = true.
Proof. simpl. reflexivity.  Qed.
Example test_odd2:    odd 4 = false.
Proof. simpl. reflexivity.  Qed.

(** (You may 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 discuss 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).
(* ===> 5 : nat *)

(** The steps of simplification that Coq performs can be
	visualized as follows: *)

(*      [plus 3 2]
   i.e. [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]
   i.e. [5]  *)

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

(** **** 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
	| O => S O
	| S n' => n * factorial n'
  end.

Example test_factorial1:          (factorial 3) = 6.
Proof. auto. Qed.
Example test_factorial2:          (factorial 5) = (mult 10 12).
Proof. auto. 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) : nat.

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

	Note that these declarations 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.

(** We'll be using these (especially [eqb]) a lot, so 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.

(** We now have two symbols that look like equality: [=] and
	[=?].  We'll have much more to say about the differences and
	similarities between them later. For now, the main thing to notice
	is that [x = y] is a logical _claim_ -- a "proposition" -- that we
	can try to prove, while [x =? y] is an _expression_ whose
	value (either [true] or [false]) we can compute. *)

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

Definition ltb (n m : nat) : bool := andb (negb (n =? m)) (leb n m).

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

Example test_ltb1:             (ltb 2 2) = false.
Proof. auto. Qed.
Example test_ltb2:             (ltb 2 4) = true.
Proof. auto. Qed.
Example test_ltb3:             (ltb 4 2) = false.
Proof. auto. 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. In [.v] files, we write the universal quantifier
	[forall] using the reserved identifier "forall."  When the [.v]
	files are converted to HTML, this gets transformed into the
	standard upside-down-A symbol.)

	This is a good place to mention that [reflexivity] is a bit more
	powerful than we have acknowledged. 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 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. Note that we could have used
	another identifier instead of [n] in the [intros] clause, (though
	of course this might be confusing to human readers of the proof): *)

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

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

(** The following theorem is a bit more interesting than the
	ones 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.
	In fact, you can omit the arrow, and Coq will default to rewriting
	in this direction.  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. *)

(* SOOMER: KK: [plus_id_exercise] contains multiple hypotheses, and at
   least one student was confused about this. Maybe we can talk about
   [->] being right-associative before it. *)

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

(** The [Check] command can also be used to examine the statements of
	previously declared lemmas and theorems.  The two examples below
	are lemmas about multiplication that are proved in the standard
	library.  (We will see how to prove them ourselves in the next
	chapter.) *)

Check mult_n_O.
(* ===> forall n : nat, 0 = n * 0 *)

Check mult_n_Sm.
(* ===> forall n m : nat, n * m + n = n * S m *)

(** We can 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_n_0_m_0 : forall p q : nat,
  (p * 0) + (q * 0) = 0.
Proof.
  intros p q.
  rewrite <- mult_n_O.
  rewrite <- mult_n_O.
  reflexivity. Qed.

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

	Use those two lemmas about multiplication that we just checked to
	prove the following theorem.  Hint: recall that [1] is [S O]. *)

Theorem mult_n_1 : forall p : nat,
  p * 1 = p.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)

(* ################################################################# *)
(** * 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] represents, 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 the two
	generated subgoals.  The part of the proof script that comes after
	a bullet is the entire proof for the corresponding 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 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, improving
	readability. 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 -- e.g., 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 a single line.  Good style lies
	somewhere in the middle.  One reasonable guideline 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.  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) or any repetition
	of a bullet symbol (e.g. [--] or [***]) as a bullet.  We can also
	enclose sub-proofs in curly braces: *)

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. The choice of braces,
	bullets, or a combination of the two is purely a matter of
	taste. *)

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.

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

	Prove the following claim, marking cases (and subcases) with
	bullets when you use [destruct]. Hint: delay introducing the
	hypothesis until after you have an opportunity to simplify it. *)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
	intros b c.
	destruct b eqn:Eb.
	- intros H.
	  simpl in H.
	  rewrite H.
	  reflexivity.
	- simpl.
		intros.
		destruct c eqn:Ec.
		+ reflexivity.
		+ destruct H.
			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 constructor arguments that need names, we can just
	write [[]] to get the case analysis. *)

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

(** **** Exercise: 1 star, standard (zero_nbeq_plus_1) *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  0 =? (n + 1) = false.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** 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 product
	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], [42],
	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!) *)

(* FILL IN HERE

	[] *)

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

(** **** Exercise: 1 star, standard (identity_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.
  (* FILL IN HERE *) Admitted.

(** [] *)

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

(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.
(** (The last definition is used by the autograder.)

	[] *)

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

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)

(** **** 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 [B0] and [B1] (representing 0s
	and 1s), terminated by a [Z]. For comparison, in the unary
	representation, a number is a sequence of [S] constructors terminated
	by an [O].

	For example:

		decimal               binary                          unary
		   0                       Z                              O
		   1                    B1 Z                            S O
		   2                B0 (B1 Z)                        S (S O)
		   3                B1 (B1 Z)                     S (S (S O))
		   4            B0 (B0 (B1 Z))                 S (S (S (S O)))
		   5            B1 (B0 (B1 Z))              S (S (S (S (S O))))
		   6            B0 (B1 (B1 Z))           S (S (S (S (S (S O)))))
		   7            B1 (B1 (B1 Z))        S (S (S (S (S (S (S O))))))
		   8        B0 (B0 (B0 (B1 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
  | B0 (n : bin)
  | B1 (n : bin).

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

(** The following "unit tests" of your increment and binary-to-unary
	functions should pass after you have defined those functions correctly.
	Of course, unit tests don't fully demonstrate the correctness of
	your functions!  We'll return to that thought at the end of the
	next chapter. *)

Example test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).
(* FILL IN HERE *) Admitted.

Example test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).
(* FILL IN HERE *) Admitted.

Example test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).
(* FILL IN HERE *) Admitted.

Example test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.
(* FILL IN HERE *) Admitted.

Example test_bin_incr5 :
		bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).
(* FILL IN HERE *) Admitted.

Example test_bin_incr6 :
		bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).
(* FILL IN HERE *) Admitted.

(** [] *)

(* ################################################################# *)
(** * Testing Your Solutions *)

(** Each SF chapter comes with a test file containing scripts that
	check whether you have solved the required exercises. If you're
	using SF as part of a course, your instructors will likely be
	running these test files to autograde your solutions. You can also
	use these test files, if you like, to make sure you haven't missed
	anything.

	Important: This step is _optional_: if you've completed all the
	non-optional exercises and Coq accepts your answers, this already
	shows that you are in good shape.

	The test file for this chapter is [BasicsTest.v]. To run it, make
	sure you have saved [Basics.v] to disk.  Then do this:

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

	If you accidentally deleted an exercise or changed its name, then
	[make BasicsTest.vo] will fail with an error that tells you the
	name of the missing exercise.  Otherwise, you will get a lot of
	useful output:

	- First will be all the output produced by [Basics.v] itself.  At
	  the end of that you will see [COQC BasicsTest.v].

	- Second, for each required exercise, there is a report that tells
	  you its point value (the number of stars or some fraction
	  thereof if there are multiple parts to the exercise), whether
	  its type is ok, and what assumptions it relies upon.

	  If the _type_ is not [ok], it means you proved the wrong thing:
	  most likely, you accidentally modified the theorem statement
	  while you were proving it.  The autograder won't give you any
	  points for that, so make sure to correct the theorem.

	  The _assumptions_ are any unproved theorems which your solution
	  relies upon.  "Closed under the global context" is a fancy way
	  of saying "none": you have solved the exercise. (Hooray!)  On
	  the other hand, a list of axioms means you haven't fully solved
	  the exercise. (But see below regarding "Allowed Axioms.") If the
	  exercise name itself is in the list, that means you haven't
	  solved it; probably you have [Admitted] it.

	- Third, you will see the maximum number of points in standard and
	  advanced versions of the assignment.  That number is based on
	  the number of stars in the non-optional exercises.

	- Fourth, you will see a list of "Allowed Axioms".  These are
	  unproved theorems that your solution is permitted to depend
	  upon.  You'll probably see something about
	  [functional_extensionality] for this chapter; we'll cover what
	  that means in a later chapter.

	- Finally, you will see a summary of whether you have solved each
	  exercise.  Note that summary does not include the critical
	  information of whether the type is ok (that is, whether you
	  accidentally changed the theorem statement): you have to look
	  above for that information.

	Exercises that are manually graded will also show up in the
	output.  But since they have to be graded by a human, the test
	script won't be able to tell you much about them.  *)

(* 2021-08-11 15:08 *)


Require Import ZArith.
Require Import Omega.
Require Import List.
Require Import FunctionalExtensionality.

Import ListNotations.

Require Import seqi.
Require Import listutils.

Open Scope Z_scope.

Fixpoint rollingSumH (n : Z) (lst : list Z) : list Z :=
  match lst with
  | nil => [n]
  | (x::xs) => n :: rollingSumH (x+n) xs
  end.

Definition rollingSum (input : list Z): list Z :=
  rollingSumH 0 input.

Lemma rollingSumH_n : forall l n,
  rollingSumH n l = map (fun x => x + n) (rollingSumH 0 l).
Proof.
induction l;intros;simpl in *;auto.
f_equal.
rewrite IHl.
rewrite  Z.add_0_r.
rewrite (IHl a).
rewrite map_map.
f_equal.
apply functional_extensionality.
intros.
omega.
Qed.

Example ex_rollingSum_summ :
  let l := [3;-5;8;3;9] in
  rollingSum l = map (fun i => sum (firstn i l)) (seq 0 (length l+1)).
Proof.
unfold rollingSum.
simpl.
auto.
Qed.

Example ex_rollingSumH_summ :
  let l := [3;-5;8;3;9] in
  let a := 7 in
  rollingSumH a l = map (fun i => sum (firstn i l) + a) (seq 0 (length l + 1)).
Proof.
simpl.
auto.
Qed.

Lemma rollingSumH_summ : forall a (l : list Z),
   rollingSumH a l = map (fun i => sum (firstn i l) + a) (seq 0 (length l + 1)).
Proof.
intros.
generalize dependent a.
induction l;intros;auto.
simpl rollingSumH.
rewrite IHl.
simpl. f_equal.
rewrite <- seq_shift.
rewrite map_map.
apply map_eq.
intros.
apply in_seq in H.
simpl.
omega.
Qed.

Lemma rollingSum_summ : forall l,
  rollingSum l = map (fun i => sum (firstn i l)) (seq 0 (length l + 1)).
Proof.
intros.
unfold rollingSum.
rewrite rollingSumH_summ.
apply map_eq;intros. omega.
Qed.

(* Close Scope Z_scope. *)


Require Import ZArith.
Open Scope Z_scope.

Inductive Z_btree : Set :=
  Z_leaf : Z_btree |
  Z_bnode : Z -> Z_btree -> Z_btree -> Z_btree.

Inductive Z_fbtree : Set :=
 | Z_fleaf : Z_fbtree
 | Z_fnode : Z  -> (bool -> Z_fbtree) -> Z_fbtree.

Definition Zf_mknode (z : Z) (t1 t2 : Z_fbtree) : Z_fbtree :=
   Z_fnode z (fun b => if b then t1 else t2).

Definition fleft_son  (t:Z_fbtree) : Z_fbtree :=
 match t with
 | Z_fleaf => Z_fleaf
 | Z_fnode a f => f true
 end.

Definition fright_son  (t:Z_fbtree) : Z_fbtree :=
 match t with
 | Z_fleaf => Z_fleaf
 | Z_fnode a f => f false
 end.

Fixpoint f1 (t:Z_btree) : Z_fbtree :=
  match t with
  | Z_leaf => Z_fleaf
  | Z_bnode z t1 t2 => Zf_mknode z (f1 t1) (f1 t2)
  end.

Fixpoint f2 (t:Z_fbtree) : Z_btree :=
  match t with
  | Z_fleaf => Z_leaf
  | Z_fnode z f => Z_bnode z (f2 (f true)) (f2 (f false))
  end.

Theorem f2_f1 : forall t: Z_btree, f2 (f1 t) = t.
Proof.
 induction t; simpl; auto.
 rewrite IHt1; rewrite IHt2; trivial.
Qed.

Section Extensionnality.
 Hypothesis extensionality : forall (A B:Set) (f g: A -> B),
                             (forall a, f a = g a)-> f =g.

 Theorem f1_f2 :  forall t: Z_fbtree, f1 (f2 t) = t.
 Proof.
  induction t; simpl; auto.
  do 2 rewrite H.
  unfold Zf_mknode.
  rewrite <- (extensionality _ _
                (fun b:bool =>  if b then z0 true else z0 false)
                z0).
  trivial.
  destruct a; simpl; trivial.
 Qed.
End Extensionnality.

Check f1_f2.


Require Import Axioms.
Require Import Types.

(* This file contains the definition of an Abelian Monoid,
   and then, an axiomatic definition of a Key-Value Set, as an Abelian Monoid, with more
   axioms and properties.
   The Key-Value Set uses generic types for its keys and values, so in order to use it,
   you must plug-in the module types of type ModuleType (see Types.v). *)

Module Type AbelianMonoid.

  (* Type of Abelian Monoid *)
  Parameter T : Type.

  (* Constructors *)
  Parameter null : T.
  Parameter mult : T -> T -> T.

  (* Notations *)
  Notation "s1 'o' s2" := (mult s1 s2) (at level 20, left associativity).

  (* Decision *)
  Parameter decide_empty : forall (s : T), { s = null }+{ s <> null }.

  (* Axioms of Monoid *)
  Parameter assoc : forall m1 m2 m3, (m1 o m2) o m3 = m1 o (m2 o m3).

  Parameter id_l : forall m, null o m = m.
  Parameter id_r : forall m, m o null = m.

  (* The Axiom of Commutativity *)
  Parameter commut : forall m1 m2, m1 o m2 = m2 o m1.

  Lemma equal_commut : forall (m1 m2 : T), m1 = m2 -> m2 = m1.
  Proof.
    intros. rewrite -> H. reflexivity.
  Qed.

  Lemma exchange : forall A B C D, A o B o C o D = A o C o B o D.
  Proof.
    intros.
    assert (H : B o C = C o B). { apply commut. }
    assert (H' : B o (C o D) = C o (B o D)).
      { repeat rewrite <- assoc. rewrite -> H. reflexivity. }
    repeat rewrite -> assoc. rewrite -> H'. reflexivity.
  Qed.

End AbelianMonoid.

Module Type KeyValueSet ( M : AbelianMonoid ) ( KM : Types.ModuleType ) ( VM : Types.ModuleType ).

  (* The Type *)
  Definition T : Type := M.T.

  Definition K : Type := KM.T.
  Definition V : Type := VM.T.

  (* Constructors *)
  Parameter append : T -> K -> V -> T.

  Definition empty := M.null.

  Notation "'[' k v ']'" := (append empty k v) (at level 15).

  Parameter alloc : T -> K.

  (* Decision *)
  Parameter decide_append : forall (s : T),
      s <> empty ->
      exists s' k v, s = append s' k v.

  Parameter decide_append_empty : forall s' k v, empty = append s' k v -> False.

  Lemma empty_union : forall s1 s2, M.mult s1 s2 = empty -> s1 = empty /\ s2 = empty.
  Proof. Admitted.

  Proposition decide_append_iff : forall (s : T),
      s <> empty <->
      exists s' k v, s = append s' k v.
  Proof.
    split.
    - apply decide_append.
    - intros. inversion H; subst. inversion H0; subst. inversion H1; subst.
      unfold not. intros H'. eapply decide_append_empty. rewrite <- H'. reflexivity.
  Qed.

  (* Relation between Append and Concat *)
  Notation "s1 'o' s2" := (M.mult s1 s2) (at level 20, left associativity).

  Parameter append_concat : forall s1 s2 s' k v,
      s2 = append s' k v ->
      s1 o s2 = append (s1 o s') k v.

  Proposition append_to_concat : forall s' k v,
      append s' k v = s' o (append empty k v).
  Proof.
    intros. erewrite -> append_concat with (s' := empty) (k := k) (v := v); try reflexivity.
    rewrite -> M.id_r. reflexivity.
  Qed.

  Proposition append_commut : forall s k v k' v',
      append (append s k v) k' v' = append (append s k' v') k v.
  Proof.
    intros. rewrite -> append_to_concat. rewrite -> append_to_concat.
    rewrite <- M.id_r with (m := s o (append empty k v) o (append empty k' v')).
    rewrite -> M.exchange. rewrite -> M.id_r. repeat rewrite <- append_to_concat.
    reflexivity.
  Qed.

  (* Remove *)
  Parameter remove : T -> K -> T.

  Parameter remove_append : forall s k v, remove (append s k v) k = s.

  (* Membership *)
  Inductive contains : T -> K -> V -> Prop :=
  | contains_append : forall s s' k v, s = append s' k v -> contains s k v
  | contains_append_set : forall s' k v k' v', k <> k' -> contains s' k' v' -> contains (append s' k v) k' v'.

  Proposition empty_contains : forall k v, contains empty k v -> False.
  Proof.
    intros. inversion H; subst.
    - apply decide_append_empty in H0. apply H0.
    - assert (H' : empty = append s' k0 v0). { rewrite <- H0. reflexivity. }
      apply decide_append_empty in H'. apply H'.
  Qed.

  (* Key Membership *)
  Inductive contains_key : T -> K -> Prop :=
  | contains_key_append : forall s s' k v, s = append s' k v -> contains_key s k
  | contains_key_append_set : forall s' k v k', k <> k' ->
    contains_key s' k' -> contains_key (append s' k v) k'.

  Proposition empty_contains_key : forall k, contains_key empty k -> False.
  Proof.
    intros. inversion H.
    - apply decide_append_empty in H0. apply H0.
    - apply M.equal_commut in H0. apply decide_append_empty in H0. apply H0.
  Qed.

  Parameter remove_not_contained : forall s k,
    ~ contains_key s k -> remove s k = s.

  Lemma contains_exists : forall (S S' : M.T) k v,
    contains S k v ->
    exists S', S = append S' k v.
  Proof.
    intros. induction H.
    - exists s'. subst. reflexivity.
    - inversion IHcontains as [s'']. subst s'. exists (append s'' k v). apply append_commut.
  Qed.

  Proposition remove_empty : forall k, remove empty k = empty.
  Proof.
    intros. apply remove_not_contained. unfold not. intros.
    eapply empty_contains_key. apply H.
  Qed.

  Parameter decide_cross_append : forall s s' k k' v v',
    append s k' v' = append s' k v ->
    (k = k' /\ v = v' /\ s = s') \/ (k <> k' /\ contains s k v /\ contains s' k' v').

  Parameter contains_contains_key : forall S k,
    (exists v, contains S k v) <-> contains_key S k.

  Lemma contains_set_append_law : forall s k v k' v',
    contains (append s k' v') k v ->
    (k = k' /\ v = v') \/ contains s k v.
  Proof.
    intros. remember H as H'. clear HeqH'. inversion H; subst.
    - apply decide_cross_append in H0. inversion H0 as [H1 | H1].
      + inversion H1. inversion H3. left. split; try apply H2; try apply H4.
      + inversion H1. right. inversion H3. apply H4.
    - remember H0 as H0'. clear HeqH0'. apply decide_cross_append in H0. inversion H0.
      + right. inversion H3 as [H3' H3'']. inversion H3'' as [H3''' H3''''].
        subst k0 v0 s'. apply H2.
      + assert (exclusi : {(k = k' /\ v = v')} + {~(k = k' /\ v = v')}).
        { apply principium_tertii_exclusi with (P := (k = k' /\ v = v')). }
        admit.
  Qed.

  (* No Duplications *)
  Parameter unique_append : forall s' k v, contains s' k v -> append s' k v = s'.

  Lemma contains_unique : forall s' k v v',
      contains s' k v -> contains s' k v' -> v = v'.
  Proof.
  Admitted.

  (* Theorems *)
  Proposition factor : forall s1 s2 k v k' v',
      (append (append s1 k v) k' v') o s2 = s1 o (append empty k v) o (append empty k' v') o s2.
  Proof.
    intros. rewrite -> append_to_concat. rewrite -> append_to_concat. reflexivity.
  Qed.

  Lemma exchange : forall s1 s2 k v k' v',
      (append (append s1 k v) k' v') o s2 = (append (append s1 k' v') k v) o s2.
  Proof.
    intros. repeat rewrite -> factor. apply M.exchange.
  Qed.

End KeyValueSet.

Module Test ( M : AbelianMonoid ) ( m_nat : Types.ModuleNat ) ( kvs : KeyValueSet M m_nat m_nat ).
  Import kvs.

  Definition test_set : kvs.T := append (append empty 1 2) 2 3.

  Example test_set_contains : contains test_set 1 2.
  Proof.
    compute. apply contains_append_set.
    - auto.
    - eapply contains_append. reflexivity.
  Qed.

End Test.


Require Import List.
Require Import ZArith.
Import ListNotations.
Require Import Bool.
Open Scope Z_scope.

Inductive sorted : list Z -> Prop :=
  | sorted0 : sorted nil
  | sorted1 : forall z:Z, sorted (z :: nil)
  | sorted2 :
      forall (z1 z2:Z) (l:list Z),
        z1 <= z2 ->
        sorted (z2 :: l) -> sorted (z1 :: z2 :: l).

Hint Resolve sorted0 sorted1 sorted2 : sort.

Fixpoint nb_occ (z:Z) (l:list Z) {struct l} : nat :=
  match l with
  | nil => O
  | (z' :: l') =>
      match Z_eq_dec z z' with
      | left _ => S(nb_occ z l')
      | right _ => nb_occ z l'
      end
  end.

Print nb_occ.

Definition equiv (l l':list Z) :=
    forall z:Z, nb_occ z l = nb_occ z l'.

Lemma equiv_refl : forall l:list Z, equiv l l.
Proof.
 unfold equiv. trivial.
Qed.

Lemma equiv_sym : forall l l':list Z, equiv l l' -> equiv l' l.
Proof.
  unfold equiv.
  intros l l' H. symmetry. apply H.
Qed.

Lemma equiv_trans :
 forall l l' l'':list Z, equiv l l' ->
                         equiv l' l'' ->
                         equiv l l''.
Proof.
 intros l l' l'' H H0 z.
 eapply trans_eq; eauto.
Qed.

Lemma equiv_cons :
 forall (z:Z) (l l':list Z), equiv l l' ->
                             equiv (z :: l) (z :: l').
Proof.
 intros z l l' H z'.
 simpl; case (Z_eq_dec z' z); auto.
Qed.

Lemma equiv_perm :
 forall (a b:Z) (l l':list Z),
   equiv l l' ->
   equiv (a :: b :: l) (b :: a :: l').
Proof.
 intros a b l l' H z; simpl.
 case (Z_eq_dec z a); case (Z_eq_dec z b);
  simpl; case (H z); auto.
Qed.

Hint Resolve equiv_cons equiv_refl equiv_perm : sort.

Fixpoint bubble (z:Z) (l:list Z) : list Z :=
  match l with
  | nil => z :: nil
  | cons a l' =>
      match Z_le_gt_dec z a with
      | left _ =>  z :: (bubble a l')
      | right _ => a :: (bubble z l')
      end
  end.

Eval compute in bubble 5 [7;0;1;2;3;6].

Lemma bubble_equiv : forall (l:list Z) (x:Z),
                  equiv (x :: l) (bubble x l).
Proof.
 induction l as [|a l0 H] ; auto with sort.
 intros x. simpl. case (Z_le_gt_dec x a).
   intros. auto with sort.
 intro; apply equiv_trans with (a :: x :: l0);
   auto with sort.
Qed.

Lemma sorted_subs: forall (l:list Z) (x:Z) (z:Z), sorted (x::l) -> (z<=x)-> sorted (z::l).
Proof.
  intros. induction l. auto with sort. apply sorted2. rewrite H0.
  inversion H. apply H3. inversion H. apply H5.
Qed.

Lemma sorted_elim_fst: forall (l:list Z) (a:Z), sorted (a::l) -> sorted l.
Proof.
  intros. induction l. auto with sort. inversion H. apply H4.
Qed.

Lemma sorted_elim_snd : forall (l:list Z) (a b:Z), sorted (a::b::l) -> sorted (a::l).
Proof.
  intros. induction l. auto with sort. inversion H.
  apply sorted_subs with (a0::l) b a in H4. apply H4. apply H2.
Qed.

Lemma sorted_add: forall (l : list Z) (x a: Z), sorted (a::l) -> x<=a -> sorted (x::a::l).
Proof.
  auto with sort.
Qed.

(*Lemma my7: forall (x: Z), x = x.
Proof.
  intros. auto.
Qed.*)

Lemma nb_occ_nil: forall  (l : list Z), (forall (a : Z),  nb_occ a l = 0%nat) -> l = [].
Proof.
  induction l. simpl. auto.
  intro. assert (H0:=H a). simpl in H0. case (Z.eq_dec a a) in H0.
  symmetry in H0. Check O_S. apply O_S in H0. contradiction. intuition. (*assert (HH:= eq_refl a). contradiction. *)
Qed.

Lemma equiv_nil: forall (l : list Z), equiv l [] -> l = [].
  induction l. auto. intro.
  unfold equiv. apply nb_occ_nil in H. apply H.
Qed.

Lemma equiv_elim: forall (l l' :list Z) (z: Z), equiv (z::l) (z::l') -> equiv l l'.
Proof.
  unfold equiv. intros l l' z H z0.
  assert (H1:= H z0). simpl in H1. case (Z.eq_dec z0 z) in H1. apply eq_add_S in H1. auto. auto.
Qed.

Lemma equiv_add: forall (l l' :list Z) (z: Z), equiv l l' -> equiv (z::l) (z::l').
Proof.
  unfold equiv. intros l l' z H z0.
  assert (H1:= H z0). simpl. case (Z.eq_dec z0 z). intros. apply eq_S. auto. auto.
Qed.

Lemma equiv_cons1: forall (l:list Z) (a:Z), equiv (a::l) [a] -> (a::l) = [a].
Proof.
  induction l. intros. auto.
  intros. assert (H1:=IHl a0).
  unfold equiv in H. assert (H2:= H a). simpl in H2. case (Z.eq_dec a a0) in H2. case (Z.eq_dec a a) in H2. symmetry in H2.

  apply eq_add_S in H2. apply O_S in H2. contradiction.
  intuition. (*assert (HH:= eq_refl a). (**???*) contradiction. *)
  case (Z.eq_dec a a) in H2. symmetry in H2. apply O_S in H2. contradiction. intuition. (* assert (HH:= eq_refl a). (**???**) contradiction. *)
Qed.

Lemma equiv_cons2: forall  (a b:Z) (l:list Z), equiv (a::l) [b] -> ((a = b) /\ ((a::l) = [a])).
Proof.
  intros a b. case (Z.eq_dec a b). intros. split. auto. apply equiv_cons1. symmetry in e. rewrite e in H. auto.
  intros. unfold equiv in H. assert (H1:= H a).
  simpl in H1. case (Z.eq_dec a a) in H1. case (Z.eq_dec a b) in H1. contradiction.
    symmetry in H1. apply O_S in H1. contradiction. intuition. (*assert (HH:= eq_refl a). contradiction.*)
Qed.

Definition minimum (m:Z) (l:list Z) :=
    forall z:Z, (nb_occ z l > 0)%nat -> m <= z.

Eval compute in minimum 5 [1;2;3].

(*Lemma help1: forall (x: nat), (x > x)%nat -> False.
Proof.
  intros. assert (H1:=eq_refl x). inversion H. intuition. intuition.
Qed.*)

Lemma sorted_min: forall (l:list Z) (m:Z), sorted (m::l) -> minimum m l.
Proof.
  induction l. intros. unfold minimum. intros. simpl in H0. intuition. (*assert(H2:=help1 0). apply H2 in H0. contradiction.*)
  intros. assert (H0:= IHl m). assert(H4:=H). apply sorted_elim_snd in H. apply H0 in H. case (Z_le_gt_dec m a).
  intros. unfold minimum. intros. unfold minimum in H. assert (H2:=H z). simpl in H1. case (Z.eq_dec z a) in H1.
  symmetry in e. rewrite e in l0. auto. apply H2. apply H1.
  intros. inversion H4. contradiction.
Qed.

(*Lemma help2: forall (x:nat), (S x > 0)%nat.
Proof.
  intros. induction x. auto. auto.
Qed.*)

Lemma min_sorted: forall (l:list Z) (m:Z), sorted l -> minimum m l -> sorted (m::l).
Proof.
  induction l. auto with sort.
  intros. case (Z_le_gt_dec m a). intros. apply sorted_add with l m a in H. apply H. auto.
  intros. assert(H4:=H0). unfold minimum in H0. assert(H1:=H0 a). simpl in H1. case (Z.eq_dec a a) in H1.
  intuition. intuition.
  (*assert (H2:=help2 (nb_occ a l)). apply H1 in H2. contradiction. assert (H2:= eq_refl a). contradiction.*)
Qed.

Lemma min_eq: forall (l l':list Z) (m:Z), equiv l l' -> minimum m l -> minimum m l'.
Proof.
  intros. unfold minimum. intros. unfold minimum in H0. apply H0. unfold equiv in H. assert (H2:=H z).
  rewrite H2. apply H1.
Qed.

Lemma minimum_cons: forall (l:list Z) (a x:Z), minimum a l -> a <= x -> minimum a (x::l).
Proof.
  unfold minimum. intros. simpl in H1. case (Z.eq_dec z x) in H1. symmetry in e. rewrite e in H0. apply H0.
  assert (H2:=H z). apply H2 in H1. apply H1.
Qed.

(*Lemma help3: forall (a x: Z), x > a -> a <= x.
Proof.
  intros. intuition.
Qed.*)

Lemma bubble_sorted :
 forall (l:list Z) (x:Z), sorted l -> sorted (bubble x l).
Proof.
induction l. simpl; auto with sort.
intros. simpl. assert (H1 := H). case (Z_le_gt_dec x a). intro.
apply sorted_elim_fst in H. apply IHl with a in H. apply sorted_add with l x a in H1.
apply sorted_min in H1. apply min_sorted. apply H. Check bubble_equiv. assert (H2:= bubble_equiv l a).
apply min_eq with (a :: l) . apply H2. apply H1. apply l0.
intros. apply sorted_elim_fst in H. apply IHl with x in H. apply min_sorted. apply H.
assert (H2:=bubble_equiv l x). apply min_eq with (x::l). apply H2. apply minimum_cons. apply sorted_min in H1.
apply H1. intuition. (*apply my16. apply g.*)
Qed.

Definition Z_sort :
  forall l:list Z, {l' : list Z | equiv l l' /\ sorted l'}.
 induction l as [| a l IHl].
 exists (nil (A:=Z)); split; auto with sort.
 case IHl; intros l' [H0 H1].
 exists (bubble a l'). split.
 apply equiv_trans with (a :: l'). auto with sort.
 apply bubble_equiv.
 apply bubble_sorted; auto.
Defined.

Extraction Language Haskell.
Extraction "/Users/User/Documents/IndependentWork/InsertionSort/certified_sorting/bubble_sort.hs" bubble Z_sort.


(**
* PSet2b: Induction in Coq (240 points)
*)

Require Import List Arith.

(**********************************************************************)

(* Exercise: app_assoc coq [10 points].
   In Coq, the list append operator is written [++]. Complete the following
   proof by induction, which shows that application is associative.
   Hint:  the solution is in the lecture slides. *)

Theorem app_assoc : forall (A:Type) (l1 l2 l3 : list A),
  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.
Proof.
  intros A l1 l2 l3.
  induction l1 as [ | h t IH].
  (* FILL IN, and change [Abort] to [Qed]. *)
Abort.

(**********************************************************************)

(* Exercise: app_assoc math [20 points].

Prove that the OCaml [@] operator is also associative.  Your answer should
be a mathematical proof, not a Coq proof.  We have supplied part of the
proof for you.

Theorem:  for all lists lst1, lst2, and lst3,
  lst1 @ (lst2 @ lst3) = (lst1 @ lst2) @ lst3.

Proof:  by induction on lst1.
The property being proved is:
P(l) = FILL IN

Case:  lst1 = []
Show:  FILL IN

Case: lst1 = h::t
IH:  FILL IN
Show:  FILL IN

QED

*)

(**********************************************************************)

(* Exercise: rev_append math [30 points].

Prove the following theorem, which shows how list reversal distributes
over list append.

Theorem: for all lists lst1 and lst2,
  rev (lst1 @ lst2) = rev lst2 @ rev lst1.

Recall that [rev] is defined as follows:
<<
let rec rev = function
  | [] -> []
  | h::t -> rev t @ [h]
>>

Your answer should be a mathematical proof, not a Coq proof. In the inductive
case, you will need the lemma proved above saying that append is associative. In
the base case, you will need this lemma:

Lemma:  for all lists lst, lst @ [] = lst.
Proof:  given in lecture.

Here, again, is the theorem you should prove:

Theorem: for all lists lst1 and lst2,
  rev (lst1 @ lst2) = rev lst2 @ rev lst1.

Proof:  FILL IN

*)

(**********************************************************************)

(* Exercise: rev_append coq [30 points].

Now prove the same theorem as the previous exercise, but in Coq.
The Coq list reversal function [rev] is defined in the standard
library for you.  Use the mathematical proof you gave above
as a guide.  For the base case, you will need the lemma [app_nil]
that we proved in lecture; we've inserted the code for it below.
You can use that lemma in your own proof with the [rewrite] tactic.
*)

Lemma app_nil : forall (A:Type) (lst : list A),
  lst ++ nil = lst.
Proof.
  intros A lst.
  induction lst as [ | h t IH].
  - trivial.
  - simpl. rewrite -> IH. trivial.
Qed.

Theorem rev_append : forall (A:Type) (lst1 lst2 : list A),
  rev (lst1 ++ lst2) = rev lst2 ++ rev lst1.
Proof.
  (* FILL IN, and change [Abort] to [Qed] *)
Abort.

(**********************************************************************)

(* Exercise: rev involutive [30 points].

Prove that [rev] is _involutive_, meaning that it is its own inverse. That is,
[rev (rev lst) = lst].

Hint:  for the inductive case, there is a lemma that has already been proved in
this lab that you will find very helpful.  Part of this exercise is figuring out
which lemmma that is.
*)

Theorem rev_involutive : forall (A:Type) (lst : list A),
  rev (rev lst) = lst.
Proof.
  (* FILL IN, and change [Abort] to [Qed] *)
Abort.

(**********************************************************************)

(* Exercise: app_length [Optional].
Prove the following theorem in Coq.
*)

(*
Theorem app_length : forall (A:Type) (l1 l2 : list A),
  length (l1 ++ l2) = length l1 + length l2.
Proof.
  (* FILL IN, and change [Abort] to [Qed] *)
Abort.
*)

(**********************************************************************)

(* Exercise: rev_length [Optional].
Prove the following theorem in Coq.

Hint: previous exercise(s) as lemma, and the [ring] tactic.
*)

(*
Theorem app_rev : forall (A:Type) (lst : list A),
  length (rev lst) = length lst.
Proof.
  (* FILL IN, and change [Abort] to [Qed] *)
Abort.
*)

(**********************************************************************)

(* INDUCTION ON BINARY TREES *)

(* Here is a Coq type for binary trees: *)
Inductive tree (A : Type) : Type :=
  | Leaf : tree A
  | Node : tree A -> A -> tree A -> tree A.

(* The following commands cause the [A] argument to
   be implicit to the [Leaf] and [Node] constructors. *)
   Arguments Leaf [A].
   Arguments Node [A] _ _ _.

(* The equivalent OCaml type would be:
<<
type 'a tree =
  | Leaf
  | Node of 'a tree * 'a * 'a tree
>>
*)

(* The _reflection_ operation swaps the left and right
   subtrees at every node. *)
Fixpoint reflect {A : Type} (t : tree A) :=
  match t with
  | Leaf => Leaf
  | Node l v r => Node (reflect r) v (reflect l)
  end.

(* The equivalent OCaml function would be:
<<
let rec reflect = function
  | Leaf -> Leaf
  | Node (l,v,r) -> Node (reflect r, v, reflect l)
>>
*)

(* A proof by induction on a binary tree has the following structure:

Theorem:  For all binary trees t, P(t).

Proof: by induction on t.

Case: t = Leaf
Show: P(Leaf)

Case: t = Node(l,v,r)
IH1:  P(l)
IH2:  P(r)
Show:  P(Node(l,v,r))

QED

Note that we get _two_ inductive hypotheses in the inductive
case, one for each subtree.
*)

(**********************************************************************)

(* Exercise: tree_ind [20 points].
Explain the output of the following command in your own words, relating it to
the proof structure given above for induction on binary trees.
Hint: read the notes on induction principles.
*)

Check tree_ind.

(**********************************************************************)

(* Exercise: reflect_involutive math [30 points].
Prove the following theorem mathematically (not in Coq).

Theorem:  for all trees t, reflect (reflect t) = t

Proof: by induction on t.
P(t) = reflect (reflect t) = t

Case: t = Leaf
Show: FILL IN

Case: t = Node(l,v,r)
IH1: P(l) = reflect(reflect l) = l
IH2: P(r) = reflect(reflect r) = r
Show: FILL IN

QED
*)

(**********************************************************************)

(* Exercise: reflect_involutive coq [30 points].
State and prove a theorem in Coq that shows reflect is involutive.
Use your mathematical proof from the previous exercise as a guide.

Hint: the [induction] tactic expects the arguments for the inductive
case in the following order:  the left subtree, the IH for the left subtree,
the value at the node, the right subtree, and the IH for the right subtree.
*)

(*
UNCOMMENT AND COMPLETE
Theorem reflect_involutive : ...
*)

(**********************************************************************)

(* Exercise: height [40 points].

1. Write a Coq function [height] that computes the height of a binary tree.
Recall that the height of a leaf is 0, and the height of a node is 1 more than
the maximum of the heights of its two subtrees.  The standard library does
contain a [max] function that will be helpful.

2. Prove that [reflect] preserves the height of a tree.  Hint: [Nat.max_comm].

3. Write a Coq function [perfect : nat -> tree nat], such that
[perfect h] constructs the perfect binary tree of height [h], and
the value at the root is [1], and if the value at a node is [v],
then the values of its left and right subnodes are [2*v] and [2*v+1].
For example, [perfect 3] is
<<
Node (Node (Node Leaf 4 Leaf)
           2
           (Node Leaf 5 Leaf))
     1
     (Node (Node Leaf 6 Leaf)
           3
           (Node Leaf 7 Leaf))
>>

4. Prove that the height of [perfect h] is in fact [h].  Hint 1: induct
on [h].  Hint 2: don't introduce all the variables. Hint 3:
[Nat.max_idempotent].
*)


Require Import List.

Print list.

Check list_ind.

Definition tl {A:Type} (l: list A) : list A :=
match l with
| nil => nil
| a::l' => l'
end.
Compute tl (3::5::8::nil).

(**
Fixpoint app {A:Type} (l l' : list A) : list A :=
match l with
| nil => l'
| a:: m => a :: (app m l')
end.
*)

Compute (1::2::3::nil) ++ (5::6::nil).

Lemma app_assoc {A:Type} :
 forall l l' l'' : list A, (l ++ l') ++ l'' = l ++ (l' ++ l'').
Proof.
  induction l.
  - simpl. intros;reflexivity.
  - simpl. intros.  rewrite IHl.
    reflexivity.
Qed.

Fixpoint In {A:Type} (x:A)(l : list A) : Prop  :=
match l with
| nil => False
| y :: l' => x = y \/ In x l'
end.

Inductive mem {A:Type} (x:A) : list A -> Prop  :=
| mem_hd : forall l', mem x (x::l')
| mem_tl : forall y l', mem x l' -> mem x (y::l').

Fixpoint memb  {A:Type} (eqb : A -> A -> bool) (x:A) (l : list A) :=
match l with
| nil => false
| y :: l' => if eqb x y then true else memb eqb x l'
end.

Lemma mem_In : forall A (x:A) l, mem x l -> In x l.
Proof.
  intros A x l H.
  induction H.
  - simpl.
    left;trivial.
  -  simpl.
    right;assumption.
Qed.

Lemma In_mem : forall A (x:A) l, In x l -> mem x l.
Proof.
  induction l.
  - intro H.
    inversion H.
  -  intro H; inversion H.
     + subst x; constructor.
     + constructor.
      apply IHl; assumption.
Qed.

Lemma memb_In {A:Type}(eqb: A -> A -> bool)
      : forall (x:A) l, memb eqb x l = true -> In x l.
Proof.
 induction l.
 - simpl.
   discriminate.
 - simpl.
   intro H; case_eq (eqb x a).
   + Abort.

Definition correct_eq {A:Type}(eqb : A -> A -> bool) :=
 forall x y : A, eqb x y = true <-> x = y.

Lemma memb_In {A:Type}(eqb: A -> A -> bool)(Ok : correct_eq eqb)
      : forall (x:A) l, memb eqb x l = true -> In x l.
Proof.
 induction l.
 - simpl.
   discriminate.
 - simpl.
   intro H; case_eq (eqb x a).
   + rewrite (Ok x a).
     auto.
   +  intro H0;rewrite H0 in H.
      auto.
Qed.

Lemma In_memb {A:Type}(eqb: A -> A -> bool)(Ok : correct_eq eqb)
      : forall (x:A) l, In x l -> memb eqb x l = true.
Proof.
 induction l.
 - simpl.
  contradiction.
 - simpl. intro H.
   destruct H.
   rewrite <- (Ok x a) in H.
   now rewrite H.
   rewrite IHl.
   now  destruct (eqb x a).
   assumption.
Qed.


(* This file should be tested by loaded from `field_examples_check.v` and     *)
(* `field_examples_no_check.v`. To edit this file, uncomment `Require         *)
(* Import`s below: *)
(* From mathcomp Require Import all_ssreflect ssralg ssrnum ssrint rat. *)
(* From mathcomp Require Import ring. *)

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Import GRing.Theory Num.Theory.

Local Open Scope ring_scope.

(* Examples from the Coq Reference Manual, but for an instance of MathComp's
   (abstract) field. *)

Goal forall (F : fieldType) (x : F), x != 0 -> (1 - 1 / x) * x - x + 1 = 0.
Proof. by move=> F x x_neq0; field. Qed.

Goal forall (F F' : fieldType) (f : {rmorphism F -> F'}) (x : F),
    f x != 0 -> f ((1 - 1 / x) * x - x + 1) = 0.
Proof. by move=> F F' f x x_neq0; field. Qed.

Goal forall (F : fieldType) (x y : F), y != 0 -> y = x -> x / y = 1.
Proof. by move=> F x y y_neq0 y_eq_x; field: y_eq_x. Qed.

Goal forall (F : fieldType) (x y : F), y != 0 -> y = 1 -> x = 1 -> x / y = 1.
Proof. by move=> F x y y_neq0 y_eq1 xeq1; field: y_eq1 xeq1. Qed.

(* Using the _%:R embedding from nat to F *)

Goal forall (F : fieldType) (n : nat),
    n%:R != 0 :> F -> (2 * n)%:R / n%:R = 2%:R :> F.
Proof. by move=> F n n_neq0; field. Qed.

(* For a numFieldType, non-nullity conditions such as 2%:R != 0 should not be *)
(* generated.                                                                 *)
Goal forall (F : numFieldType) (x : F), (x / 2%:R) * 2%:R = x.
Proof. by move=> F x; field. Qed.

Goal forall (F : numFieldType) (n : nat),
  n != 1%N -> ((n ^ 2)%:R - 1) / (n%:R - 1) = (n%:R + 1) :> F.
Proof. by move=> F n n_neq0; field; rewrite subr_eq0 pnatr_eq1. Qed.

Goal forall (F : numFieldType) (n : nat),
  n != 1%N -> (2%:R - (2 * n)%:R) / (1 - n%:R) = 2%:R :> F.
Proof. by move=> F n n_neq0; field; rewrite subr_eq0 eq_sym pnatr_eq1. Qed.


Require Export ZArith.
Require Export List.
Require Export Arith.
Require Export ZArithRing.

(** Example of use of the conversion rule
*)
Theorem conv_example : forall n:nat, 7*5 < n -> 6*6 <= n.
Proof.
 intros; assumption.
Qed.

Theorem imp_trans : forall P Q R:Prop, (P->Q)->(Q->R)->P->R.
Proof.
  intros P Q R H H0 p.
  apply H0; apply H; assumption.
Qed.

(** Tests :

Print imp_trans.

Check (imp_trans _ _ _ (le_S 0 1)(le_S 0 2)).

*)

Definition neutral_left (A:Type)(op:A->A->A)(e:A) : Prop :=
  forall x:A, op e x = x.

Lemma one_neutral_left : neutral_left Z Zmult 1%Z.
Proof.
 intro z; ring.
Qed.

Lemma le_i_SSi : forall i:nat, i <= S (S i).
Proof.
 intro i.
 do 2 apply le_S; apply le_n.
Qed.

Lemma all_imp_dist   :
 forall (A:Type)(P Q:A->Prop),
         (forall x:A, P x -> Q x)->
         (forall y:A, P y)->
          forall z:A, Q z.
Proof.
 intros A P Q H H0 z.
 apply H; apply H0; assumption.
Qed.

Lemma mult_le_compat_r : forall m n p:nat, le n p -> le (n * m) (p * m).
Proof.
 intros m n p H; rewrite (mult_comm n m); rewrite (mult_comm p m).
 apply mult_le_compat_l; trivial.
Qed.

Lemma le_mult_mult :
   forall a b c d:nat, a <= c -> b <= d -> a * b <= c * d.
Proof.
 intros a b c d H H0.
 apply le_trans with (m := c  *b).
 - apply mult_le_compat_r; assumption.
 - apply mult_le_compat_l; assumption.
Qed.

(** using eapply ...
*)

Lemma le_mult_mult' :
 forall a b c d:nat, a <= c -> b <= d -> a*b <= c*d.
Proof.
 intros a b c d H H0.
 eapply le_trans.
 - eapply mult_le_compat_l.
   eexact H0.
 -  now apply mult_le_compat_r.
Qed.

Lemma le_O_mult : forall n p:nat, 0 * n <= 0 * p.
Proof.
 intros n p; apply le_n.
Qed.

Lemma lt_8_9 : 8 < 9.
Proof.
 unfold lt; apply le_n.
Qed.

(** Tests :

SearchPattern (_ + _ <= _)%Z.

SearchPattern (?X1 * _ <= ?X1 * _)%Z.

*)

Lemma lt_S : forall n p:nat, n < p -> n < S p.
Proof.
 intros n p H.
 unfold lt; apply le_S; trivial.
Qed.

Open Scope Z_scope.

Definition Zsquare_diff (x y:Z):= x * x - y * y.

Theorem unfold_example :
 forall x y:Z,
   x*x = y*y ->
   Zsquare_diff x y * Zsquare_diff (x+y)(x*y) = 0.
Proof.
 intros x y Heq.
 unfold Zsquare_diff at 1.
 rewrite Heq; ring.
Qed.

Section ex_falso_quodlibet.
 Hypothesis ff : False.

 Lemma ex1 : 220 = 284.
 Proof.
   apply False_ind.
   exact ff.
 Qed.

 Lemma ex2 : 220 = 284.
 Proof.
  destruct ff.
 Qed.

End ex_falso_quodlibet.

Theorem absurd : forall P Q:Prop, P -> ~P -> Q.
Proof.
 intros P Q p H.
 elim H.
 assumption.
Qed.

Theorem double_neg_i : forall P:Prop, P->~~P.
Proof.
 intros P p H.
 apply H; assumption.
Qed.

Theorem modus_ponens :forall P Q:Prop, P->(P->Q)->Q.
Proof.
 auto.
Qed.

Theorem double_neg_i' : forall P:Prop, P -> ~ ~ P.
Proof.
 intro P; exact (modus_ponens P False).
Qed.

Theorem contrap :forall A B:Prop, (A->B) -> ~B -> ~A.
Proof.
 intros A B; unfold not.
 apply imp_trans.
Qed.

Theorem disj4_3' : forall P Q R S:Prop, R -> P \/ Q \/ R \/ S.
Proof.
  right; right; left; assumption.
Qed.

Lemma and_commutes : forall A B:Prop, A /\ B -> B /\ A.
Proof.
 intros A B H; destruct H.
 split; assumption.
Qed.

Lemma or_commutes : forall A B:Prop, A\/B->B\/A.
Proof.
 intros A B H; destruct H as [H | H]; auto.
Qed.

Lemma ex_imp_ex :
 forall (A:Type)(P Q:A->Prop), (ex P)->(forall x:A, P x -> Q x)->(ex Q).
Proof.
 intros A P Q H H0; destruct H as [a Ha].
 exists a; apply H0; assumption.
Qed.

Lemma L36 : 6 * 6 =9 * 4.
Proof. reflexivity. Qed.

Lemma diff_of_squares : forall a b:Z, ((a + b) * (a - b) = a * a - b * b)%Z.
Proof.
 intros; ring.
Qed.

Theorem eq_sym' : forall (A:Type)(a b:A), a = b -> b = a.
Proof.
 intros A a b e; rewrite e; reflexivity.
Qed.

Lemma Zmult_distr_1 : forall n x:Z, n * x + x = ( n + 1) * x.
Proof.
 intros n x ; rewrite Zmult_plus_distr_l.
 now rewrite  Zmult_1_l.
Qed.

Lemma regroup : forall x:Z, x + x + x + x + x = 5 * x.
Proof.
 intro x; pattern x at 1.
 rewrite <- Zmult_1_l.
 repeat rewrite Zmult_distr_1.
 reflexivity.
Qed.

Open Scope nat_scope.

Theorem le_lt_S_eq : forall n p:nat, n <= p -> p < S n -> n = p.
Proof.
 intros; omega.
Qed.

Lemma conditional_rewrite_example : forall n:nat,
   8 < n + 6 ->  3 + n < 6 -> n * n = n + n.
Proof.
 intros n  H H0.
 rewrite <- (le_lt_S_eq 2 n).
 - reflexivity.
 -  apply  plus_le_reg_l with (p := 6).
    rewrite plus_comm in H; auto with arith.
 - apply   plus_lt_reg_l with (p:= 3); auto with arith.
Qed.

(** A shorter proof ...
*)

Lemma conditional_rewrite_example' : forall n:nat,
   8 < n + 6 ->  3 + n < 6 -> n * n = n + n.
Proof.
 intros n  H H0.
 assert (n = 2) by omega.
 now subst n.
Qed.

Theorem eq_trans :
   forall (A:Type)(x y z:A), x = y -> y = z -> x = z.
Proof.
 intros A x y z H; rewrite H; auto.
Qed.

Definition my_True : Prop
:= forall P:Prop, P -> P.

Definition my_False : Prop
:= forall P:Prop, P.

Theorem my_I : my_True.
Proof.
 intros P p; assumption.
Qed.

Theorem my_False_ind : forall P:Prop, my_False->P.
Proof.
 intros P F; apply F.
Qed.

Definition my_not (P:Prop) : Prop := P->my_False.

Section leibniz.

 Variable A : Type.

 Definition leibniz (a b:A) : Prop :=
 forall P:A -> Prop, P a -> P b.

Require Import Relations.

Theorem leibniz_sym : symmetric A leibniz.
Proof.
 intros x y H Q; apply H; trivial.
Qed.

End leibniz.

Definition my_and (P Q:Prop) :=
  forall R:Prop, (P->Q->R)->R.

Definition my_or (P Q:Prop) :=
  forall R:Prop, (P->R)->(Q->R)->R.

Definition my_ex (A:Type)(P:A->Prop) :=
  forall R:Prop, (forall x:A, P x -> R)->R.

Definition my_le (n p:nat) :=
  forall P:nat -> Prop, P n ->(forall q:nat, P q -> P (S q))-> P p.


Require Import Coq.Unicode.Utf8_core.

Theorem slb_plus_0_n: ∀ n : nat, 0 + n = n.
Proof.
 intros n.
 reflexivity.
Qed.

Theorem slb_plus_1_l : ∀ n : nat, 1 + n = S n.
Proof.
  intros n.
  reflexivity.
Qed.

(* _reflexivity_ is a proofing _tactic_ *)
(*  reflexivity =>
    This tactic applies to a goal that has the form t=u. It checks that t and u are convertible and then solves the goal. It is equivalent to apply refl_equal.*)