Commit b5b821de authored by Adam Chlipala's avatar Adam Chlipala

Pass over Subset

parent a39a0883
...@@ -993,7 +993,7 @@ Lemma substring_suffix_emp : forall s n m, ...@@ -993,7 +993,7 @@ Lemma substring_suffix_emp : forall s n m,
substring n m s = "" substring n m s = ""
-> m > 0 -> m > 0
-> n >= length s. -> n >= length s.
destruct m as [| m]; [crush | intros; apply substring_suffix_emp' with m; assumption]. destruct m as [ | m]; [crush | intros; apply substring_suffix_emp' with m; assumption].
Qed. Qed.
Hint Rewrite substring_stack substring_stack' substring_suffix Hint Rewrite substring_stack substring_stack' substring_suffix
......
(* Copyright (c) 2008, Adam Chlipala (* Copyright (c) 2008, 2011, Adam Chlipala
* *
* This work is licensed under a * This work is licensed under a
* Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
...@@ -51,7 +51,7 @@ Inductive maybe (A : Set) (P : A -> Prop) : Set := ...@@ -51,7 +51,7 @@ Inductive maybe (A : Set) (P : A -> Prop) : Set :=
Notation "{{ x | P }}" := (maybe (fun x => P)) : specif_scope. Notation "{{ x | P }}" := (maybe (fun x => P)) : specif_scope.
Notation "??" := (Unknown _) : specif_scope. Notation "??" := (Unknown _) : specif_scope.
Notation "[[ x ]]" := (Found _ x _) : specif_scope. Notation "[| x |]" := (Found _ x _) : specif_scope.
Notation "x <- e1 ; e2" := (match e1 with Notation "x <- e1 ; e2" := (match e1 with
| Unknown => ?? | Unknown => ??
...@@ -60,7 +60,7 @@ Notation "x <- e1 ; e2" := (match e1 with ...@@ -60,7 +60,7 @@ Notation "x <- e1 ; e2" := (match e1 with
(right associativity, at level 60) : specif_scope. (right associativity, at level 60) : specif_scope.
Notation "!!" := (inright _ _) : specif_scope. Notation "!!" := (inright _ _) : specif_scope.
Notation "[[[ x ]]]" := (inleft _ [x]) : specif_scope. Notation "[|| x ||]" := (inleft _ [x]) : specif_scope.
Notation "x <-- e1 ; e2" := (match e1 with Notation "x <-- e1 ; e2" := (match e1 with
| inright _ => !! | inright _ => !!
......
...@@ -20,7 +20,7 @@ Set Implicit Arguments. ...@@ -20,7 +20,7 @@ Set Implicit Arguments.
\chapter{Subset Types and Variations}% *) \chapter{Subset Types and Variations}% *)
(** So far, we have seen many examples of what we might call %``%#"#classical program verification.#"#%''% We write programs, write their specifications, and then prove that the programs satisfy their specifications. The programs that we have written in Coq have been normal functional programs that we could just as well have written in Haskell or ML. In this chapter, we start investigating uses of %\textit{%#<i>#dependent types#</i>#%}% to integrate programming, specification, and proving into a single phase. *) (** So far, we have seen many examples of what we might call %``%#"#classical program verification.#"#%''% We write programs, write their specifications, and then prove that the programs satisfy their specifications. The programs that we have written in Coq have been normal functional programs that we could just as well have written in Haskell or ML. In this chapter, we start investigating uses of %\index{dependent types}\textit{%#<i>#dependent types#</i>#%}% to integrate programming, specification, and proving into a single phase. The techniques we will learn make it possible to reduce the cost of program verification dramatically. *)
(** * Introducing Subset Types *) (** * Introducing Subset Types *)
...@@ -37,7 +37,7 @@ pred = fun n : nat => match n with ...@@ -37,7 +37,7 @@ pred = fun n : nat => match n with
]] ]]
We can use a new command, [Extraction], to produce an OCaml version of this function. *) We can use a new command, %\index{Vernacular commands!Extraction}\index{program extraction}\index{extraction|see{program extraction}}%[Extraction], to produce an %\index{OCaml}%OCaml version of this function. *)
Extraction pred. Extraction pred.
...@@ -92,20 +92,29 @@ Definition pred_strong1' (n : nat) (pf : n > 0) : nat := ...@@ -92,20 +92,29 @@ Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
| O => match zgtz pf with end | O => match zgtz pf with end
| S n' => n' | S n' => n'
end. end.
]]
<<
Error: In environment Error: In environment
n : nat n : nat
pf : n > 0 pf : n > 0
The term "pf" has type "n > 0" while it is expected to have type The term "pf" has type "n > 0" while it is expected to have type
"0 > 0" "0 > 0"
>>
]]
The term [zgtz pf] fails to type-check. Somehow the type checker has failed to take into account information that follows from which [match] branch that term appears in. The problem is that, by default, [match] does not let us use such implied information. To get refined typing, we must always rely on [match] annotations, either written explicitly or inferred. The term [zgtz pf] fails to type-check. Somehow the type checker has failed to take into account information that follows from which [match] branch that term appears in. The problem is that, by default, [match] does not let us use such implied information. To get refined typing, we must always rely on [match] annotations, either written explicitly or inferred.
In this case, we must use a [return] annotation to declare the relationship between the %\textit{%#<i>#value#</i>#%}% of the [match] discriminee and the %\textit{%#<i>#type#</i>#%}% of the result. There is no annotation that lets us declare a relationship between the discriminee and the type of a variable that is already in scope; hence, we delay the binding of [pf], so that we can use the [return] annotation to express the needed relationship. In this case, we must use a [return] annotation to declare the relationship between the %\textit{%#<i>#value#</i>#%}% of the [match] discriminee and the %\textit{%#<i>#type#</i>#%}% of the result. There is no annotation that lets us declare a relationship between the discriminee and the type of a variable that is already in scope; hence, we delay the binding of [pf], so that we can use the [return] annotation to express the needed relationship.
We are lucky that Coq's heuristics infer the [return] clause (specifically, [return n > 0 -> nat]) for us in this case. In general, however, the inference problem is undecidable. The known undecidable problem of %\textit{%#<i>#higher-order unification#</i>#%}% reduces to the [match] type inference problem. Over time, Coq is enhanced with more and more heuristics to get around this problem, but there must always exist [match]es whose types Coq cannot infer without annotations. We are lucky that Coq's heuristics infer the [return] clause (specifically, [return n > 0 -> nat]) for us in this case. *)
Definition pred_strong1' (n : nat) : n > 0 -> nat :=
match n return n > 0 -> nat with
| O => fun pf : 0 > 0 => match zgtz pf with end
| S n' => fun _ => n'
end.
(** By making explicit the functional relationship between value [n] and the result type of the [match], we guide Coq toward proper type checking. The clause for this example follows by simple copying of the original annotation on the definition. In general, however, the [match] annotation inference problem is undecidable. The known undecidable problem of %\index{higher-order unification}\textit{%#<i>#higher-order unification#</i>#%}~\cite{HOU}% reduces to the [match] type inference problem. Over time, Coq is enhanced with more and more heuristics to get around this problem, but there must always exist [match]es whose types Coq cannot infer without annotations.
Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *) Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)
...@@ -129,27 +138,23 @@ let pred_strong1 = function ...@@ -129,27 +138,23 @@ let pred_strong1 = function
(** The proof argument has disappeared! We get exactly the OCaml code we would have written manually. This is our first demonstration of the main technically interesting feature of Coq program extraction: program components of type [Prop] are erased systematically. (** The proof argument has disappeared! We get exactly the OCaml code we would have written manually. This is our first demonstration of the main technically interesting feature of Coq program extraction: program components of type [Prop] are erased systematically.
We can reimplement our dependently-typed [pred] based on %\textit{%#<i>#subset types#</i>#%}%, defined in the standard library with the type family [sig]. *) We can reimplement our dependently typed [pred] based on %\index{subset types}\textit{%#<i>#subset types#</i>#%}%, defined in the standard library with the type family %\index{Gallina terms!sig}%[sig]. *)
Print sig. Print sig.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
Inductive sig (A : Type) (P : A -> Prop) : Type := Inductive sig (A : Type) (P : A -> Prop) : Type :=
exist : forall x : A, P x -> sig P exist : forall x : A, P x -> sig P
For sig: Argument A is implicit
For exist: Argument A is implicit
]] ]]
[sig] is a Curry-Howard twin of [ex], except that [sig] is in [Type], while [ex] is in [Prop]. That means that [sig] values can survive extraction, while [ex] proofs will always be erased. The actual details of extraction of [sig]s are more subtle, as we will see shortly. The family [sig] is a Curry-Howard twin of [ex], except that [sig] is in [Type], while [ex] is in [Prop]. That means that [sig] values can survive extraction, while [ex] proofs will always be erased. The actual details of extraction of [sig]s are more subtle, as we will see shortly.
We rewrite [pred_strong1], using some syntactic sugar for subset types. *) We rewrite [pred_strong1], using some syntactic sugar for subset types. *)
Locate "{ _ : _ | _ }". Locate "{ _ : _ | _ }".
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
Notation Scope Notation
"{ x : A | P }" := sig (fun x : A => P) "{ x : A | P }" := sig (fun x : A => P)
: type_scope
(default interpretation)
]] ]]
*) *)
...@@ -159,13 +164,12 @@ Definition pred_strong2 (s : {n : nat | n > 0}) : nat := ...@@ -159,13 +164,12 @@ Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
| exist (S n') _ => n' | exist (S n') _ => n'
end. end.
(** To build a value of a subset type, we use the [exist] constructor, and the details of how to do that follow from the output of our earlier [Print sig] command. *) (** To build a value of a subset type, we use the [exist] constructor, and the details of how to do that follow from the output of our earlier [Print sig] command (where we elided the extra information that parameter [A] is implicit). *)
Eval compute in pred_strong2 (exist _ 2 two_gt0). Eval compute in pred_strong2 (exist _ 2 two_gt0).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= 1 = 1
: nat : nat
]] ]]
*) *)
...@@ -201,11 +205,10 @@ Eval compute in pred_strong3 (exist _ 2 two_gt0). ...@@ -201,11 +205,10 @@ Eval compute in pred_strong3 (exist _ 2 two_gt0).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= exist (fun m : nat => 2 = S m) 1 (refl_equal 2) = exist (fun m : nat => 2 = S m) 1 (refl_equal 2)
: {m : nat | proj1_sig (exist (lt 0) 2 two_gt0) = S m} : {m : nat | proj1_sig (exist (lt 0) 2 two_gt0) = S m}
]]
]]
*) *)
(** The function [proj1_sig] extracts the base value from a subset type. It turns out that we need to include an explicit [return] clause here, since Coq's heuristics are not smart enough to propagate the result type that we wrote earlier. (** The function %\index{Gallina terms!proj1\_sig}%[proj1_sig] extracts the base value from a subset type. It turns out that we need to include an explicit [return] clause here, since Coq's heuristics are not smart enough to propagate the result type that we wrote earlier.
By now, the reader is probably ready to believe that the new [pred_strong] leads to the same OCaml code as we have seen several times so far, and Coq does not disappoint. *) By now, the reader is probably ready to believe that the new [pred_strong] leads to the same OCaml code as we have seen several times so far, and Coq does not disappoint. *)
...@@ -227,7 +230,7 @@ let pred_strong3 = function ...@@ -227,7 +230,7 @@ let pred_strong3 = function
| S n' -> n' | S n' -> n'
</pre># </pre>#
We have managed to reach a type that is, in a formal sense, the most expressive possible for [pred]. Any other implementation of the same type must have the same input-output behavior. However, there is still room for improvement in making this kind of code easier to write. Here is a version that takes advantage of tactic-based theorem proving. We switch back to passing a separate proof argument instead of using a subset type for the function's input, because this leads to cleaner code. *) We have managed to reach a type that is, in a formal sense, the most expressive possible for [pred]. Any other implementation of the same type must have the same input-output behavior. However, there is still room for improvement in making this kind of code easier to write. Here is a version that takes advantage of tactic-based theorem proving. We switch back to passing a separate proof argument instead of using a subset type for the function's input, because this leads to cleaner code. (Recall that [False_rec] is the [Set]-level induction principle for [False], which can be used to produce a value in any [Set] given a proof of [False].) *)
Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}. Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.
refine (fun n => refine (fun n =>
...@@ -237,19 +240,21 @@ Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}. ...@@ -237,19 +240,21 @@ Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.
end). end).
(* begin thide *) (* begin thide *)
(** We build [pred_strong4] using tactic-based proving, beginning with a [Definition] command that ends in a period before a definition is given. Such a command enters the interactive proving mode, with the type given for the new identifier as our proof goal. We do most of the work with the [refine] tactic, to which we pass a partial %``%#"#proof#"#%''% of the type we are trying to prove. There may be some pieces left to fill in, indicated by underscores. Any underscore that Coq cannot reconstruct with type inference is added as a proof subgoal. In this case, we have two subgoals: (** We build [pred_strong4] using tactic-based proving, beginning with a [Definition] command that ends in a period before a definition is given. Such a command enters the interactive proving mode, with the type given for the new identifier as our proof goal. It may seem strange to change perspective so implicitly between programming and proving, but recall that programs and proofs are two sides of the same coin in Coq, thanks to the Curry-Howard correspondence.
We do most of the work with the %\index{tactics!refine}%[refine] tactic, to which we pass a partial %``%#"#proof#"#%''% of the type we are trying to prove. There may be some pieces left to fill in, indicated by underscores. Any underscore that Coq cannot reconstruct with type inference is added as a proof subgoal. In this case, we have two subgoals:
[[ %\vspace{.1in} \noindent 2 \coqdockw{subgoals}\vspace{-.1in}%#<tt>2 subgoals</tt>#
2 subgoals [[
n : nat n : nat
_ : 0 > 0 _ : 0 > 0
============================ ============================
False False
]]
subgoal 2 is: %\noindent \coqdockw{subgoal} 2 \coqdockw{is}:%#<tt>subgoal 2 is</tt>#
[[
S n' = S n' S n' = S n'
]] ]]
We can see that the first subgoal comes from the second underscore passed to [False_rec], and the second subgoal comes from the second underscore passed to [exist]. In the first case, we see that, though we bound the proof variable with an underscore, it is still available in our proof context. It is hard to refer to underscore-named variables in manual proofs, but automation makes short work of them. Both subgoals are easy to discharge that way, so let us back up and ask to prove all subgoals automatically. *) We can see that the first subgoal comes from the second underscore passed to [False_rec], and the second subgoal comes from the second underscore passed to [exist]. In the first case, we see that, though we bound the proof variable with an underscore, it is still available in our proof context. It is hard to refer to underscore-named variables in manual proofs, but automation makes short work of them. Both subgoals are easy to discharge that way, so let us back up and ask to prove all subgoals automatically. *)
...@@ -263,7 +268,7 @@ We can see that the first subgoal comes from the second underscore passed to [Fa ...@@ -263,7 +268,7 @@ We can see that the first subgoal comes from the second underscore passed to [Fa
(* end thide *) (* end thide *)
Defined. Defined.
(** We end the %``%#"#proof#"#%''% with [Defined] instead of [Qed], so that the definition we constructed remains visible. This contrasts to the case of ending a proof with [Qed], where the details of the proof are hidden afterward. Let us see what our proof script constructed. *) (** We end the %``%#"#proof#"#%''% with %\index{Vernacular commands!Defined}%[Defined] instead of [Qed], so that the definition we constructed remains visible. This contrasts to the case of ending a proof with [Qed], where the details of the proof are hidden afterward. (More formally, [Defined] marks an identifier as %\index{transparent}\emph{%#<i>#transparent#</i>#%}%, allowing it to be unfolded; while [Qed] marks an identifier as %\index{opaque}\emph{%#<i>#opaque#</i>#%}%, preventing unfolding.) Let us see what our proof script constructed. *)
Print pred_strong4. Print pred_strong4.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
...@@ -291,10 +296,37 @@ Eval compute in pred_strong4 two_gt0. ...@@ -291,10 +296,37 @@ Eval compute in pred_strong4 two_gt0.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= exist (fun m : nat => 2 = S m) 1 (refl_equal 2) = exist (fun m : nat => 2 = S m) 1 (refl_equal 2)
: {m : nat | 2 = S m} : {m : nat | 2 = S m}
]] ]]
We are almost done with the ideal implementation of dependent predecessor. We can use Coq's syntax extension facility to arrive at code with almost no complexity beyond a Haskell or ML program with a complete specification in a comment. *) A tactic modifier called %\index{tactics!abstract}%[abstract] can be helpful for producing shorter terms, by automatically abstracting subgoals into named lemmas. *)
(* begin thide *)
Definition pred_strong4' : forall n : nat, n > 0 -> {m : nat | n = S m}.
refine (fun n =>
match n with
| O => fun _ => False_rec _ _
| S n' => fun _ => exist _ n' _
end); abstract crush.
Defined.
Print pred_strong4'.
(* end thide *)
(** %\vspace{-.15in}% [[
pred_strong4' =
fun n : nat =>
match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
| 0 =>
fun _H : 0 > 0 =>
False_rec {m : nat | 0 = S m} (pred_strong4'_subproof n _H)
| S n' =>
fun _H : S n' > 0 =>
exist (fun m : nat => S n' = S m) n' (pred_strong4'_subproof0 n _H)
end
: forall n : nat, n > 0 -> {m : nat | n = S m}
]]
We are almost done with the ideal implementation of dependent predecessor. We can use Coq's syntax extension facility to arrive at code with almost no complexity beyond a Haskell or ML program with a complete specification in a comment. *)
Notation "!" := (False_rec _ _). Notation "!" := (False_rec _ _).
Notation "[ e ]" := (exist _ e _). Notation "[ e ]" := (exist _ e _).
...@@ -313,10 +345,9 @@ Eval compute in pred_strong5 two_gt0. ...@@ -313,10 +345,9 @@ Eval compute in pred_strong5 two_gt0.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [1] = [1]
: {m : nat | 2 = S m} : {m : nat | 2 = S m}
]] ]]
One other alternative is worth demonstrating. Recent Coq versions include a facility called [Program] that streamlines this style of definition. Here is a complete implementation using [Program]. *) One other alternative is worth demonstrating. Recent Coq versions include a facility called %\index{Program}%[Program] that streamlines this style of definition. Here is a complete implementation using [Program].%\index{Vernacular commands!Obligation Tactic}\index{Vernacular commands!Program Definition}% *)
Obligation Tactic := crush. Obligation Tactic := crush.
...@@ -326,28 +357,25 @@ Program Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} := ...@@ -326,28 +357,25 @@ Program Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} :=
| S n' => n' | S n' => n'
end. end.
(** Printing the resulting definition of [pred_strong6] yields a term very similar to what we built with [refine]. [Program] can save time in writing programs that use subset types. Nonetheless, [refine] is often just as effective, and [refine] gives you more control over the form the final term takes, which can be useful when you want to prove additional theorems about your definition. [Program] will sometimes insert type casts that can complicate theorem-proving. *) (** Printing the resulting definition of [pred_strong6] yields a term very similar to what we built with [refine]. [Program] can save time in writing programs that use subset types. Nonetheless, [refine] is often just as effective, and [refine] gives you more control over the form the final term takes, which can be useful when you want to prove additional theorems about your definition. [Program] will sometimes insert type casts that can complicate theorem proving. *)
Eval compute in pred_strong6 two_gt0. Eval compute in pred_strong6 two_gt0.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [1] = [1]
: {m : nat | 2 = S m} : {m : nat | 2 = S m}
]] ]]
*)
In this case, we see that the new definition yields the same computational behavior as before. *)
(** * Decidable Proposition Types *) (** * Decidable Proposition Types *)
(** There is another type in the standard library which captures the idea of program values that indicate which of two propositions is true. *) (** There is another type in the standard library which captures the idea of program values that indicate which of two propositions is true.%\index{Gallina terms!sumbool}% *)
Print sumbool. Print sumbool.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
Inductive sumbool (A : Prop) (B : Prop) : Set := Inductive sumbool (A : Prop) (B : Prop) : Set :=
left : A -> {A} + {B} | right : B -> {A} + {B} left : A -> {A} + {B} | right : B -> {A} + {B}
For left: Argument A is implicit
For right: Argument B is implicit
]] ]]
We can define some notations to make working with [sumbool] more convenient. *) We can define some notations to make working with [sumbool] more convenient. *)
...@@ -373,7 +401,6 @@ Eval compute in eq_nat_dec 2 2. ...@@ -373,7 +401,6 @@ Eval compute in eq_nat_dec 2 2.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= Yes = Yes
: {2 = 2} + {2 <> 2} : {2 = 2} + {2 <> 2}
]] ]]
*) *)
...@@ -381,11 +408,12 @@ Eval compute in eq_nat_dec 2 3. ...@@ -381,11 +408,12 @@ Eval compute in eq_nat_dec 2 3.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= No = No
: {2 = 2} + {2 <> 2} : {2 = 2} + {2 <> 2}
]] ]]
*) *)
(** Our definition extracts to reasonable OCaml code. *) (** Note that the [Yes] and [No] notations are hiding proofs establishing the correctness of the outputs.
Our definition extracts to reasonable OCaml code. *)
Extraction eq_nat_dec. Extraction eq_nat_dec.
...@@ -415,13 +443,13 @@ let rec eq_nat_dec n m = ...@@ -415,13 +443,13 @@ let rec eq_nat_dec n m =
| S m' -> eq_nat_dec n' m') | S m' -> eq_nat_dec n' m')
</pre># </pre>#
Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it. *) Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it.%\index{tactics!decide equality}% *)
Definition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}. Definition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.
decide equality. decide equality.
Defined. Defined.
(** Curious readers can verify that the [decide equality] version extracts to the same OCaml code as our more manual version does. That OCaml code had one undesirable property, which is that it uses %\texttt{%#<tt>#Left#</tt>#%}% and %\texttt{%#<tt>#Right#</tt>#%}% constructors instead of the boolean values built into OCaml. We can fix this, by using Coq's facility for mapping Coq inductive types to OCaml variant types. *) (** Curious readers can verify that the [decide equality] version extracts to the same OCaml code as our more manual version does. That OCaml code had one undesirable property, which is that it uses %\texttt{%#<tt>#Left#</tt>#%}% and %\texttt{%#<tt>#Right#</tt>#%}% constructors instead of the boolean values built into OCaml. We can fix this, by using Coq's facility for mapping Coq inductive types to OCaml variant types.%\index{Vernacular commands!Extract Inductive}% *)
Extract Inductive sumbool => "bool" ["true" "false"]. Extract Inductive sumbool => "bool" ["true" "false"].
Extraction eq_nat_dec'. Extraction eq_nat_dec'.
...@@ -480,7 +508,6 @@ Eval compute in In_dec eq_nat_dec 2 (1 :: 2 :: nil). ...@@ -480,7 +508,6 @@ Eval compute in In_dec eq_nat_dec 2 (1 :: 2 :: nil).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= Yes = Yes
: {In 2 (1 :: 2 :: nil)} + {~ In 2 (1 :: 2 :: nil)} : {In 2 (1 :: 2 :: nil)} + {~ In 2 (1 :: 2 :: nil)}
]] ]]
*) *)
...@@ -488,7 +515,6 @@ Eval compute in In_dec eq_nat_dec 3 (1 :: 2 :: nil). ...@@ -488,7 +515,6 @@ Eval compute in In_dec eq_nat_dec 3 (1 :: 2 :: nil).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= No = No
: {In 3 (1 :: 2 :: nil)} + {~ In 3 (1 :: 2 :: nil)} : {In 3 (1 :: 2 :: nil)} + {~ In 3 (1 :: 2 :: nil)}
]] ]]
*) *)
...@@ -522,7 +548,7 @@ let rec in_dec a_eq_dec x = function ...@@ -522,7 +548,7 @@ let rec in_dec a_eq_dec x = function
(** * Partial Subset Types *) (** * Partial Subset Types *)
(** Our final implementation of dependent predecessor used a very specific argument type to ensure that execution could always complete normally. Sometimes we want to allow execution to fail, and we want a more principled way of signaling that than returning a default value, as [pred] does for [0]. One approach is to define this type family [maybe], which is a version of [sig] that allows obligation-free failure. *) (** Our final implementation of dependent predecessor used a very specific argument type to ensure that execution could always complete normally. Sometimes we want to allow execution to fail, and we want a more principled way of signaling failure than returning a default value, as [pred] does for [0]. One approach is to define this type family %\index{Gallina terms!maybe}%[maybe], which is a version of [sig] that allows obligation-free failure. *)
Inductive maybe (A : Set) (P : A -> Prop) : Set := Inductive maybe (A : Set) (P : A -> Prop) : Set :=
| Unknown : maybe P | Unknown : maybe P
...@@ -532,7 +558,7 @@ Inductive maybe (A : Set) (P : A -> Prop) : Set := ...@@ -532,7 +558,7 @@ Inductive maybe (A : Set) (P : A -> Prop) : Set :=
Notation "{{ x | P }}" := (maybe (fun x => P)). Notation "{{ x | P }}" := (maybe (fun x => P)).
Notation "??" := (Unknown _). Notation "??" := (Unknown _).
Notation "[[ x ]]" := (Found _ x _). Notation "[| x |]" := (Found _ x _).
(** Now our next version of [pred] is trivial to write. *) (** Now our next version of [pred] is trivial to write. *)
...@@ -540,56 +566,51 @@ Definition pred_strong7 : forall n : nat, {{m | n = S m}}. ...@@ -540,56 +566,51 @@ Definition pred_strong7 : forall n : nat, {{m | n = S m}}.
refine (fun n => refine (fun n =>
match n with match n with
| O => ?? | O => ??
| S n' => [[n']] | S n' => [|n'|]
end); trivial. end); trivial.
Defined. Defined.
Eval compute in pred_strong7 2. Eval compute in pred_strong7 2.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [[1]] = [|1|]
: {{m | 2 = S m}} : {{m | 2 = S m}}
]]
]]
*) *)
Eval compute in pred_strong7 0. Eval compute in pred_strong7 0.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= ?? = ??
: {{m | 0 = S m}} : {{m | 0 = S m}}
]] ]]
Because we used [maybe], one valid implementation of the type we gave [pred_strong7] would return [??] in every case. We can strengthen the type to rule out such vacuous implementations, and the type family [sumor] from the standard library provides the easiest starting point. For type [A] and proposition [B], [A + {B}] desugars to [sumor A B], whose values are either values of [A] or proofs of [B]. *) Because we used [maybe], one valid implementation of the type we gave [pred_strong7] would return [??] in every case. We can strengthen the type to rule out such vacuous implementations, and the type family %\index{Gallina terms!sumor}%[sumor] from the standard library provides the easiest starting point. For type [A] and proposition [B], [A + {B}] desugars to [sumor A B], whose values are either values of [A] or proofs of [B]. *)
Print sumor. Print sumor.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
Inductive sumor (A : Type) (B : Prop) : Type := Inductive sumor (A : Type) (B : Prop) : Type :=
inleft : A -> A + {B} | inright : B -> A + {B} inleft : A -> A + {B} | inright : B -> A + {B}
For inleft: Argument A is implicit
For inright: Argument B is implicit
]] ]]
*) *)
(** We add notations for easy use of the [sumor] constructors. The second notation is specialized to [sumor]s whose [A] parameters are instantiated with regular subset types, since this is how we will use [sumor] below. *) (** We add notations for easy use of the [sumor] constructors. The second notation is specialized to [sumor]s whose [A] parameters are instantiated with regular subset types, since this is how we will use [sumor] below. *)
Notation "!!" := (inright _ _). Notation "!!" := (inright _ _).
Notation "[[[ x ]]]" := (inleft _ [x]). Notation "[|| x ||]" := (inleft _ [x]).
(** Now we are ready to give the final version of possibly-failing predecessor. The [sumor]-based type that we use is maximally expressive; any implementation of the type has the same input-output behavior. *) (** Now we are ready to give the final version of possibly failing predecessor. The [sumor]-based type that we use is maximally expressive; any implementation of the type has the same input-output behavior. *)
Definition pred_strong8 : forall n : nat, {m : nat | n = S m} + {n = 0}. Definition pred_strong8 : forall n : nat, {m : nat | n = S m} + {n = 0}.
refine (fun n => refine (fun n =>
match n with match n with
| O => !! | O => !!
| S n' => [[[n']]] | S n' => [||n'||]
end); trivial. end); trivial.
Defined. Defined.
Eval compute in pred_strong8 2. Eval compute in pred_strong8 2.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [[[1]]] = [||1||]
: {m : nat | 2 = S m} + {2 = 0} : {m : nat | 2 = S m} + {2 = 0}
]] ]]
*) *)
...@@ -597,14 +618,15 @@ Eval compute in pred_strong8 0. ...@@ -597,14 +618,15 @@ Eval compute in pred_strong8 0.
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= !! = !!
: {m : nat | 0 = S m} + {0 = 0} : {m : nat | 0 = S m} + {0 = 0}
]] ]]
*) *)
(** As with our other maximally expressive [pred] function, we arrive at quite simple output values, thanks to notations. *)
(** * Monadic Notations *) (** * Monadic Notations *)
(** We can treat [maybe] like a monad, in the same way that the Haskell [Maybe] type is interpreted as a failure monad. Our [maybe] has the wrong type to be a literal monad, but a %``%#"#bind#"#%''%-like notation will still be helpful. *) (** We can treat [maybe] like a monad%~\cite{Monads}\index{monad}\index{failure monad}%, in the same way that the Haskell [Maybe] type is interpreted as a failure monad. Our [maybe] has the wrong type to be a literal monad, but a %``%#"#bind#"#%''%-like notation will still be helpful. *)
Notation "x <- e1 ; e2" := (match e1 with Notation "x <- e1 ; e2" := (match e1 with
| Unknown => ?? | Unknown => ??
...@@ -614,13 +636,13 @@ Notation "x <- e1 ; e2" := (match e1 with ...@@ -614,13 +636,13 @@ Notation "x <- e1 ; e2" := (match e1 with
(** The meaning of [x <- e1; e2] is: First run [e1]. If it fails to find an answer, then announce failure for our derived computation, too. If [e1] %\textit{%#<i>#does#</i>#%}% find an answer, pass that answer on to [e2] to find the final result. The variable [x] can be considered bound in [e2]. (** The meaning of [x <- e1; e2] is: First run [e1]. If it fails to find an answer, then announce failure for our derived computation, too. If [e1] %\textit{%#<i>#does#</i>#%}% find an answer, pass that answer on to [e2] to find the final result. The variable [x] can be considered bound in [e2].
This notation is very helpful for composing richly-typed procedures. For instance, here is a very simple implementation of a function to take the predecessors of two naturals at once. *) This notation is very helpful for composing richly typed procedures. For instance, here is a very simple implementation of a function to take the predecessors of two naturals at once. *)
Definition doublePred : forall n1 n2 : nat, {{p | n1 = S (fst p) /\ n2 = S (snd p)}}. Definition doublePred : forall n1 n2 : nat, {{p | n1 = S (fst p) /\ n2 = S (snd p)}}.
refine (fun n1 n2 => refine (fun n1 n2 =>
m1 <- pred_strong7 n1; m1 <- pred_strong7 n1;
m2 <- pred_strong7 n2; m2 <- pred_strong7 n2;
[[(m1, m2)]]); tauto. [|(m1, m2)|]); tauto.
Defined. Defined.
(** We can build a [sumor] version of the %``%#"#bind#"#%''% notation and use it to write a similarly straightforward version of this function. *) (** We can build a [sumor] version of the %``%#"#bind#"#%''% notation and use it to write a similarly straightforward version of this function. *)
...@@ -641,13 +663,13 @@ Definition doublePred' : forall n1 n2 : nat, ...@@ -641,13 +663,13 @@ Definition doublePred' : forall n1 n2 : nat,
refine (fun n1 n2 => refine (fun n1 n2 =>
m1 <-- pred_strong8 n1; m1 <-- pred_strong8 n1;
m2 <-- pred_strong8 n2; m2 <-- pred_strong8 n2;
[[[(m1, m2)]]]); tauto. [||(m1, m2)||]); tauto.
Defined. Defined.
(** * A Type-Checking Example *) (** * A Type-Checking Example *)
(** We can apply these specification types to build a certified type-checker for a simple expression language. *) (** We can apply these specification types to build a certified type checker for a simple expression language. *)
Inductive exp : Set := Inductive exp : Set :=
| Nat : nat -> exp | Nat : nat -> exp
...@@ -685,7 +707,7 @@ Defined. ...@@ -685,7 +707,7 @@ Defined.
Notation "e1 ;; e2" := (if e1 then e2 else ??) Notation "e1 ;; e2" := (if e1 then e2 else ??)
(right associativity, at level 60). (right associativity, at level 60).
(** With that notation defined, we can implement a [typeCheck] function, whose code is only more complex than what we would write in ML because it needs to include some extra type annotations. Every [[[e]]] expression adds a [hasType] proof obligation, and [crush] makes short work of them when we add [hasType]'s constructors as hints. *) (** With that notation defined, we can implement a [typeCheck] function, whose code is only more complex than what we would write in ML because it needs to include some extra type annotations. Every [[|e|]] expression adds a [hasType] proof obligation, and [crush] makes short work of them when we add [hasType]'s constructors as hints. *)
(* end thide *) (* end thide *)
Definition typeCheck : forall e : exp, {{t | hasType e t}}. Definition typeCheck : forall e : exp, {{t | hasType e t}}.
...@@ -694,20 +716,20 @@ Definition typeCheck : forall e : exp, {{t | hasType e t}}. ...@@ -694,20 +716,20 @@ Definition typeCheck : forall e : exp, {{t | hasType e t}}.
refine (fix F (e : exp) : {{t | hasType e t}} := refine (fix F (e : exp) : {{t | hasType e t}} :=
match e with match e with
| Nat _ => [[TNat]] | Nat _ => [|TNat|]
| Plus e1 e2 => | Plus e1 e2 =>
t1 <- F e1; t1 <- F e1;
t2 <- F e2; t2 <- F e2;
eq_type_dec t1 TNat;; eq_type_dec t1 TNat;;
eq_type_dec t2 TNat;; eq_type_dec t2 TNat;;
[[TNat]] [|TNat|]
| Bool _ => [[TBool]] | Bool _ => [|TBool|]
| And e1 e2 => | And e1 e2 =>
t1 <- F e1; t1 <- F e1;
t2 <- F e2; t2 <- F e2;
eq_type_dec t1 TBool;; eq_type_dec t1 TBool;;
eq_type_dec t2 TBool;; eq_type_dec t2 TBool;;
[[TBool]] [|TBool|]
end); crush. end); crush.
(* end thide *) (* end thide *)
Defined. Defined.
...@@ -716,14 +738,14 @@ Defined. ...@@ -716,14 +738,14 @@ Defined.
Eval simpl in typeCheck (Nat 0). Eval simpl in typeCheck (Nat 0).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [[TNat]] = [|TNat|]
: {{t | hasType (Nat 0) t}} : {{t | hasType (Nat 0) t}}
]] ]]
*) *)
Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)). Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [[TNat]] = [|TNat|]
: {{t | hasType (Plus (Nat 1) (Nat 2)) t}} : {{t | hasType (Plus (Nat 1) (Nat 2)) t}}
]] ]]
*) *)
...@@ -735,7 +757,7 @@ Eval simpl in typeCheck (Plus (Nat 1) (Bool false)). ...@@ -735,7 +757,7 @@ Eval simpl in typeCheck (Plus (Nat 1) (Bool false)).
]] ]]
*) *)
(** The type-checker also extracts to some reasonable OCaml code. *) (** The type checker also extracts to some reasonable OCaml code. *)
Extraction typeCheck. Extraction typeCheck.
...@@ -819,14 +841,15 @@ Notation "e1 ;;; e2" := (if e1 then e2 else !!) ...@@ -819,14 +841,15 @@ Notation "e1 ;;; e2" := (if e1 then e2 else !!)
Lemma hasType_det : forall e t1, Lemma hasType_det : forall e t1,
hasType e t1 hasType e t1
-> forall t2, -> forall t2, hasType e t2
hasType e t2
-> t1 = t2. -> t1 = t2.
induction 1; inversion 1; crush. induction 1; inversion 1; crush.
Qed. Qed.
(** Now we can define the type-checker. Its type expresses that it only fails on untypable expressions. *) (** Now we can define the type-checker. Its type expresses that it only fails on untypable expressions. *)
(** printing <-- $\longleftarrow$ *)
(* end thide *) (* end thide *)
Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ hasType e t}. Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ hasType e t}.
(* begin thide *) (* begin thide *)
...@@ -834,29 +857,29 @@ Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ ...@@ -834,29 +857,29 @@ Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~
(** We register all of the typing rules as hints. *) (** We register all of the typing rules as hints. *)
Hint Resolve hasType_det. Hint Resolve hasType_det.
(** [hasType_det] will also be useful for proving proof obligations with contradictory contexts. Since its statement includes [forall]-bound variables that do not appear in its conclusion, only [eauto] will apply this hint. *) (** The lemma [hasType_det] will also be useful for proving proof obligations with contradictory contexts. Since its statement includes [forall]-bound variables that do not appear in its conclusion, only [eauto] will apply this hint. *)
(** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *) (** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *)
refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t} := refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t} :=
match e with match e with
| Nat _ => [[[TNat]]] | Nat _ => [||TNat||]
| Plus e1 e2 => | Plus e1 e2 =>
t1 <-- F e1; t1 <-- F e1;
t2 <-- F e2; t2 <-- F e2;
eq_type_dec t1 TNat;;; eq_type_dec t1 TNat;;;
eq_type_dec t2 TNat;;; eq_type_dec t2 TNat;;;
[[[TNat]]] [||TNat||]
| Bool _ => [[[TBool]]] | Bool _ => [||TBool||]
| And e1 e2 => | And e1 e2 =>
t1 <-- F e1; t1 <-- F e1;
t2 <-- F e2; t2 <-- F e2;
eq_type_dec t1 TBool;;; eq_type_dec t1 TBool;;;
eq_type_dec t2 TBool;;; eq_type_dec t2 TBool;;;
[[[TBool]]] [||TBool||]
end); clear F; crush' tt hasType; eauto. end); clear F; crush' tt hasType; eauto.
(** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make. The [crush] variant [crush'] helps us by performing automatic inversion on instances of the predicates specified in its second argument. Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *) (** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make. The [crush] variant %\index{tactics!crush'}%[crush'] helps us by performing automatic inversion on instances of the predicates specified in its second argument. Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *)
(* end thide *) (* end thide *)
...@@ -864,11 +887,11 @@ Defined. ...@@ -864,11 +887,11 @@ Defined.
(** The short implementation here hides just how time-saving automation is. Every use of one of the notations adds a proof obligation, giving us 12 in total. Most of these obligations require multiple inversions and either uses of [hasType_det] or applications of [hasType] rules. (** The short implementation here hides just how time-saving automation is. Every use of one of the notations adds a proof obligation, giving us 12 in total. Most of these obligations require multiple inversions and either uses of [hasType_det] or applications of [hasType] rules.
The results of simplifying calls to [typeCheck'] look deceptively similar to the results for [typeCheck], but now the types of the results provide more information. *) Our new function remains easy to test: *)
Eval simpl in typeCheck' (Nat 0). Eval simpl in typeCheck' (Nat 0).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [[[TNat]]] = [||TNat||]
: {t : type | hasType (Nat 0) t} + : {t : type | hasType (Nat 0) t} +
{(forall t : type, ~ hasType (Nat 0) t)} {(forall t : type, ~ hasType (Nat 0) t)}
]] ]]
...@@ -876,7 +899,7 @@ Eval simpl in typeCheck' (Nat 0). ...@@ -876,7 +899,7 @@ Eval simpl in typeCheck' (Nat 0).
Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)). Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).
(** %\vspace{-.15in}% [[ (** %\vspace{-.15in}% [[
= [[[TNat]]] = [||TNat||]
: {t : type | hasType (Plus (Nat 1) (Nat 2)) t} + : {t : type | hasType (Plus (Nat 1) (Nat 2)) t} +
{(forall t : type, ~ hasType (Plus (Nat 1) (Nat 2)) t)} {(forall t : type, ~ hasType (Plus (Nat 1) (Nat 2)) t)}
]] ]]
...@@ -888,7 +911,8 @@ Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)). ...@@ -888,7 +911,8 @@ Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)).
: {t : type | hasType (Plus (Nat 1) (Bool false)) t} + : {t : type | hasType (Plus (Nat 1) (Bool false)) t} +
{(forall t : type, ~ hasType (Plus (Nat 1) (Bool false)) t)} {(forall t : type, ~ hasType (Plus (Nat 1) (Bool false)) t)}
]] ]]
*)
The results of simplifying calls to [typeCheck'] look deceptively similar to the results for [typeCheck], but now the types of the results provide more information. *)
(** * Exercises *) (** * Exercises *)
...@@ -903,8 +927,8 @@ Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)). ...@@ -903,8 +927,8 @@ Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)).
%\item%#<li># Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction.#</li># %\item%#<li># Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction.#</li>#
%\item%#<li># Define a function [propDenote] from variable truth assignments and [prop]s to [Prop], based on the usual meanings of the connectives. Represent truth assignments as functions from [var] to [bool].#</li># %\item%#<li># Define a function [propDenote] from variable truth assignments and [prop]s to [Prop], based on the usual meanings of the connectives. Represent truth assignments as functions from [var] to [bool].#</li>#
%\item%#<li># Define a function [bool_true_dec] that checks whether a boolean is true, with a maximally expressive dependent type. That is, the function should have type [forall b, {b = true} + {b = true -> False}]. #</li># %\item%#<li># Define a function [bool_true_dec] that checks whether a boolean is true, with a maximally expressive dependent type. That is, the function should have type [forall b, {b = true} + {b = true -> False}]. #</li>#
%\item%#<li># Define a function [decide] that determines whether a particular [prop] is true under a particular truth assignment. That is, the function should have type [forall (truth : var -> bool) (p : prop), {propDenote truth p} + {~ propDenote truth p}]. This function is probably easiest to write in the usual tactical style, instead of programming with [refine]. [bool_true_dec] may come in handy as a hint.#</li># %\item%#<li># Define a function [decide] that determines whether a particular [prop] is true under a particular truth assignment. That is, the function should have type [forall (truth : var -> bool) (p : prop), {propDenote truth p} + {~ propDenote truth p}]. This function is probably easiest to write in the usual tactical style, instead of programming with [refine]. The function [bool_true_dec] may come in handy as a hint.#</li>#
%\item%#<li># Define a function [negate] that returns a simplified version of the negation of a [prop]. That is, the function should have type [forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}]. To simplify a variable, just negate it. Simplify a negation by returning its argument. Simplify conjunctions and disjunctions using De Morgan's laws, negating the arguments recursively and switching the kind of connective. [decide] may be useful in some of the proof obligations, even if you do not use it in the computational part of [negate]'s definition. Lemmas like [decide] allow us to compensate for the lack of a general Law of the Excluded Middle in CIC.#</li># %\item%#<li># Define a function [negate] that returns a simplified version of the negation of a [prop]. That is, the function should have type [forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}]. To simplify a variable, just negate it. Simplify a negation by returning its argument. Simplify conjunctions and disjunctions using De Morgan's laws, negating the arguments recursively and switching the kind of connective. Your [decide] function may be useful in some of the proof obligations, even if you do not use it in the computational part of [negate]'s definition. Lemmas like [decide] allow us to compensate for the lack of a general Law of the Excluded Middle in CIC.#</li>#
#</ol>#%\end{enumerate}% #</li># #</ol>#%\end{enumerate}% #</li>#
%\item%#<li># Implement the DPLL satisfiability decision procedure for boolean formulas in conjunctive normal form, with a dependent type that guarantees its correctness. An example of a reasonable type for this function would be [forall f : formula, {truth : tvals | formulaTrue truth f} + {forall truth, ~ formulaTrue truth f}]. Implement at least %``%#"#the basic backtracking algorithm#"#%''% as defined here: %\item%#<li># Implement the DPLL satisfiability decision procedure for boolean formulas in conjunctive normal form, with a dependent type that guarantees its correctness. An example of a reasonable type for this function would be [forall f : formula, {truth : tvals | formulaTrue truth f} + {forall truth, ~ formulaTrue truth f}]. Implement at least %``%#"#the basic backtracking algorithm#"#%''% as defined here:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment