fact
stringlengths
9
10.6k
type
stringclasses
19 values
library
stringclasses
6 values
imports
listlengths
0
12
filename
stringclasses
101 values
symbolic_name
stringlengths
1
48
docstring
stringclasses
1 value
bexp1: beval (t_update empty_state X 5) (BAnd BTrue (BNot (BLe (AId X) (ANum 4)))) = true. Proof. reflexivity. Qed. (** Now we are ready define the syntax and behavior of Imp _commands_ (sometimes called _statements_). *) (** Informally, commands [c] are described by the following BNF grammar. (We choose this slightly awkward concrete syntax for the sake of being able to define Imp syntax using Coq's Notation mechanism. In particular, we use [IFB] to avoid conflicting with the [if] notation from the standard library.) c ::= SKIP | x ::= a | c ;; c | IFB b THEN c ELSE c FI | WHILE b DO c END *) (** For example, here's factorial in Imp: Z ::= X;; Y ::= 1;; WHILE not (Z = 0) DO Y ::= Y * Z;; Z ::= Z - 1 END When this command terminates, the variable [Y] will contain the factorial of the initial value of [X]. *) (** Here is the formal definition of the abstract syntax of commands: *)
Example
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
bexp1
com: Type := | CSkip : com | CAss : id -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com. (** As usual, we can use a few [Notation] declarations to make things more readable. To avoid conflicts with Coq's built-in notations, we keep this light -- in particular, we don't introduce any notations for [aexps] and [bexps] to avoid confusion with the numeric and boolean operators we've already defined. *) Notation "'SKIP'" := CSkip. Notation "x '::=' a" := (CAss x a) (at level 60). Notation "c1 ;; c2" := (CSeq c1 c2) (at level 80, right associativity). Notation "'WHILE' b 'DO' c 'END'" := (CWhile b c) (at level 80, right associativity). Notation "'IFB' c1 'THEN' c2 'ELSE' c3 'FI'" := (CIf c1 c2 c3) (at level 80, right associativity). (** For example, here is the factorial function again, written as a formal definition to Coq: *)
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
com
fact_in_coq: com := Z ::= AId X;; Y ::= ANum 1;; WHILE BNot (BEq (AId Z) (ANum 0)) DO Y ::= AMult (AId Y) (AId Z);; Z ::= AMinus (AId Z) (ANum 1) END.
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
fact_in_coq
plus2: com := X ::= (APlus (AId X) (ANum 2)).
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
plus2
XtimesYinZ: com := Z ::= (AMult (AId X) (AId Y)).
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
XtimesYinZ
subtract_slowly_body: com := Z ::= AMinus (AId Z) (ANum 1) ;; X ::= AMinus (AId X) (ANum 1).
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
subtract_slowly_body
subtract_slowly: com := WHILE BNot (BEq (AId X) (ANum 0)) DO subtract_slowly_body END.
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
subtract_slowly
subtract_3_from_5_slowly: com := X ::= ANum 3 ;; Z ::= ANum 5 ;; subtract_slowly.
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
subtract_3_from_5_slowly
loop: com := WHILE BTrue DO SKIP END. (** Next we need to define what it means to evaluate an Imp command. The fact that [WHILE] loops don't necessarily terminate makes defining an evaluation function tricky... *) (** Here's an attempt at defining an evaluation function for commands, omitting the [WHILE] case. *)
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
loop
ceval_fun_no_while(st : state) (c : com) : state := match c with | SKIP => st | x ::= a1 => t_update st x (aeval st a1) | c1 ;; c2 => let st' := ceval_fun_no_while st c1 in ceval_fun_no_while st' c2 | IFB b THEN c1 ELSE c2 FI => if (beval st b) then ceval_fun_no_while st c1 else ceval_fun_no_while st c2 | WHILE b DO c END => st (* bogus *) end. (** In a traditional functional programming language like OCaml or Haskell we could add the [WHILE] case as follows: Fixpoint ceval_fun (st : state) (c : com) : state := match c with ... | WHILE b DO c END => if (beval st b) then ceval_fun st (c; WHILE b DO c END) else st end. Coq doesn't accept such a definition ("Error: Cannot guess decreasing argument of fix") because the function we want to define is not guaranteed to terminate. Indeed, it _doesn't_ always terminate: for example, the full version of the [ceval_fun] function applied to the [loop] program above would never terminate. Since Coq is not just a functional programming language but also a consistent logic, any potentially non-terminating function needs to be rejected. Here is an (invalid!) program showing what would go wrong if Coq allowed non-terminating recursive functions: Fixpoint loop_false (n : nat) : False := loop_false n. That is, propositions like [False] would become provable ([loop_false 0] would be a proof of [False]), which would be a disaster for Coq's logical consistency. Thus, because it doesn't terminate on all inputs, of [ceval_fun] cannot be written in Coq -- at least not without additional tricks and workarounds (see chapter [ImpCEvalFun] if you're curious about what those might be). *) (** Here's a better way: define [ceval] as a _relation_ rather than a _function_ -- i.e., define it in [Prop] instead of [Type], as we did for [aevalR] above. *) (** This is an important change. Besides freeing us from awkward workarounds, it gives us a lot more flexibility in the definition. For example, if we add nondeterministic features like [any] to the language, we want the definition of evaluation to be nondeterministic -- i.e., not only will it not be total, it will not even be a function! *) (** We'll use the notation [c / st \\ st'] for the [ceval] relation: [c / st \\ st'] means that executing program [c] in a starting state [st] results in an ending state [st']. This can be pronounced "[c] takes state [st] to [st']". *) (** Here is an informal definition of evaluation, presented as inference rules for readability: ---------------- (E_Skip) SKIP / st \\ st aeval st a1 = n -------------------------------- (E_Ass) x := a1 / st \\ (t_update st x n) c1 / st \\ st' c2 / st' \\ st'' ------------------- (E_Seq) c1;;c2 / st \\ st'' beval st b1 = true c1 / st \\ st' ------------------------------------- (E_IfTrue) IF b1 THEN c1 ELSE c2 FI / st \\ st' beval st b1 = false c2 / st \\ st' ------------------------------------- (E_IfFalse) IF b1 THEN c1 ELSE c2 FI / st \\ st' beval st b = false ------------------------------ (E_WhileFalse) WHILE b DO c END / st \\ st beval st b = true c / st \\ st' WHILE b DO c END / st' \\ st'' --------------------------------- (E_WhileTrue) WHILE b DO c END / st \\ st'' *) (** Here is the formal definition. Make sure you understand how it corresponds to the inference rules. *) Reserved Notation "c1 '/' st '\\' st'" (at level 40, st at level 39).
Fixpoint
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval_fun_no_while
ceval: com -> state -> state -> Prop := | E_Skip : forall st, SKIP / st \\ st | E_Ass : forall st a1 n x, aeval st a1 = n -> (x ::= a1) / st \\ (t_update st x n) | E_Seq : forall c1 c2 st st' st'', c1 / st \\ st' -> c2 / st' \\ st'' -> (c1 ;; c2) / st \\ st'' | E_IfTrue : forall st st' b c1 c2, beval st b = true -> c1 / st \\ st' -> (IFB b THEN c1 ELSE c2 FI) / st \\ st' | E_IfFalse : forall st st' b c1 c2, beval st b = false -> c2 / st \\ st' -> (IFB b THEN c1 ELSE c2 FI) / st \\ st' | E_WhileFalse : forall b st c, beval st b = false -> (WHILE b DO c END) / st \\ st | E_WhileTrue : forall st st' st'' b c, beval st b = true -> c / st \\ st' -> (WHILE b DO c END) / st' \\ st'' -> (WHILE b DO c END) / st \\ st'' where "c1 '/' st '\\' st'" := (ceval c1 st st'). (** The cost of defining evaluation as a relation instead of a function is that we now need to construct _proofs_ that some program evaluates to some result state, rather than just letting Coq's computation mechanism do it for us. *)
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval
ceval_example1: (X ::= ANum 2;; IFB BLe (AId X) (ANum 1) THEN Y ::= ANum 3 ELSE Z ::= ANum 4 FI) / empty_state \\ (t_update (t_update empty_state X 2) Z 4). Proof. apply E_Seq with (t_update empty_state X 2). - (* assignment command *) apply E_Ass. reflexivity. - (* if command *) apply E_IfFalse. reflexivity. apply E_Ass. reflexivity. Qed.
Example
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval_example1
ceval_example2: (X ::= ANum 0;; Y ::= ANum 1;; Z ::= ANum 2) / empty_state \\ (t_update (t_update (t_update empty_state X 0) Y 1) Z 2). Proof. (* FILL IN HERE *) Admitted. (** Write an Imp program that sums the numbers from [1] to [X] (inclusive: [1 + 2 + ... + X]) in the variable [Y]. Prove that this program executes as intended for [X] = [2] (this is trickier than you might expect). *)
Example
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval_example2
pup_to_n: com (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Definition
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
pup_to_n
pup_to_2_ceval: pup_to_n / (t_update empty_state X 2) \\ t_update (t_update (t_update (t_update (t_update (t_update empty_state X 2) Y 0) Y 2) X 1) Y 3) X 0. Proof. (* FILL IN HERE *) Admitted. (** Changing from a computational to a relational definition of evaluation is a good move because it frees us from the artificial requirement that evaluation should be a total function. But it also raises a question: Is the second definition of evaluation really a partial function? Or is it possible that, beginning from the same state [st], we could evaluate some command [c] in different ways to reach two different output states [st'] and [st'']? In fact, this cannot happen: [ceval] _is_ a partial function: *)
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
pup_to_2_ceval
ceval_deterministic: forall c st st1 st2, c / st \\ st1 -> c / st \\ st2 -> st1 = st2. Proof. intros c st st1 st2 E1 E2. generalize dependent st2. induction E1; intros st2 E2; inversion E2; subst. - (* E_Skip *) reflexivity. - (* E_Ass *) reflexivity. - (* E_Seq *) assert (st' = st'0) as EQ1. { (* Proof of assertion *) apply IHE1_1; assumption. } subst st'0. apply IHE1_2. assumption. - (* E_IfTrue, b1 evaluates to true *) apply IHE1. assumption. - (* E_IfTrue, b1 evaluates to false (contradiction) *) rewrite H in H5. inversion H5. - (* E_IfFalse, b1 evaluates to true (contradiction) *) rewrite H in H5. inversion H5. - (* E_IfFalse, b1 evaluates to false *) apply IHE1. assumption. - (* E_WhileFalse, b1 evaluates to false *) reflexivity. - (* E_WhileFalse, b1 evaluates to true (contradiction) *) rewrite H in H2. inversion H2. - (* E_WhileTrue, b1 evaluates to false (contradiction) *) rewrite H in H4. inversion H4. - (* E_WhileTrue, b1 evaluates to true *) assert (st' = st'0) as EQ1. { (* Proof of assertion *) apply IHE1_1; assumption. } subst st'0. apply IHE1_2. assumption. Qed. (** We'll get deeper into systematic techniques for reasoning about Imp programs in the following chapters, but we can do quite a bit just working with the bare definitions. This section explores some examples. *)
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval_deterministic
plus2_spec: forall st n st', st X = n -> plus2 / st \\ st' -> st' X = n + 2. Proof. intros st n st' HX Heval. (** Inverting [Heval] essentially forces Coq to expand one step of the [ceval] computation -- in this case revealing that [st'] must be [st] extended with the new value of [X], since [plus2] is an assignment *) inversion Heval. subst. clear Heval. simpl. apply t_update_eq. Qed.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
plus2_spec
loop_never_stops: forall st st', ~(loop / st \\ st'). Proof. intros st st' contra. unfold loop in contra. remember (WHILE BTrue DO SKIP END) as loopdef eqn:Heqloopdef. (** Proceed by induction on the assumed derivation showing that [loopdef] terminates. Most of the cases are immediately contradictory (and so can be solved in one step with [inversion]). *) (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
loop_never_stops
no_whiles(c : com) : bool := match c with | SKIP => true | _ ::= _ => true | c1 ;; c2 => andb (no_whiles c1) (no_whiles c2) | IFB _ THEN ct ELSE cf FI => andb (no_whiles ct) (no_whiles cf) | WHILE _ DO _ END => false end. (** This predicate yields [true] just on programs that have no while loops. Using [Inductive], write a property [no_whilesR] such that [no_whilesR c] is provable exactly when [c] is a program with no while loops. Then prove its equivalence with [no_whiles]. *)
Fixpoint
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
no_whiles
no_whilesR: com -> Prop := .
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
no_whilesR
no_whiles_eqv: forall c, no_whiles c = true <-> no_whilesR c. Proof. (* FILL IN HERE *) Admitted. (** Imp programs that don't involve while loops always terminate. State and prove a theorem [no_whiles_terminating] that says this. *) (** HP Calculators, programming languages like Forth and Postscript and abstract machines like the Java Virtual Machine all evaluate arithmetic expressions using a stack. For instance, the expression (2*3)+(3*(4-2)) would be entered as 2 3 * 3 4 2 - * + and evaluated like this (where we show the program being evaluated on the right and the contents of the stack on the left): [ ] | 2 3 * 3 4 2 - * + [2] | 3 * 3 4 2 - * + [3, 2] | * 3 4 2 - * + [6] | 3 4 2 - * + [3, 6] | 4 2 - * + [4, 3, 6] | 2 - * + [2, 4, 3, 6] | - * + [2, 3, 6] | * + [6, 6] | + [12] | The task of this exercise is to write a small compiler that translates [aexp]s into stack machine instructions. The instruction set for our stack language will consist of the following instructions: - [SPush n]: Push the number [n] on the stack. - [SLoad x]: Load the identifier [x] from the store and push it on the stack - [SPlus]: Pop the two top numbers from the stack, add them, and push the result onto the stack. - [SMinus]: Similar, but subtract. - [SMult]: Similar, but multiply. *)
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
no_whiles_eqv
sinstr: Type := | SPush : nat -> sinstr | SLoad : id -> sinstr | SPlus : sinstr | SMinus : sinstr | SMult : sinstr. (** Write a function to evaluate programs in the stack language. It should take as input a state, a stack represented as a list of numbers (top stack item is the head of the list), and a program represented as a list of instructions, and it should return the stack after executing the program. Test your function on the examples below. Note that the specification leaves unspecified what to do when encountering an [SPlus], [SMinus], or [SMult] instruction if the stack contains less than two elements. In a sense, it is immaterial what we do, since our compiler will never emit such a malformed program. *)
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
sinstr
s_execute(st : state) (stack : list nat) (prog : list sinstr) : list nat (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Fixpoint
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
s_execute
s_execute1: s_execute empty_state [] [SPush 5; SPush 3; SPush 1; SMinus] = [2; 5]. (* FILL IN HERE *) Admitted.
Example
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
s_execute1
s_execute2: s_execute (t_update empty_state X 3) [3;4] [SPush 4; SLoad X; SMult; SPlus] = [15; 4]. (* FILL IN HERE *) Admitted. (** Next, write a function that compiles an [aexp] into a stack machine program. The effect of running the program should be the same as pushing the value of the expression on the stack. *)
Example
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
s_execute2
s_compile(e : aexp) : list sinstr (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted. (** After you've defined [s_compile], prove the following to test that it works. *)
Fixpoint
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
s_compile
s_compile1: s_compile (AMinus (AId X) (AMult (ANum 2) (AId Y))) = [SLoad X; SPush 2; SLoad Y; SMult; SMinus]. (* FILL IN HERE *) Admitted. (** Now we'll prove the correctness of the compiler implemented in the previous exercise. Remember that the specification left unspecified what to do when encountering an [SPlus], [SMinus], or [SMult] instruction if the stack contains less than two elements. (In order to make your correctness proof easier you might find it helpful to go back and change your implementation!) Prove the following theorem. You will need to start by stating a more general lemma to get a usable induction hypothesis; the main theorem will then be a simple corollary of this lemma. *)
Example
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
s_compile1
s_compile_correct: forall (st : state) (e : aexp), s_execute st [] (s_compile e) = [ aeval st e ]. Proof. (* FILL IN HERE *) Admitted. (** Most modern programming languages use a "short-circuit" evaluation rule for boolean [and]: to evaluate [BAnd b1 b2], first evaluate [b1]. If it evaluates to [false], then the entire [BAnd] expression evaluates to [false] immediately, without evaluating [b2]. Otherwise, [b2] is evaluated to determine the result of the [BAnd] expression. Write an alternate version of [beval] that performs short-circuit evaluation of [BAnd] in this manner, and prove that it is equivalent to [beval]. *)
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
s_compile_correct
com: Type := | CSkip : com | CBreak : com (* <-- new *) | CAss : id -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com. Notation "'SKIP'" := CSkip. Notation "'BREAK'" := CBreak. Notation "x '::=' a" := (CAss x a) (at level 60). Notation "c1 ;; c2" := (CSeq c1 c2) (at level 80, right associativity). Notation "'WHILE' b 'DO' c 'END'" := (CWhile b c) (at level 80, right associativity). Notation "'IFB' c1 'THEN' c2 'ELSE' c3 'FI'" := (CIf c1 c2 c3) (at level 80, right associativity). (** Next, we need to define the behavior of [BREAK]. Informally, whenever [BREAK] is executed in a sequence of commands, it stops the execution of that sequence and signals that the innermost enclosing loop should terminate. (If there aren't any enclosing loops, then the whole program simply terminates.) The final state should be the same as the one in which the [BREAK] statement was executed. One important point is what to do when there are multiple loops enclosing a given [BREAK]. In those cases, [BREAK] should only terminate the _innermost_ loop. Thus, after executing the following... X ::= 0;; Y ::= 1;; WHILE 0 <> Y DO WHILE TRUE DO BREAK END;; X ::= 1;; Y ::= Y - 1 END ... the value of [X] should be [1], and not [0]. One way of expressing this behavior is to add another parameter to the evaluation relation that specifies whether evaluation of a command executes a [BREAK] statement: *)
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
com
result: Type := | SContinue : result | SBreak : result. Reserved Notation "c1 '/' st '\\' s '/' st'" (at level 40, st, s at level 39). (** Intuitively, [c / st \\ s / st'] means that, if [c] is started in state [st], then it terminates in state [st'] and either signals that the innermost surrounding loop (or the whole program) should exit immediately ([s = SBreak]) or that execution should continue normally ([s = SContinue]). The definition of the "[c / st \\ s / st']" relation is very similar to the one we gave above for the regular evaluation relation ([c / st \\ st']) -- we just need to handle the termination signals appropriately: - If the command is [SKIP], then the state doesn't change and execution of any enclosing loop can continue normally. - If the command is [BREAK], the state stays unchanged but we signal a [SBreak]. - If the command is an assignment, then we update the binding for that variable in the state accordingly and signal that execution can continue normally. - If the command is of the form [IFB b THEN c1 ELSE c2 FI], then the state is updated as in the original semantics of Imp, except that we also propagate the signal from the execution of whichever branch was taken. - If the command is a sequence [c1 ;; c2], we first execute [c1]. If this yields a [SBreak], we skip the execution of [c2] and propagate the [SBreak] signal to the surrounding context; the resulting state is the same as the one obtained by executing [c1] alone. Otherwise, we execute [c2] on the state obtained after executing [c1], and propagate the signal generated there. - Finally, for a loop of the form [WHILE b DO c END], the semantics is almost the same as before. The only difference is that, when [b] evaluates to true, we execute [c] and check the signal that it raises. If that signal is [SContinue], then the execution proceeds as in the original semantics. Otherwise, we stop the execution of the loop, and the resulting state is the same as the one resulting from the execution of the current iteration. In either case, since [BREAK] only terminates the innermost loop, [WHILE] signals [SContinue]. *) (** Based on the above description, complete the definition of the [ceval] relation. *)
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
result
ceval: com -> state -> result -> state -> Prop := | E_Skip : forall st, CSkip / st \\ SContinue / st where "c1 '/' st '\\' s '/' st'" := (ceval c1 st s st').
Inductive
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval
break_ignore: forall c st st' s, (BREAK;; c) / st \\ s / st' -> st = st'. Proof. (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
break_ignore
while_continue: forall b c st st' s, (WHILE b DO c END) / st \\ s / st' -> s = SContinue. Proof. (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
while_continue
while_stops_on_break: forall b c st st', beval st b = true -> c / st \\ SBreak / st' -> (WHILE b DO c END) / st \\ SContinue / st'. Proof. (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
while_stops_on_break
while_break_true: forall b c st st', (WHILE b DO c END) / st \\ SContinue / st' -> beval st' b = true -> exists st'', c / st'' \\ SBreak / st'. Proof. (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
while_break_true
ceval_deterministic: forall (c:com) st st1 st2 s1 s2, c / st \\ s1 / st1 -> c / st \\ s2 / st2 -> st1 = st2 /\ s1 = s2. Proof. (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.Bool.Bool", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.omega.Omega", "Require Import Coq.Lists.List", "Require Import Maps" ]
sf-experiment/Imp.v
ceval_deterministic
ceval_step1(st : state) (c : com) : state := match c with | SKIP => st | l ::= a1 => t_update st l (aeval st a1) | c1 ;; c2 => let st' := ceval_step1 st c1 in ceval_step1 st' c2 | IFB b THEN c1 ELSE c2 FI => if (beval st b) then ceval_step1 st c1 else ceval_step1 st c2 | WHILE b1 DO c1 END => st (* bogus *) end. (** As we remarked in chapter [Imp], in a traditional functional programming language like ML or Haskell we could write the WHILE case as follows: | WHILE b1 DO c1 END => if (beval st b1) then ceval_step1 st (c1;; WHILE b1 DO c1 END) else st Coq doesn't accept such a definition ([Error: Cannot guess decreasing argument of fix]) because the function we want to define is not guaranteed to terminate. Indeed, the changed [ceval_step1] function applied to the [loop] program from [Imp.v] would never terminate. Since Coq is not just a functional programming language, but also a consistent logic, any potentially non-terminating function needs to be rejected. Here is an invalid(!) Coq program showing what would go wrong if Coq allowed non-terminating recursive functions: Fixpoint loop_false (n : nat) : False := loop_false n. That is, propositions like [False] would become provable (e.g., [loop_false 0] would be a proof of [False]), which would be a disaster for Coq's logical consistency. Thus, because it doesn't terminate on all inputs, the full version of [ceval_step1] cannot be written in Coq -- at least not without one additional trick... *) (** The trick we need is to pass an _additional_ parameter to the evaluation function that tells it how long to run. Informally, we start the evaluator with a certain amount of "gas" in its tank, and we allow it to run until either it terminates in the usual way _or_ it runs out of gas, at which point we simply stop evaluating and say that the final result is the empty memory. (We could also say that the result is the current state at the point where the evaluator runs out fo gas -- it doesn't really matter because the result is going to be wrong in either case!) *)
Fixpoint
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_step1
ceval_step2(st : state) (c : com) (i : nat) : state := match i with | O => empty_state | S i' => match c with | SKIP => st | l ::= a1 => t_update st l (aeval st a1) | c1 ;; c2 => let st' := ceval_step2 st c1 i' in ceval_step2 st' c2 i' | IFB b THEN c1 ELSE c2 FI => if (beval st b) then ceval_step2 st c1 i' else ceval_step2 st c2 i' | WHILE b1 DO c1 END => if (beval st b1) then let st' := ceval_step2 st c1 i' in ceval_step2 st' c i' else st end end. (** _Note_: It is tempting to think that the index [i] here is counting the "number of steps of evaluation." But if you look closely you'll see that this is not the case: for example, in the rule for sequencing, the same [i] is passed to both recursive calls. Understanding the exact way that [i] is treated will be important in the proof of [ceval__ceval_step], which is given as an exercise below. One thing that is not so nice about this evaluator is that we can't tell, from its result, whether it stopped because the program terminated normally or because it ran out of gas. Our next version returns an [option state] instead of just a [state], so that we can distinguish between normal and abnormal termination. *)
Fixpoint
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_step2
ceval_step3(st : state) (c : com) (i : nat) : option state := match i with | O => None | S i' => match c with | SKIP => Some st | l ::= a1 => Some (t_update st l (aeval st a1)) | c1 ;; c2 => match (ceval_step3 st c1 i') with | Some st' => ceval_step3 st' c2 i' | None => None end | IFB b THEN c1 ELSE c2 FI => if (beval st b) then ceval_step3 st c1 i' else ceval_step3 st c2 i' | WHILE b1 DO c1 END => if (beval st b1) then match (ceval_step3 st c1 i') with | Some st' => ceval_step3 st' c i' | None => None end else Some st end end. (** We can improve the readability of this version by introducing a bit of auxiliary notation to hide the plumbing involved in repeatedly matching against optional states. *) Notation "'LETOPT' x <== e1 'IN' e2" := (match e1 with | Some x => e2 | None => None end) (right associativity, at level 60).
Fixpoint
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_step3
ceval_step(st : state) (c : com) (i : nat) : option state := match i with | O => None | S i' => match c with | SKIP => Some st | l ::= a1 => Some (t_update st l (aeval st a1)) | c1 ;; c2 => LETOPT st' <== ceval_step st c1 i' IN ceval_step st' c2 i' | IFB b THEN c1 ELSE c2 FI => if (beval st b) then ceval_step st c1 i' else ceval_step st c2 i' | WHILE b1 DO c1 END => if (beval st b1) then LETOPT st' <== ceval_step st c1 i' IN ceval_step st' c i' else Some st end end.
Fixpoint
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_step
test_ceval(st:state) (c:com) := match ceval_step st c 500 with | None => None | Some st => Some (st X, st Y, st Z) end. (* Compute (test_ceval empty_state (X ::= ANum 2;; IFB BLe (AId X) (ANum 1) THEN Y ::= ANum 3 ELSE Z ::= ANum 4 FI)). ====> Some (2, 0, 4) *) (** Write an Imp program that sums the numbers from [1] to [X] (inclusive: [1 + 2 + ... + X]) in the variable [Y]. Make sure your solution satisfies the test that follows. *)
Definition
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
test_ceval
pup_to_n: com (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted. (*
Definition
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
pup_to_n
pup_to_n_1: test_ceval (t_update empty_state X 5) pup_to_n = Some (0, 15, 0). Proof. reflexivity. Qed. *) (** Write a [While] program that sets [Z] to [0] if [X] is even and sets [Z] to [1] otherwise. Use [ceval_test] to test your program. *) (** As for arithmetic and boolean expressions, we'd hope that the two alternative definitions of evaluation would actually amount to the same thing in the end. This section shows that this is the case. *)
Example
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
pup_to_n_1
ceval_step__ceval: forall c st st', (exists i, ceval_step st c i = Some st') -> c / st \\ st'. Proof. intros c st st' H. inversion H as [i E]. clear H. generalize dependent st'. generalize dependent st. generalize dependent c. induction i as [| i' ]. - (* i = 0 -- contradictory *) intros c st st' H. inversion H. - (* i = S i' *) intros c st st' H. destruct c; simpl in H; inversion H; subst; clear H. + (* SKIP *) apply E_Skip. + (* ::= *) apply E_Ass. reflexivity. + (* ;; *) destruct (ceval_step st c1 i') eqn:Heqr1. * (* Evaluation of r1 terminates normally *) apply E_Seq with s. apply IHi'. rewrite Heqr1. reflexivity. apply IHi'. simpl in H1. assumption. * (* Otherwise -- contradiction *) inversion H1. + (* IFB *) destruct (beval st b) eqn:Heqr. * (* r = true *) apply E_IfTrue. rewrite Heqr. reflexivity. apply IHi'. assumption. * (* r = false *) apply E_IfFalse. rewrite Heqr. reflexivity. apply IHi'. assumption. + (* WHILE *) destruct (beval st b) eqn :Heqr. * (* r = true *) destruct (ceval_step st c i') eqn:Heqr1. { (* r1 = Some s *) apply E_WhileTrue with s. rewrite Heqr. reflexivity. apply IHi'. rewrite Heqr1. reflexivity. apply IHi'. simpl in H1. assumption. } { (* r1 = None *) inversion H1. } * (* r = false *) inversion H1. apply E_WhileFalse. rewrite <- Heqr. subst. reflexivity. Qed. (** Write an informal proof of [ceval_step__ceval], following the usual template. (The template for case analysis on an inductively defined value should look the same as for induction, except that there is no induction hypothesis.) Make your proof communicate the main ideas to a human reader; do not simply transcribe the steps of the formal proof. [] *)
Theorem
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_step__ceval
ceval_step_more: forall i1 i2 st st' c, i1 <= i2 -> ceval_step st c i1 = Some st' -> ceval_step st c i2 = Some st'. Proof. induction i1 as [|i1']; intros i2 st st' c Hle Hceval. - (* i1 = 0 *) simpl in Hceval. inversion Hceval. - (* i1 = S i1' *) destruct i2 as [|i2']. inversion Hle. assert (Hle': i1' <= i2') by omega. destruct c. + (* SKIP *) simpl in Hceval. inversion Hceval. reflexivity. + (* ::= *) simpl in Hceval. inversion Hceval. reflexivity. + (* ;; *) simpl in Hceval. simpl. destruct (ceval_step st c1 i1') eqn:Heqst1'o. * (* st1'o = Some *) apply (IHi1' i2') in Heqst1'o; try assumption. rewrite Heqst1'o. simpl. simpl in Hceval. apply (IHi1' i2') in Hceval; try assumption. * (* st1'o = None *) inversion Hceval. + (* IFB *) simpl in Hceval. simpl. destruct (beval st b); apply (IHi1' i2') in Hceval; assumption. + (* WHILE *) simpl in Hceval. simpl. destruct (beval st b); try assumption. destruct (ceval_step st c i1') eqn: Heqst1'o. * (* st1'o = Some *) apply (IHi1' i2') in Heqst1'o; try assumption. rewrite -> Heqst1'o. simpl. simpl in Hceval. apply (IHi1' i2') in Hceval; try assumption. * (* i1'o = None *) simpl in Hceval. inversion Hceval. Qed. (** Finish the following proof. You'll need [ceval_step_more] in a few places, as well as some basic facts about [<=] and [plus]. *)
Theorem
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_step_more
ceval__ceval_step: forall c st st', c / st \\ st' -> exists i, ceval_step st c i = Some st'. Proof. intros c st st' Hce. induction Hce. (* FILL IN HERE *) Admitted.
Theorem
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval__ceval_step
ceval_and_ceval_step_coincide: forall c st st', c / st \\ st' <-> exists i, ceval_step st c i = Some st'. Proof. intros c st st'. split. apply ceval__ceval_step. apply ceval_step__ceval. Qed. (** Using the fact that the relational and step-indexed definition of evaluation are the same, we can give a slicker proof that the evaluation _relation_ is deterministic. *)
Theorem
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_and_ceval_step_coincide
ceval_deterministic': forall c st st1 st2, c / st \\ st1 -> c / st \\ st2 -> st1 = st2. Proof. intros c st st1 st2 He1 He2. apply ceval__ceval_step in He1. apply ceval__ceval_step in He2. inversion He1 as [i1 E1]. inversion He2 as [i2 E2]. apply ceval_step_more with (i2 := i1 + i2) in E1. apply ceval_step_more with (i2 := i1 + i2) in E2. rewrite E1 in E2. inversion E2. reflexivity. omega. omega. Qed.
Theorem
sf-experiment
[ "Require Import Coq.omega.Omega", "Require Import Coq.Arith.Arith", "Require Import Imp", "Require Import Maps" ]
sf-experiment/ImpCEvalFun.v
ceval_deterministic'
isWhite(c : ascii) : bool := let n := nat_of_ascii c in orb (orb (beq_nat n 32) (* space *) (beq_nat n 9)) (* tab *) (orb (beq_nat n 10) (* linefeed *) (beq_nat n 13)). (* Carriage return. *) Notation "x '<=?' y" := (leb x y) (at level 70, no associativity) : nat_scope.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
isWhite
isLowerAlpha(c : ascii) : bool := let n := nat_of_ascii c in andb (97 <=? n) (n <=? 122).
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
isLowerAlpha
isAlpha(c : ascii) : bool := let n := nat_of_ascii c in orb (andb (65 <=? n) (n <=? 90)) (andb (97 <=? n) (n <=? 122)).
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
isAlpha
isDigit(c : ascii) : bool := let n := nat_of_ascii c in andb (48 <=? n) (n <=? 57).
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
isDigit
chartype:= white | alpha | digit | other.
Inductive
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
chartype
classifyChar(c : ascii) : chartype := if isWhite c then white else if isAlpha c then alpha else if isDigit c then digit else other.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
classifyChar
list_of_string(s : string) : list ascii := match s with | EmptyString => [] | String c s => c :: (list_of_string s) end.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
list_of_string
string_of_list(xs : list ascii) : string := fold_right String EmptyString xs.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
string_of_list
token:= string.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
token
tokenize_helper(cls : chartype) (acc xs : list ascii) : list (list ascii) := let tk := match acc with [] => [] | _::_ => [rev acc] end in match xs with | [] => tk | (x::xs') => match cls, classifyChar x, x with | _, _, "(" => tk ++ ["("]::(tokenize_helper other [] xs') | _, _, ")" => tk ++ [")"]::(tokenize_helper other [] xs') | _, white, _ => tk ++ (tokenize_helper white [] xs') | alpha,alpha,x => tokenize_helper alpha (x::acc) xs' | digit,digit,x => tokenize_helper digit (x::acc) xs' | other,other,x => tokenize_helper other (x::acc) xs' | _,tp,x => tk ++ (tokenize_helper tp [x] xs') end end %char.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
tokenize_helper
tokenize(s : string) : list string := map string_of_list (tokenize_helper white [] (list_of_string s)).
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
tokenize
tokenize_ex1: tokenize "abc12==3 223*(3+(a+c))" %string = ["abc"; "12"; "=="; "3"; "223"; "*"; "("; "3"; "+"; "("; "a"; "+"; "c"; ")"; ")"]%string. Proof. reflexivity. Qed.
Example
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
tokenize_ex1
optionE(X:Type) : Type := | SomeE : X -> optionE X | NoneE : string -> optionE X. Implicit Arguments SomeE [[X]]. Implicit Arguments NoneE [[X]]. (** Some syntactic sugar to make writing nested match-expressions on optionE more convenient. *) Notation "'DO' ( x , y ) <== e1 ; e2" := (match e1 with | SomeE (x,y) => e2 | NoneE err => NoneE err end) (right associativity, at level 60). Notation "'DO' ( x , y ) <-- e1 ; e2 'OR' e3" := (match e1 with | SomeE (x,y) => e2 | NoneE err => e3 end) (right associativity, at level 60, e2 at next level). Open Scope string_scope.
Inductive
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
optionE
parser(T : Type) := list token -> optionE (T * list token).
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parser
many_helper{T} (p : parser T) acc steps xs := match steps, p xs with | 0, _ => NoneE "Too many recursive calls" | _, NoneE _ => SomeE ((rev acc), xs) | S steps', SomeE (t, xs') => many_helper p (t::acc) steps' xs' end.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
many_helper
many{T} (p : parser T) (steps : nat) : parser (list T) := many_helper p [] steps.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
many
firstExpect{T} (t : token) (p : parser T) : parser T := fun xs => match xs with | x::xs' => if string_dec x t then p xs' else NoneE ("expected '" ++ t ++ "'.") | [] => NoneE ("expected '" ++ t ++ "'.") end.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
firstExpect
expect(t : token) : parser unit := firstExpect t (fun xs => SomeE(tt, xs)).
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
expect
parseIdentifier(xs : list token) : optionE (id * list token) := match xs with | [] => NoneE "Expected identifier" | x::xs' => if forallb isLowerAlpha (list_of_string x) then SomeE (Id x, xs') else NoneE ("Illegal identifier:'" ++ x ++ "'") end.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parseIdentifier
parseNumber(xs : list token) : optionE (nat * list token) := match xs with | [] => NoneE "Expected number" | x::xs' => if forallb isDigit (list_of_string x) then SomeE (fold_left (fun n d => 10 * n + (nat_of_ascii d - nat_of_ascii "0"%char)) (list_of_string x) 0, xs') else NoneE "Expected number" end.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parseNumber
parsePrimaryExp(steps:nat) (xs : list token) : optionE (aexp * list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (i, rest) <-- parseIdentifier xs ; SomeE (AId i, rest) OR DO (n, rest) <-- parseNumber xs ; SomeE (ANum n, rest) OR (DO (e, rest) <== firstExpect "(" (parseSumExp steps') xs; DO (u, rest') <== expect ")" rest ; SomeE(e,rest')) end with parseProductExp (steps:nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (e, rest) <== parsePrimaryExp steps' xs ; DO (es, rest') <== many (firstExpect "*" (parsePrimaryExp steps')) steps' rest; SomeE (fold_left AMult es e, rest') end with parseSumExp (steps:nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (e, rest) <== parseProductExp steps' xs ; DO (es, rest') <== many (fun xs => DO (e,rest') <-- firstExpect "+" (parseProductExp steps') xs; SomeE ( (true, e), rest') OR DO (e,rest') <== firstExpect "-" (parseProductExp steps') xs; SomeE ( (false, e), rest')) steps' rest; SomeE (fold_left (fun e0 term => match term with (true, e) => APlus e0 e | (false, e) => AMinus e0 e end) es e, rest') end.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parsePrimaryExp
parseAExp:= parseSumExp.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parseAExp
parseAtomicExp(steps:nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (u,rest) <-- expect "true" xs; SomeE (BTrue,rest) OR DO (u,rest) <-- expect "false" xs; SomeE (BFalse,rest) OR DO (e,rest) <-- firstExpect "not" (parseAtomicExp steps') xs; SomeE (BNot e, rest) OR DO (e,rest) <-- firstExpect "(" (parseConjunctionExp steps') xs; (DO (u,rest') <== expect ")" rest; SomeE (e, rest')) OR DO (e, rest) <== parseProductExp steps' xs; (DO (e', rest') <-- firstExpect "==" (parseAExp steps') rest; SomeE (BEq e e', rest') OR DO (e', rest') <-- firstExpect "<=" (parseAExp steps') rest; SomeE (BLe e e', rest') OR NoneE "Expected '==' or '<=' after arithmetic expression") end with parseConjunctionExp (steps:nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (e, rest) <== parseAtomicExp steps' xs ; DO (es, rest') <== many (firstExpect "&&" (parseAtomicExp steps')) steps' rest; SomeE (fold_left BAnd es e, rest') end.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parseAtomicExp
parseBExp:= parseConjunctionExp. Check parseConjunctionExp.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parseBExp
testParsing{X : Type} (p : nat -> list token -> optionE (X * list token)) (s : string) := let t := tokenize s in p 100 t. (* Eval compute in testParsing parseProductExp "x*y*(x*x)*x". Eval compute in testParsing parseConjunctionExp "not((x==x||x*x<=(x*x)*x)&&x==x". *)
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
testParsing
parseSimpleCommand(steps:nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (u, rest) <-- expect "SKIP" xs; SomeE (SKIP, rest) OR DO (e,rest) <-- firstExpect "IF" (parseBExp steps') xs; DO (c,rest') <== firstExpect "THEN" (parseSequencedCommand steps') rest; DO (c',rest'') <== firstExpect "ELSE" (parseSequencedCommand steps') rest'; DO (u,rest''') <== expect "END" rest''; SomeE(IFB e THEN c ELSE c' FI, rest''') OR DO (e,rest) <-- firstExpect "WHILE" (parseBExp steps') xs; DO (c,rest') <== firstExpect "DO" (parseSequencedCommand steps') rest; DO (u,rest'') <== expect "END" rest'; SomeE(WHILE e DO c END, rest'') OR DO (i, rest) <== parseIdentifier xs; DO (e, rest') <== firstExpect ":=" (parseAExp steps') rest; SomeE(i ::= e, rest') end with parseSequencedCommand (steps:nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => DO (c, rest) <== parseSimpleCommand steps' xs; DO (c', rest') <-- firstExpect ";" (parseSequencedCommand steps') rest; SomeE(c ;; c', rest') OR SomeE(c, rest) end.
Fixpoint
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parseSimpleCommand
bignumber:= 1000.
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
bignumber
parse(str : string) : optionE (com * list token) := let tokens := tokenize str in parseSequencedCommand bignumber tokens. (* Compute parse " IF x == y + 1 + 2 - y * 6 + 3 THEN x := x * 1;; y := 0 ELSE SKIP END ". ====> SomeE (IFB BEq (AId (Id 0)) (APlus (AMinus (APlus (APlus (AId (Id 1)) (ANum 1)) (ANum 2)) (AMult (AId (Id 1)) (ANum 6))) (ANum 3)) THEN Id 0 ::= AMult (AId (Id 0)) (ANum 1);; Id 1 ::= ANum 0 ELSE SKIP FI, []) *) (* Compute parse " SKIP;; z:=x*y*(x*x);; WHILE x==x DO IF z <= z*z && not x == 2 THEN x := z;; y := z ELSE SKIP END;; SKIP END;; x:=z ". ====> SomeE (SKIP;; Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2))) (AMult (AId (Id 1)) (AId (Id 1)));; WHILE BEq (AId (Id 1)) (AId (Id 1)) DO IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0)))) (BNot (BEq (AId (Id 1)) (ANum 2))) THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0) ELSE SKIP FI;; SKIP END;; Id 1 ::= AId (Id 0), []) *) (* Compute parse " SKIP;; z:=x*y*(x*x);; WHILE x==x DO IF z <= z*z && not x == 2 THEN x := z;; y := z ELSE SKIP END;; SKIP END;; x:=z ". =====> SomeE (SKIP;; Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2))) (AMult (AId (Id 1)) (AId (Id 1)));; WHILE BEq (AId (Id 1)) (AId (Id 1)) DO IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0)))) (BNot (BEq (AId (Id 1)) (ANum 2))) THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0) ELSE SKIP FI;; SKIP END;; Id 1 ::= AId (Id 0), []). *)
Definition
sf-experiment
[ "Require Import Coq.Strings.String", "Require Import Coq.Strings.Ascii", "Require Import Coq.Arith.Arith", "Require Import Coq.Arith.EqNat", "Require Import Coq.Lists.List", "Require Import Maps", "Require Import Imp" ]
sf-experiment/ImpParser.v
parse
mult_0_r': forall n:nat, n * 0 = 0. Proof. apply nat_ind. - (* n = O *) reflexivity. - (* n = S n' *) simpl. intros n' IHn'. rewrite -> IHn'. reflexivity. Qed. (** This proof is basically the same as the earlier one, but a few minor differences are worth noting. First, in the induction step of the proof (the ["S"] case), we have to do a little bookkeeping manually (the [intros]) that [induction] does automatically. Second, we do not introduce [n] into the context before applying [nat_ind] -- the conclusion of [nat_ind] is a quantified formula, and [apply] needs this conclusion to exactly match the shape of the goal state, including the quantifier. By contrast, the [induction] tactic works either with a variable in the context or a quantified variable in the goal. These conveniences make [induction] nicer to use in practice than applying induction principles like [nat_ind] directly. But it is important to realize that, modulo these bits of bookkeeping, applying [nat_ind] is what we are really doing. *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
mult_0_r'
plus_one_r': forall n:nat, n + 1 = S n. Proof. (* FILL IN HERE *) Admitted. (** Coq generates induction principles for every datatype defined with [Inductive], including those that aren't recursive. Although of course we don't need induction to prove properties of non-recursive datatypes, the idea of an induction principle still makes sense for them: it gives a way to prove that a property holds for all values of the type. These generated principles follow a similar pattern. If we define a type [t] with constructors [c1] ... [cn], Coq generates a theorem with this shape: t_ind : forall P : t -> Prop, ... case for c1 ... -> ... case for c2 ... -> ... ... case for cn ... -> forall n : t, P n The specific shape of each case depends on the arguments to the corresponding constructor. Before trying to write down a general rule, let's look at some more examples. First, an example where the constructors take no arguments: *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
plus_one_r'
yesno: Type := | yes : yesno | no : yesno. Check yesno_ind. (* ===> yesno_ind : forall P : yesno -> Prop, P yes -> P no -> forall y : yesno, P y *) (** Write out the induction principle that Coq will generate for the following datatype. Write down your answer on paper or type it into a comment, and then compare it with what Coq prints. *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
yesno
rgb: Type := | red : rgb | green : rgb | blue : rgb. Check rgb_ind. (** Here's another example, this time with one of the constructors taking some arguments. *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
rgb
natlist: Type := | nnil : natlist | ncons : nat -> natlist -> natlist. Check natlist_ind. (* ===> (modulo a little variable renaming) natlist_ind : forall P : natlist -> Prop, P nnil -> (forall (n : nat) (l : natlist), P l -> P (ncons n l)) -> forall n : natlist, P n *) (** Suppose we had written the above definition a little differently: *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
natlist
natlist1: Type := | nnil1 : natlist1 | nsnoc1 : natlist1 -> nat -> natlist1. (** From these examples, we can extract this general rule: - The type declaration gives several constructors; each corresponds to one clause of the induction principle. - Each constructor [c] takes argument types [a1] ... [an]. - Each [ai] can be either [t] (the datatype we are defining) or some other type [s]. - The corresponding case of the induction principle says: - "For all values [x1]...[xn] of types [a1]...[an], if [P] holds for each of the inductive arguments (each [xi] of type [t]), then [P] holds for [c x1 ... xn]". *) (** Write out the induction principle that Coq will generate for the following datatype. (Again, write down your answer on paper or type it into a comment, and then compare it with what Coq prints.) *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
natlist1
byntree: Type := | bempty : byntree | bleaf : yesno -> byntree | nbranch : yesno -> byntree -> byntree -> byntree. (** Here is an induction principle for an inductively defined set. ExSet_ind : forall P : ExSet -> Prop, (forall b : bool, P (con1 b)) -> (forall (n : nat) (e : ExSet), P e -> P (con2 n e)) -> forall e : ExSet, P e Give an [Inductive] definition of [ExSet]: *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
byntree
ExSet: Type := . (** Next, what about polymorphic datatypes? The inductive definition of polymorphic lists Inductive list (X:Type) : Type := | nil : list X | cons : X -> list X -> list X. is very similar to that of [natlist]. The main difference is that, here, the whole definition is _parameterized_ on a set [X]: that is, we are defining a _family_ of inductive types [list X], one for each [X]. (Note that, wherever [list] appears in the body of the declaration, it is always applied to the parameter [X].) The induction principle is likewise parameterized on [X]: list_ind : forall (X : Type) (P : list X -> Prop), P [] -> (forall (x : X) (l : list X), P l -> P (x :: l)) -> forall l : list X, P l Note that the _whole_ induction principle is parameterized on [X]. That is, [list_ind] can be thought of as a polymorphic function that, when applied to a type [X], gives us back an induction principle specialized to the type [list X]. *) (** Write out the induction principle that Coq will generate for the following datatype. Compare your answer with what Coq prints. *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
ExSet
tree(X:Type) : Type := | leaf : X -> tree X | node : tree X -> tree X -> tree X. Check tree_ind. (** Find an inductive definition that gives rise to the following induction principle: mytype_ind : forall (X : Type) (P : mytype X -> Prop), (forall x : X, P (constr1 X x)) -> (forall n : nat, P (constr2 X n)) -> (forall m : mytype X, P m -> forall n : nat, P (constr3 X m n)) -> forall m : mytype X, P m *) (** Find an inductive definition that gives rise to the following induction principle: foo_ind : forall (X Y : Type) (P : foo X Y -> Prop), (forall x : X, P (bar X Y x)) -> (forall y : Y, P (baz X Y y)) -> (forall f1 : nat -> foo X Y, (forall n : nat, P (f1 n)) -> P (quux X Y f1)) -> forall f2 : foo X Y, P f2 *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
tree
foo'(X:Type) : Type := | C1 : list X -> foo' X -> foo' X | C2 : foo' X. (** What induction principle will Coq generate for [foo']? Fill in the blanks, then check your answer with Coq.) foo'_ind : forall (X : Type) (P : foo' X -> Prop), (forall (l : list X) (f : foo' X), _______________________ -> _______________________ ) -> ___________________________________________ -> forall f : foo' X, ________________________ *) (** Where does the phrase "induction hypothesis" fit into this story? The induction principle for numbers forall P : nat -> Prop, P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n is a generic statement that holds for all propositions [P] (or rather, strictly speaking, for all families of propositions [P] indexed by a number [n]). Each time we use this principle, we are choosing [P] to be a particular expression of type [nat->Prop]. We can make proofs by induction more explicit by giving this expression a name. For example, instead of stating the theorem [mult_0_r] as "[forall n, n * 0 = 0]," we can write it as "[forall n, P_m0r n]", where [P_m0r] is defined as... *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
foo'
P_m0r(n:nat) : Prop := n * 0 = 0.
Definition
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
P_m0r
P_m0r': nat->Prop := fun n => n * 0 = 0.
Definition
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
P_m0r'
mult_0_r'': forall n:nat, P_m0r n. Proof. apply nat_ind. - (* n = O *) reflexivity. - (* n = S n' *) intros n IHn. unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed. (** This extra naming step isn't something that we do in normal proofs, but it is useful to do it explicitly for an example or two, because it allows us to see exactly what the induction hypothesis is. If we prove [forall n, P_m0r n] by induction on [n] (using either [induction] or [apply nat_ind]), we see that the first subgoal requires us to prove [P_m0r 0] ("[P] holds for zero"), while the second subgoal requires us to prove [forall n', P_m0r n' -> P_m0r (S n')] (that is "[P] holds of [S n'] if it holds of [n']" or, more elegantly, "[P] is preserved by [S]"). The _induction hypothesis_ is the premise of this latter implication -- the assumption that [P] holds of [n'], which we are allowed to use in proving that [P] holds for [S n']. *) (** The [induction] tactic actually does even more low-level bookkeeping for us than we discussed above. Recall the informal statement of the induction principle for natural numbers: - If [P n] is some proposition involving a natural number n, and we want to show that P holds for _all_ numbers n, we can reason like this: - show that [P O] holds - show that, if [P n'] holds, then so does [P (S n')] - conclude that [P n] holds for all n. So, when we begin a proof with [intros n] and then [induction n], we are first telling Coq to consider a _particular_ [n] (by introducing it into the context) and then telling it to prove something about _all_ numbers (by using induction). What Coq actually does in this situation, internally, is to "re-generalize" the variable we perform induction on. For example, in our original proof that [plus] is associative... *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
mult_0_r''
plus_assoc': forall n m p : nat, n + (m + p) = (n + m) + p. Proof. (* ...we first introduce all 3 variables into the context, which amounts to saying "Consider an arbitrary [n], [m], and [p]..." *) intros n m p. (* ...We now use the [induction] tactic to prove [P n] (that is, [n + (m + p) = (n + m) + p]) for _all_ [n], and hence also for the particular [n] that is in the context at the moment. *) induction n as [| n']. - (* n = O *) reflexivity. - (* n = S n' *) (* In the second subgoal generated by [induction] -- the "inductive step" -- we must prove that [P n'] implies [P (S n')] for all [n']. The [induction] tactic automatically introduces [n'] and [P n'] into the context for us, leaving just [P (S n')] as the goal. *) simpl. rewrite -> IHn'. reflexivity. Qed. (** It also works to apply [induction] to a variable that is quantified in the goal. *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
plus_assoc'
plus_comm': forall n m : nat, n + m = m + n. Proof. induction n as [| n']. - (* n = O *) intros m. rewrite <- plus_n_O. reflexivity. - (* n = S n' *) intros m. simpl. rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity. Qed. (** Note that [induction n] leaves [m] still bound in the goal -- i.e., what we are proving inductively is a statement beginning with [forall m]. If we do [induction] on a variable that is quantified in the goal _after_ some other quantifiers, the [induction] tactic will automatically introduce the variables bound by these quantifiers into the context. *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
plus_comm'
plus_comm'': forall n m : nat, n + m = m + n. Proof. induction m as [| m']. - (* m = O *) simpl. rewrite <- plus_n_O. reflexivity. - (* m = S m' *) simpl. rewrite <- IHm'. rewrite <- plus_n_Sm. reflexivity. Qed. (** Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in the same style as [mult_0_r''] above -- that is, for each theorem, give an explicit [Definition] of the proposition being proved by induction, and state the theorem and proof in terms of this defined proposition. *) (** Earlier, we looked in detail at the induction principles that Coq generates for inductively defined _sets_. The induction principles for inductively defined _propositions_ like [ev] are a tiny bit more complicated. As with all induction principles, we want to use the induction principle on [ev] to prove things by inductively considering the possible shapes that something in [ev] can have. Intuitively speaking, however, what we want to prove are not statements about _evidence_ but statements about _numbers_: accordingly, we want an induction principle that lets us prove properties of numbers by induction on evidence. For example, from what we've said so far, you might expect the inductive definition of [ev]... Inductive ev : nat -> Prop := | ev_0 : ev 0 | ev_SS : forall n : nat, ev n -> ev (S (S n)). ...to give rise to an induction principle that looks like this... ev_ind_max : forall P : (forall n : nat, ev n -> Prop), P O ev_0 -> (forall (m : nat) (E : ev m), P m E -> P (S (S m)) (ev_SS m E)) -> forall (n : nat) (E : ev n), P n E ... because: - Since [ev] is indexed by a number [n] (every [ev] object [E] is a piece of evidence that some particular number [n] is even), the proposition [P] is parameterized by both [n] and [E] -- that is, the induction principle can be used to prove assertions involving both an even number and the evidence that it is even. - Since there are two ways of giving evidence of evenness ([ev] has two constructors), applying the induction principle generates two subgoals: - We must prove that [P] holds for [O] and [ev_0]. - We must prove that, whenever [n] is an even number and [E] is an evidence of its evenness, if [P] holds of [n] and [E], then it also holds of [S (S n)] and [ev_SS n E]. - If these subgoals can be proved, then the induction principle tells us that [P] is true for _all_ even numbers [n] and evidence [E] of their evenness. This is more flexibility than we normally need or want: it is giving us a way to prove logical assertions where the assertion involves properties of some piece of _evidence_ of evenness, while all we really care about is proving properties of _numbers_ that are even -- we are interested in assertions about numbers, not about evidence. It would therefore be more convenient to have an induction principle for proving propositions [P] that are parameterized just by [n] and whose conclusion establishes [P] for all even numbers [n]: forall P : nat -> Prop, ... -> forall n : nat, even n -> P n For this reason, Coq actually generates the following simplified induction principle for [ev]: *) Check ev_ind. (* ===> ev_ind : forall P : nat -> Prop, P 0 -> (forall n : nat, ev n -> P n -> P (S (S n))) -> forall n : nat, ev n -> P n *) (** In particular, Coq has dropped the evidence term [E] as a parameter of the the proposition [P]. *) (** In English, [ev_ind] says: - Suppose, [P] is a property of natural numbers (that is, [P n] is a [Prop] for every [n]). To show that [P n] holds whenever [n] is even, it suffices to show: - [P] holds for [0], - for any [n], if [n] is even and [P] holds for [n], then [P] holds for [S (S n)]. *) (** As expected, we can apply [ev_ind] directly instead of using [induction]. For example, we can use it to show that [ev'] (the slightly awkward alternate definition of evenness that we saw in an exercise in the \chap{IndProp} chapter) is equivalent to the cleaner inductive definition [ev]: *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
plus_comm''
ev_ev': forall n, ev n -> ev' n. Proof. apply ev_ind. - (* ev_0 *) apply ev'_0. - (* ev_SS *) intros m Hm IH. apply (ev'_sum 2 m). + apply ev'_2. + apply IH. Qed. (** The precise form of an [Inductive] definition can affect the induction principle Coq generates. For example, in chapter [IndProp], we defined [<=] as: *) (* Inductive le : nat -> nat -> Prop := | le_n : forall n, le n n | le_S : forall n m, (le n m) -> (le n (S m)). *) (** This definition can be streamlined a little by observing that the left-hand argument [n] is the same everywhere in the definition, so we can actually make it a "general parameter" to the whole definition, rather than an argument to each constructor. *)
Theorem
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
ev_ev'
le(n:nat) : nat -> Prop := | le_n : le n n | le_S : forall m, (le n m) -> (le n (S m)). Notation "m <= n" := (le m n). (** The second one is better, even though it looks less symmetric. Why? Because it gives us a simpler induction principle. *) Check le_ind. (* ===> forall (n : nat) (P : nat -> Prop), P n -> (forall m : nat, n <= m -> P m -> P (S m)) -> forall n0 : nat, n <= n0 -> P n0 *) (** Question: What is the relation between a formal proof of a proposition [P] and an informal proof of the same proposition [P]? Answer: The latter should _teach_ the reader how to produce the former. Question: How much detail is needed?? Unfortunately, there is no single right answer; rather, there is a range of choices. At one end of the spectrum, we can essentially give the reader the whole formal proof (i.e., the "informal" proof will amount to just transcribing the formal one into words). This may give the reader the ability to reproduce the formal one for themselves, but it probably doesn't _teach_ them anything much. At the other end of the spectrum, we can say "The theorem is true and you can figure out why for yourself if you think about it hard enough." This is also not a good teaching strategy, because often writing the proof requires one or more significant insights into the thing we're proving, and most readers will give up before they rediscover all the same insights as we did. In the middle is the golden mean -- a proof that includes all of the essential insights (saving the reader the hard work that we went through to find the proof in the first place) plus high-level suggestions for the more routine parts to save the reader from spending too much time reconstructing these (e.g., what the IH says and what must be shown in each case of an inductive proof), but not so much detail that the main ideas are obscured. Since we've spent much of this chapter looking "under the hood" at formal proofs by induction, now is a good moment to talk a little about _informal_ proofs by induction. In the real world of mathematical communication, written proofs range from extremely longwinded and pedantic to extremely brief and telegraphic. Although the ideal is somewhere in between, while one is getting used to the style it is better to start out at the pedantic end. Also, during the learning phase, it is probably helpful to have a clear standard to compare against. With this in mind, we offer two templates -- one for proofs by induction over _data_ (i.e., where the thing we're doing induction on lives in [Type]) and one for proofs by induction over _evidence_ (i.e., where the inductively defined thing lives in [Prop]). *) (** _Template_: - _Theorem_: <Universally quantified proposition of the form "For all [n:S], [P(n)]," where [S] is some inductively defined set.> _Proof_: By induction on [n]. <one case for each constructor [c] of [S]...> - Suppose [n = c a1 ... ak], where <...and here we state the IH for each of the [a]'s that has type [S], if any>. We must show <...and here we restate [P(c a1 ... ak)]>. <go on and prove [P(n)] to finish the case...> - <other cases similarly...> [] _Example_: - _Theorem_: For all sets [X], lists [l : list X], and numbers [n], if [length l = n] then [index (S n) l = None]. _Proof_: By induction on [l]. - Suppose [l = []]. We must show, for all numbers [n], that, if [length [] = n], then [index (S n) [] = None]. This follows immediately from the definition of [index]. - Suppose [l = x :: l'] for some [x] and [l'], where [length l' = n'] implies [index (S n') l' = None], for any number [n']. We must show, for all [n], that, if [length (x::l') = n] then [index (S n) (x::l') = None]. Let [n] be a number with [length l = n]. Since length l = length (x::l') = S (length l'), it suffices to show that index (S (length l')) l' = None. But this follows directly from the induction hypothesis, picking [n'] to be [length l']. [] *) (** Since inductively defined proof objects are often called "derivation trees," this form of proof is also known as _induction on derivations_. _Template_: - _Theorem_: <Proposition of the form "[Q -> P]," where [Q] is some inductively defined proposition (more generally, "For all [x] [y] [z], [Q x y z -> P x y z]")> _Proof_: By induction on a derivation of [Q]. <Or, more generally, "Suppose we are given [x], [y], and [z]. We show that [Q x y z] implies [P x y z], by induction on a derivation of [Q x y z]"...> <one case for each constructor [c] of [Q]...> - Suppose the final rule used to show [Q] is [c]. Then <...and here we state the types of all of the [a]'s together with any equalities that follow from the definition of the constructor and the IH for each of the [a]'s that has type [Q], if there are any>. We must show <...and here we restate [P]>. <go on and prove [P] to finish the case...> - <other cases similarly...> [] _Example_ - _Theorem_: The [<=] relation is transitive -- i.e., for all numbers [n], [m], and [o], if [n <= m] and [m <= o], then [n <= o]. _Proof_: By induction on a derivation of [m <= o]. - Suppose the final rule used to show [m <= o] is [le_n]. Then [m = o] and we must show that [n <= m], which is immediate by hypothesis. - Suppose the final rule used to show [m <= o] is [le_S]. Then [o = S o'] for some [o'] with [m <= o']. We must show that [n <= S o']. By induction hypothesis, [n <= o']. But then, by [le_S], [n <= S o']. [] *)
Inductive
sf-experiment
[ "Require Export ProofObjects" ]
sf-experiment/IndPrinciples.v
le
ev: nat -> Prop := | ev_0 : ev 0 | ev_SS : forall n : nat, ev n -> ev (S (S n)). (** This definition is different in one crucial respect from previous uses of [Inductive]: its result is not a [Type], but rather a function from [nat] to [Prop] -- that is, a property of numbers. Note that we've already seen other inductive definitions that result in functions, such as [list], whose type is [Type -> Type]. What is new here is that, because the [nat] argument of [ev] appears _unnamed_, to the _right_ of the colon, it is allowed to take different values in the types of different constructors: [0] in the type of [ev_0] and [S (S n)] in the type of [ev_SS]. In contrast, the definition of [list] names the [X] parameter _globally_, to the _left_ of the colon, forcing the result of [nil] and [cons] to be the same ([list X]). Had we tried to bring [nat] to the left in defining [ev], we would have seen an error: *) Fail Inductive wrong_ev (n : nat) : Prop := | wrong_ev_0 : wrong_ev 0 | wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)). (* ===> Error: A parameter of an inductive type n is not allowed to be used as a bound variable in the type of its constructor. *) (** ("Parameter" here is Coq jargon for an argument on the left of the colon in an [Inductive] definition; "index" is used to refer to arguments on the right of the colon.) *) (** We can think of the definition of [ev] as defining a Coq property [ev : nat -> Prop], together with theorems [ev_0 : ev 0] and [ev_SS : forall n, ev n -> ev (S (S n))]. Such "constructor theorems" have the same status as proven theorems. In particular, we can use Coq's [apply] tactic with the rule names to prove [ev] for particular numbers... *)
Inductive
sf-experiment
[ "Require Export Logic" ]
sf-experiment/IndProp.v
ev
ev_4: ev 4. Proof. apply ev_SS. apply ev_SS. apply ev_0. Qed.
Theorem
sf-experiment
[ "Require Export Logic" ]
sf-experiment/IndProp.v
ev_4
ev_4': ev 4. Proof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.
Theorem
sf-experiment
[ "Require Export Logic" ]
sf-experiment/IndProp.v
ev_4'
ev_plus4: forall n, ev n -> ev (4 + n). Proof. intros n. simpl. intros Hn. apply ev_SS. apply ev_SS. apply Hn. Qed.
Theorem
sf-experiment
[ "Require Export Logic" ]
sf-experiment/IndProp.v
ev_plus4
ev_double: forall n, ev (double n). Proof. (* FILL IN HERE *) Admitted. (** Besides _constructing_ evidence that numbers are even, we can also _reason about_ such evidence. Introducing [ev] with an [Inductive] declaration tells Coq not only that the constructors [ev_0] and [ev_SS] are valid ways to build evidence that some number is even, but also that these two constructors are the _only_ ways to build evidence that numbers are even (in the sense of [ev]). *) (** In other words, if someone gives us evidence [E] for the assertion [ev n], then we know that [E] must have one of two shapes: - [E] is [ev_0] (and [n] is [O]), or - [E] is [ev_SS n' E'] (and [n] is [S (S n')], where [E'] is evidence for [ev n']). *) (** This suggests that it should be possible to analyze a hypothesis of the form [ev n] much as we do inductively defined data structures; in particular, it should be possible to argue by _induction_ and _case analysis_ on such evidence. Let's look at a few examples to see what this means in practice. *) (** Suppose we are proving some fact involving a number [n], and we are given [ev n] as a hypothesis. We already know how to perform case analysis on [n] using the [inversion] tactic, generating separate subgoals for the case where [n = O] and the case where [n = S n'] for some [n']. But for some proofs we may instead want to analyze the evidence that [ev n] _directly_. By the definition of [ev], there are two cases to consider: - If the evidence is of the form [ev_0], we know that [n = 0]. - Otherwise, the evidence must have the form [ev_SS n' E'], where [n = S (S n')] and [E'] is evidence for [ev n']. *) (** We can perform this kind of reasoning in Coq, again using the [inversion] tactic. Besides allowing us to reason about equalities involving constructors, [inversion] provides a case-analysis principle for inductively defined propositions. When used in this way, its syntax is similar to [destruct]: We pass it a list of identifiers separated by [|] characters to name the arguments to each of the possible constructors. *)
Theorem
sf-experiment
[ "Require Export Logic" ]
sf-experiment/IndProp.v
ev_double
ev_minus2: forall n, ev n -> ev (pred (pred n)). Proof. intros n E. inversion E as [| n' E']. - (* E = ev_0 *) simpl. apply ev_0. - (* E = ev_SS n' E' *) simpl. apply E'. Qed. (** In words, here is how the inversion reasoning works in this proof: - If the evidence is of the form [ev_0], we know that [n = 0]. Therefore, it suffices to show that [ev (pred (pred 0))] holds. By the definition of [pred], this is equivalent to showing that [ev 0] holds, which directly follows from [ev_0]. - Otherwise, the evidence must have the form [ev_SS n' E'], where [n = S (S n')] and [E'] is evidence for [ev n']. We must then show that [ev (pred (pred (S (S n'))))] holds, which, after simplification, follows directly from [E']. *) (** This particular proof also works if we replace [inversion] by [destruct]: *)
Theorem
sf-experiment
[ "Require Export Logic" ]
sf-experiment/IndProp.v
ev_minus2