coq with classes

93
Coq with Classes Matthieu Sozeau Currently at the IAS, Princeton Project Team πr 2 INRIA Rocquencourt & PPS, Paris 7 University Advanced Martial Arts in Coq October 8th 2012 University of Pennsylvania, Philadelphia, USA

Upload: others

Post on 29-Oct-2021

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Coq with Classes

Coq with ClassesMatthieu SozeauCurrently at the IAS, Princeton

Project Team πr2

INRIA Rocquencourt &

PPS, Paris 7 University

Advanced Martial Arts in CoqOctober 8th 2012University of Pennsylvania, Philadelphia,USA

Page 2: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 2

Page 3: Coq with Classes

Goal

Enhancing type inference through overloading:

I For generic programming with interfaces rather than concreteimplementations. Akin to a first-class module system.

I For generic proof scripts: refer to proofs by semantic conceptrather than name. E.g. reflexivity of R instead ofR refl. Proofs may be found using arbitrary search.

In general, allows inference of arbitrary additional structure on agiven type or value.

Matthieu Sozeau - Coq with Classes 3

Page 4: Coq with Classes

Solutions for overloading

Context:

I Modularity: separate definitions of the specializations.

I Constrained by Coq: a fixed kernel language!

Existing paradigms:

I Intersection types: closed overloading by declaring multiplesignatures for a single constant (e.g. CDuce, Stardust).

I Bounded quantification and class-based overloading.Overloading circumscribed by a subtyping relation (e.g.structural subtyping a la OCaml, nominal subtyping inJava).

Solution:

Elaborate Type Classes, a kind of bounded quantificationwhere the subtyping relation needs not be internalized.

Matthieu Sozeau - Coq with Classes 4

Page 5: Coq with Classes

Solutions for overloading

Context:

I Modularity: separate definitions of the specializations.

I Constrained by Coq: a fixed kernel language!

Existing paradigms:

I Intersection types: closed overloading by declaring multiplesignatures for a single constant (e.g. CDuce, Stardust).

I Bounded quantification and class-based overloading.Overloading circumscribed by a subtyping relation (e.g.structural subtyping a la OCaml, nominal subtyping inJava).

Solution:

Elaborate Type Classes, a kind of bounded quantificationwhere the subtyping relation needs not be internalized.

Matthieu Sozeau - Coq with Classes 4

Page 6: Coq with Classes

Solutions for overloading

Context:

I Modularity: separate definitions of the specializations.

I Constrained by Coq: a fixed kernel language!

Existing paradigms:

I Intersection types: closed overloading by declaring multiplesignatures for a single constant (e.g. CDuce, Stardust).

I Bounded quantification and class-based overloading.Overloading circumscribed by a subtyping relation (e.g.structural subtyping a la OCaml, nominal subtyping inJava).

Solution:

Elaborate Type Classes, a kind of bounded quantificationwhere the subtyping relation needs not be internalized.

Matthieu Sozeau - Coq with Classes 4

Page 7: Coq with Classes

Making ad-hoc polymorphism less ad hoc

In Haskell, Wadler & Blott, POPL’89.In Isabelle, Nipkow & Snelting, FPCA’91.

class Eq a where

(==) :: a → a → Bool

instance Eq Bool wherex == y = if x then y else not y

in :: Eq a ⇒ a → [a] → Boolin x [] = Falsein x (y : ys) = x == y || in x ys

Matthieu Sozeau - Coq with Classes 5

Page 8: Coq with Classes

Making ad-hoc polymorphism less ad hoc

In Haskell, Wadler & Blott, POPL’89.In Isabelle, Nipkow & Snelting, FPCA’91.

class Eq a where

(==) :: a → a → Bool

instance Eq Bool wherex == y = if x then y else not y

in :: Eq a ⇒ a → [a] → Boolin x [] = Falsein x (y : ys) = x == y || in x ys

Matthieu Sozeau - Coq with Classes 5

Page 9: Coq with Classes

Making ad-hoc polymorphism less ad hoc

In Haskell, Wadler & Blott, POPL’89.In Isabelle, Nipkow & Snelting, FPCA’91.

class Eq a where

(==) :: a → a → Bool

instance Eq Bool wherex == y = if x then y else not y

in :: Eq a ⇒ a → [a] → Boolin x [] = Falsein x (y : ys) = x == y || in x ys

Matthieu Sozeau - Coq with Classes 5

Page 10: Coq with Classes

Parametrized instances

instance (Eq a) ⇒ Eq [a] where[] == [] = True(x : xs) == (y : ys) = x == y && xs == ys

== = False

Super-classes

class Num a where

(+) :: a → a → a . . .

class (Num a) ⇒ Fractional a where

(/) :: a → a → a . . .

Matthieu Sozeau - Coq with Classes 6

Page 11: Coq with Classes

Parametrized instances

instance (Eq a) ⇒ Eq [a] where[] == [] = True(x : xs) == (y : ys) = x == y && xs == ys

== = False

Super-classes

class Num a where

(+) :: a → a → a . . .

class (Num a) ⇒ Fractional a where

(/) :: a → a → a . . .

Matthieu Sozeau - Coq with Classes 6

Page 12: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 7

Page 13: Coq with Classes

Extension to Coq

I Overloading of names in programs, specifications and proofs.

I A safer Haskell Proofs are part of instances.

Class Eq A := {eqb : A → A → bool ;eq eqb : ∀ x y : A, x = y ↔ eqb x y = true }.

I Types and values are unified Dependent types give new powerto type classes.

Class Reflexive A (R : relation A) :=reflexive : ∀ x , R x x .

Matthieu Sozeau - Coq with Classes 8

Page 14: Coq with Classes

Extension to Coq

I Overloading of names in programs, specifications and proofs.

I A safer Haskell Proofs are part of instances.

Class Eq A := {eqb : A → A → bool ;eq eqb : ∀ x y : A, x = y ↔ eqb x y = true }.

I Types and values are unified Dependent types give new powerto type classes.

Class Reflexive A (R : relation A) :=reflexive : ∀ x , R x x .

Matthieu Sozeau - Coq with Classes 8

Page 15: Coq with Classes

Extension to Coq

I Overloading of names in programs, specifications and proofs.

I A safer Haskell Proofs are part of instances.

Class Eq A := {eqb : A → A → bool ;eq eqb : ∀ x y : A, x = y ↔ eqb x y = true }.

I Types and values are unified Dependent types give new powerto type classes.

Class Reflexive A (R : relation A) :=reflexive : ∀ x , R x x .

Matthieu Sozeau - Coq with Classes 8

Page 16: Coq with Classes

A cheap implementation

I Parametrized dependent records

Class Id (α1 : τ1) · · · (αn : τn) :={f1 : φ1 ; · · · ; fm : φm}.

Instances are just definitions of conclusion Id−→tn .

I Custom implicit arguments of projections

f1 : ∀

{

−−−−→αn : τn

}

,

{

Id −→αn

}

→ φ1

Matthieu Sozeau - Coq with Classes 9

Page 17: Coq with Classes

A cheap implementation

I Parametrized dependent records

Record Id (α1 : τ1) · · · (αn : τn) :={f1 : φ1 ; · · · ; fm : φm}.

Instances are just definitions of conclusion Id−→tn .

I Custom implicit arguments of projections

f1 : ∀

{

−−−−→αn : τn

}

,

{

Id −→αn

}

→ φ1

Matthieu Sozeau - Coq with Classes 9

Page 18: Coq with Classes

A cheap implementation

I Parametrized dependent records

Record Id (α1 : τ1) · · · (αn : τn) :={f1 : φ1 ; · · · ; fm : φm}.

Instances are just definitions of conclusion Id−→tn .

I Custom implicit arguments of projections

f1 : ∀

{

−−−−→αn : τn

}

,

{

Id −→αn

}

→ φ1

Matthieu Sozeau - Coq with Classes 9

Page 19: Coq with Classes

A cheap implementation

I Parametrized dependent records

Record Id (α1 : τ1) · · · (αn : τn) :={f1 : φ1 ; · · · ; fm : φm}.

Instances are just definitions of conclusion Id−→tn .

I Custom implicit arguments of projections

f1 : ∀

{

−−−−→αn : τn

}

,

{

Id −→αn

}

→ φ1

Matthieu Sozeau - Coq with Classes 9

Page 20: Coq with Classes

A cheap implementation

I Parametrized dependent records

Record Id (α1 : τ1) · · · (αn : τn) :={f1 : φ1 ; · · · ; fm : φm}.

Instances are just definitions of conclusion Id−→tn .

I Custom implicit arguments of projections

f1 : ∀{−−−−→αn : τn}, {Id −→αn} → φ1

Matthieu Sozeau - Coq with Classes 9

Page 21: Coq with Classes

Elaboration with classes, an example

λx y : bool. eqb x y

{ Implicit arguments }

λx y : bool. @eqb x y

{ Typing }

λx y : bool. @eqb (?A : Type) (?eq : Eq ?A) x y

{ Unification }

λx y : bool. @eqb bool (?eq : Eq bool) x y

{ Proof search for Eq bool returns Eq bool }

λx y : bool. @eqb bool Eq bool x y

Matthieu Sozeau - Coq with Classes 10

Page 22: Coq with Classes

Elaboration with classes, an example

λx y : bool. eqb x y

{ Implicit arguments }

λx y : bool. @eqb x y

{ Typing }

λx y : bool. @eqb (?A : Type) (?eq : Eq ?A) x y

{ Unification }

λx y : bool. @eqb bool (?eq : Eq bool) x y

{ Proof search for Eq bool returns Eq bool }

λx y : bool. @eqb bool Eq bool x y

Matthieu Sozeau - Coq with Classes 10

Page 23: Coq with Classes

Elaboration with classes, an example

λx y : bool. eqb x y

{ Implicit arguments }

λx y : bool. @eqb x y

{ Typing }

λx y : bool. @eqb (?A : Type) (?eq : Eq ?A) x y

{ Unification }

λx y : bool. @eqb bool (?eq : Eq bool) x y

{ Proof search for Eq bool returns Eq bool }

λx y : bool. @eqb bool Eq bool x y

Matthieu Sozeau - Coq with Classes 10

Page 24: Coq with Classes

Elaboration with classes, an example

λx y : bool. eqb x y

{ Implicit arguments }

λx y : bool. @eqb x y

{ Typing }

λx y : bool. @eqb (?A : Type) (?eq : Eq ?A) x y

{ Unification }

λx y : bool. @eqb bool (?eq : Eq bool) x y

{ Proof search for Eq bool returns Eq bool }

λx y : bool. @eqb bool Eq bool x y

Matthieu Sozeau - Coq with Classes 10

Page 25: Coq with Classes

Elaboration with classes, an example

λx y : bool. eqb x y

{ Implicit arguments }

λx y : bool. @eqb x y

{ Typing }

λx y : bool. @eqb (?A : Type) (?eq : Eq ?A) x y

{ Unification }

λx y : bool. @eqb bool (?eq : Eq bool) x y

{ Proof search for Eq bool returns Eq bool }

λx y : bool. @eqb bool Eq bool x y

Matthieu Sozeau - Coq with Classes 10

Page 26: Coq with Classes

Type Class resolution

Proof-search tactic with instances as lemmas:

A : Type, eqa : Eq A ` ? : Eq (list A)

I Simple depth-first search with higher-order unification

– Returns the first solution only

+ Extensible through Ltac

Matthieu Sozeau - Coq with Classes 11

Page 27: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 12

Page 28: Coq with Classes

Numeric overloading

Class Num α := { zero : α ; one : α ; plus : α → α → α }.

Instance nat num : Num nat :={ zero := 0%nat ; one := 1%nat ; plus := Peano.plus }.

Instance Z num : Num Z :={ zero := 0%Z ; one := 1%Z ; plus := Zplus }.

Notation ”0” := zero.Notation ”1” := one.Infix ”+” := plus.

Check (λ x : nat, x + (1 + 0 + x)).Check (λ x : Z, x + (1 + 0 + x)).

(* Defaulting *)

Check (λ x , x + 1).

Matthieu Sozeau - Coq with Classes 13

Page 29: Coq with Classes

Numeric overloading

Class Num α := { zero : α ; one : α ; plus : α → α → α }.Instance nat num : Num nat :={ zero := 0%nat ; one := 1%nat ; plus := Peano.plus }.

Instance Z num : Num Z :={ zero := 0%Z ; one := 1%Z ; plus := Zplus }.

Notation ”0” := zero.Notation ”1” := one.Infix ”+” := plus.

Check (λ x : nat, x + (1 + 0 + x)).Check (λ x : Z, x + (1 + 0 + x)).

(* Defaulting *)

Check (λ x , x + 1).

Matthieu Sozeau - Coq with Classes 13

Page 30: Coq with Classes

Numeric overloading

Class Num α := { zero : α ; one : α ; plus : α → α → α }.Instance nat num : Num nat :={ zero := 0%nat ; one := 1%nat ; plus := Peano.plus }.

Instance Z num : Num Z :={ zero := 0%Z ; one := 1%Z ; plus := Zplus }.

Notation ”0” := zero.Notation ”1” := one.Infix ”+” := plus.

Check (λ x : nat, x + (1 + 0 + x)).Check (λ x : Z, x + (1 + 0 + x)).

(* Defaulting *)

Check (λ x , x + 1).

Matthieu Sozeau - Coq with Classes 13

Page 31: Coq with Classes

Numeric overloading

Class Num α := { zero : α ; one : α ; plus : α → α → α }.Instance nat num : Num nat :={ zero := 0%nat ; one := 1%nat ; plus := Peano.plus }.

Instance Z num : Num Z :={ zero := 0%Z ; one := 1%Z ; plus := Zplus }.

Notation ”0” := zero.Notation ”1” := one.Infix ”+” := plus.

Check (λ x : nat, x + (1 + 0 + x)).Check (λ x : Z, x + (1 + 0 + x)).

(* Defaulting *)

Check (λ x , x + 1).

Matthieu Sozeau - Coq with Classes 13

Page 32: Coq with Classes

Numeric overloading

Class Num α := { zero : α ; one : α ; plus : α → α → α }.Instance nat num : Num nat :={ zero := 0%nat ; one := 1%nat ; plus := Peano.plus }.

Instance Z num : Num Z :={ zero := 0%Z ; one := 1%Z ; plus := Zplus }.

Notation ”0” := zero.Notation ”1” := one.Infix ”+” := plus.

Check (λ x : nat, x + (1 + 0 + x)).Check (λ x : Z, x + (1 + 0 + x)).

(* Defaulting *)

Check (λ x , x + 1).

Matthieu Sozeau - Coq with Classes 13

Page 33: Coq with Classes

Instance inference

Class EqDec A := eq dec : ∀ x y : A, {x = y} + {x 6= y}.Instance: EqDec nat := { eq dec := eq nat dec }.Instance: EqDec bool := { eq dec := bool dec }.

Program Instance: ∀ A, EqDec A → EqDec (option A) := {eq dec x y := match x , y with

| None, None ⇒ in left| Some x , Some y ⇒ if eq dec x y then in left else in right| , ⇒ in rightend }.

Check (λ x : option (option nat), eq dec x None).: ∀ x : option (option nat), {x = None} + {x 6= None}Eval compute in (eq dec (Some (Some 0)) (Some None)).= in right : {Some (Some 0) = Some None} + {Some (Some 0)6= Some None}

Matthieu Sozeau - Coq with Classes 14

Page 34: Coq with Classes

Instance inference

Class EqDec A := eq dec : ∀ x y : A, {x = y} + {x 6= y}.Instance: EqDec nat := { eq dec := eq nat dec }.Instance: EqDec bool := { eq dec := bool dec }.Program Instance: ∀ A, EqDec A → EqDec (option A) := {

eq dec x y := match x , y with

| None, None ⇒ in left| Some x , Some y ⇒ if eq dec x y then in left else in right| , ⇒ in rightend }.

Check (λ x : option (option nat), eq dec x None).: ∀ x : option (option nat), {x = None} + {x 6= None}Eval compute in (eq dec (Some (Some 0)) (Some None)).= in right : {Some (Some 0) = Some None} + {Some (Some 0)6= Some None}

Matthieu Sozeau - Coq with Classes 14

Page 35: Coq with Classes

Dependent classes

Class Reflexive {A} (R : relation A) :=refl : ∀ x , R x x .

Instance eq refl A : Reflexive (@eq A) := @refl equal A.

Instance iff refl : Reflexive iff.Proof. red. tauto. Qed.

Goal ∀ P, P ↔ P.Proof. apply refl. Qed.

Goal ∀ A (x : A), x = x .Proof. intros A ; apply refl. Qed.

Ltac refl := apply refl.

Lemma foo ‘{Reflexive nat R} : R 0 0.Proof. intros. refl . Qed.

Matthieu Sozeau - Coq with Classes 15

Page 36: Coq with Classes

Dependent classes

Class Reflexive {A} (R : relation A) :=refl : ∀ x , R x x .

Instance eq refl A : Reflexive (@eq A) := @refl equal A.

Instance iff refl : Reflexive iff.Proof. red. tauto. Qed.

Goal ∀ P, P ↔ P.Proof. apply refl. Qed.

Goal ∀ A (x : A), x = x .Proof. intros A ; apply refl. Qed.

Ltac refl := apply refl.

Lemma foo ‘{Reflexive nat R} : R 0 0.Proof. intros. refl . Qed.

Matthieu Sozeau - Coq with Classes 15

Page 37: Coq with Classes

Dependent classes

Class Reflexive {A} (R : relation A) :=refl : ∀ x , R x x .

Instance eq refl A : Reflexive (@eq A) := @refl equal A.

Instance iff refl : Reflexive iff.Proof. red. tauto. Qed.

Goal ∀ P, P ↔ P.Proof. apply refl. Qed.

Goal ∀ A (x : A), x = x .Proof. intros A ; apply refl. Qed.

Ltac refl := apply refl.

Lemma foo ‘{Reflexive nat R} : R 0 0.Proof. intros. refl . Qed.

Matthieu Sozeau - Coq with Classes 15

Page 38: Coq with Classes

Dependent classes

Class Reflexive {A} (R : relation A) :=refl : ∀ x , R x x .

Instance eq refl A : Reflexive (@eq A) := @refl equal A.

Instance iff refl : Reflexive iff.Proof. red. tauto. Qed.

Goal ∀ P, P ↔ P.Proof. apply refl. Qed.

Goal ∀ A (x : A), x = x .Proof. intros A ; apply refl. Qed.

Ltac refl := apply refl.

Lemma foo ‘{Reflexive nat R} : R 0 0.Proof. intros. refl . Qed.

Matthieu Sozeau - Coq with Classes 15

Page 39: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 16

Page 40: Coq with Classes

Implicit Generalization

An old convention: the free variables of a statement are implicitlyuniversally quantified. E.g., when defining a set of equations:

x + y = y + x ∀x y ∈ Nx + 0 = 0 ∀x ∈ Nx + S y = S (x + y) ∀x y ∈ N

We introduce new syntax to automatically generalize the freevariables of a given term or binder, as implicit arguments:

Γ ` ‘(t) : Type , Γ ` ΠFV(t)\Γ, t

Γ ` ‘(t) : T : Type , Γ ` λFV(t)\Γ, t−−−−−→(xi : τi) ‘{y : T} ,

−−−−−→(xi : τi) {FV(T ) \ −→xi} {y : T}

−−−−−→(xi : τi) ‘(y : T ) ,

−−−−−→(xi : τi) {FV(T ) \ −→xi} (y : T )

Matthieu Sozeau - Coq with Classes 17

Page 41: Coq with Classes

Implicit Generalization

An old convention: the free variables of a statement are implicitlyuniversally quantified. E.g., when defining a set of equations:

x + y = y + x ∀x y ∈ Nx + 0 = 0 ∀x ∈ Nx + S y = S (x + y) ∀x y ∈ N

We introduce new syntax to automatically generalize the freevariables of a given term or binder, as implicit arguments:

Γ ` ‘(t) : Type , Γ ` ΠFV(t)\Γ, t

Γ ` ‘(t) : T : Type , Γ ` λFV(t)\Γ, t−−−−−→(xi : τi) ‘{y : T} ,

−−−−−→(xi : τi) {FV(T ) \ −→xi} {y : T}

−−−−−→(xi : τi) ‘(y : T ) ,

−−−−−→(xi : τi) {FV(T ) \ −→xi} (y : T )

Matthieu Sozeau - Coq with Classes 17

Page 42: Coq with Classes

Monomorphic binary power

The following definition is very naıve, but obviously correct:

Fixpoint power (a : Z) (n : nat) :=match n with

| 0%nat ⇒ 1| S p ⇒ a × power a p

end.

Eval vm compute in power 2 40.= 1099511627776 : Z

Matthieu Sozeau - Coq with Classes 18

Page 43: Coq with Classes

An efficient tail-recursive version

This one is more efficient but relies on a more elaborate property:

Function binary power mult (acc x : Z) (n : nat){measure (fun i⇒i) n} : Z :=match n with

| 0%nat ⇒ acc| ⇒ if Even.even odd dec nthen binary power mult acc (x × x) (div2 n)else binary power mult (acc × x) (x × x) (div2 n)

end.

Definition binary power (x :Z) (n:nat) :=binary power mult 1 x n.

Eval vm compute in binary power 2 40.= 1099511627776 : Z

Goal binary power 2 234 = power 2 234.Proof. reflexivity. Qed.

Matthieu Sozeau - Coq with Classes 19

Page 44: Coq with Classes

Questions

I Is binary power correct (w.r.t. power)?

I Is it worth proving this correctness only for powers of integers?

I And prove it again for powers of real numbers, matrices?

NO!

We aim to prove the equivalence between power andbinary power for any structure consisting of a binary associativeoperation that admits a neutral element, i.e. any monoid.

Matthieu Sozeau - Coq with Classes 20

Page 45: Coq with Classes

Questions

I Is binary power correct (w.r.t. power)?

I Is it worth proving this correctness only for powers of integers?

I And prove it again for powers of real numbers, matrices?

NO!

We aim to prove the equivalence between power andbinary power for any structure consisting of a binary associativeoperation that admits a neutral element, i.e. any monoid.

Matthieu Sozeau - Coq with Classes 20

Page 46: Coq with Classes

Questions

I Is binary power correct (w.r.t. power)?

I Is it worth proving this correctness only for powers of integers?

I And prove it again for powers of real numbers, matrices?

NO!

We aim to prove the equivalence between power andbinary power for any structure consisting of a binary associativeoperation that admits a neutral element, i.e. any monoid.

Matthieu Sozeau - Coq with Classes 20

Page 47: Coq with Classes

Questions

I Is binary power correct (w.r.t. power)?

I Is it worth proving this correctness only for powers of integers?

I And prove it again for powers of real numbers, matrices?

NO!

We aim to prove the equivalence between power andbinary power for any structure consisting of a binary associativeoperation that admits a neutral element, i.e. any monoid.

Matthieu Sozeau - Coq with Classes 20

Page 48: Coq with Classes

Monoids

Class Monoid {A:Type} (dot : A → A → A) (one : A) : Type :={ dot assoc : ∀ x y z : A, dot x (dot y z) = dot (dot x y) z ;

one left : ∀ x , dot one x = x ;one right : ∀ x , dot x one = x }.

Operations as parameters to ease sharing, allows to specifymultiple monoids on the same carrier unambiguously, e.g.Monoid 0 plus and Monoid 1 mult.

Matthieu Sozeau - Coq with Classes 21

Page 49: Coq with Classes

Implicit Generalization

Quantification becomes verbose:

Definition two {A dot one} {M : @Monoid A dot one} :=dot one one.

Using implicit generalization:

Generalizable Variables A dot one.

Definition three ‘{Monoid A dot one} := dot two one.

Matthieu Sozeau - Coq with Classes 22

Page 50: Coq with Classes

Generic notations

One can define trivial projections to recover global names forparameters:

Definition monop ‘{Monoid A dot one} := dot.Definition monunit ‘{Monoid A dot one} := one.

and the corresponding generic notations:

Infix ”×” := monop.Notation ”1” := monunit.

Matthieu Sozeau - Coq with Classes 23

Page 51: Coq with Classes

Generic power

Let’s redefine power and binary power generically.

Section Power.Context ‘{Monoid A dot one}.

All following definitions are overloaded over any Monoid structure.

Fixpoint power (a : A) (n : nat) :=match n with

| 0%nat ⇒ 1| S p ⇒ a × (power a p)

end.

Lemma power of unit : ∀ n : nat, power 1 n = 1.Proof. . . . Qed.

Matthieu Sozeau - Coq with Classes 24

Page 52: Coq with Classes

Generic binary exponentiation

Function binary power mult (acc x : A) (n : nat){measure (fun i⇒i) n} : A :=match n with

| 0%nat ⇒ acc| ⇒ if Even.even odd dec nthen binary power mult acc (x × x) (div2 n)else binary power mult (acc × x) (x × x) (div2 n)

end.Definition binary power (x : A) (n : nat) :=

binary power mult 1 x n.

Lemma binary spec x n : power x n = binary power x n.Proof. . . . Qed.

End Power.

Matthieu Sozeau - Coq with Classes 25

Page 53: Coq with Classes

Instantiation

Let’s build a Monoid instance.

Instance ZMult : Monoid Zmult 1%Z .Proof. split.subgoal 1 is:∀ x y z : Z, x × (y × z) = x × y × zsubgoal 2 is:∀ x : Z, 1 × x = xsubgoal 3 is:∀ x : Z, x × 1 = x

. . . Qed.

Matthieu Sozeau - Coq with Classes 26

Page 54: Coq with Classes

Instantiation

We can now use the overloaded power on our new Monoid.

About power.: ∀ (A : Type) (dot : A → A → A) (one : A), Monoid dot one →A → nat → AArguments A, dot, one, H are implicit and maximally inserted

Set Printing Implicit.Check power 2 100.@power Z Z.mul 1 ZMult 2 100 : Z

Compute power 2 100.= 1267650600228229401496703205376 : Z

Matthieu Sozeau - Coq with Classes 27

Page 55: Coq with Classes

Instantiation

We can now use the overloaded power on our new Monoid.

About power.: ∀ (A : Type) (dot : A → A → A) (one : A), Monoid dot one →A → nat → AArguments A, dot, one, H are implicit and maximally inserted

Set Printing Implicit.Check power 2 100.@power Z Z.mul 1 ZMult 2 100 : Z

Compute power 2 100.= 1267650600228229401496703205376 : Z

Matthieu Sozeau - Coq with Classes 27

Page 56: Coq with Classes

Instantiation

We can now use the overloaded power on our new Monoid.

About power.: ∀ (A : Type) (dot : A → A → A) (one : A), Monoid dot one →A → nat → AArguments A, dot, one, H are implicit and maximally inserted

Set Printing Implicit.Check power 2 100.@power Z Z.mul 1 ZMult 2 100 : Z

Compute power 2 100.= 1267650600228229401496703205376 : Z

Matthieu Sozeau - Coq with Classes 27

Page 57: Coq with Classes

The monoid of square matrices

Live demo

Matthieu Sozeau - Coq with Classes 28

Page 58: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 29

Page 59: Coq with Classes

Building hierarchies of classes: superclasses

Superclasses become parameters:

Class (Num α) ⇒ Frac α :={ div : α → { y : α | y 6= 0 } → α }.

⇒Class Frac α ‘{Num α} :={ div : α → { y : α | y 6= 0 } → α }.

+ Support for binding super-classes by implicit generalization:

Program Definition div2 ‘{Frac α} (a : α) := div a (1 + 1).

⇒Definition div2 {α} {N : Num α} {Frac α N} (a : α) :=. . .

Matthieu Sozeau - Coq with Classes 30

Page 60: Coq with Classes

Building hierarchies of classes: superclasses

Superclasses become parameters:

Class (Num α) ⇒ Frac α :={ div : α → { y : α | y 6= 0 } → α }.

⇒Class Frac α ‘{Num α} :={ div : α → { y : α | y 6= 0 } → α }.

+ Support for binding super-classes by implicit generalization:

Program Definition div2 ‘{Frac α} (a : α) := div a (1 + 1).

⇒Definition div2 {α} {N : Num α} {Frac α N} (a : α) :=. . .

Matthieu Sozeau - Coq with Classes 30

Page 61: Coq with Classes

Building hierarchies of classes: subinstances

Substructures become subinstances:

Class Monoid A := { monop : A → A → A ; . . . }Class Group A := { grp mon :> Monoid A ; . . . }

Instance grp mon ‘{Group A} : Monoid A.

Definition foo ‘{Group A} (x : A) : A := monop x x .

Similar to the existing Structures based on coercive subtyping.

Matthieu Sozeau - Coq with Classes 31

Page 62: Coq with Classes

Building hierarchies of classes: subinstances

Substructures become subinstances:

Class Monoid A := { monop : A → A → A ; . . . }Class Group A := { grp mon : Monoid A ; . . . }Instance grp mon ‘{Group A} : Monoid A.

Definition foo ‘{Group A} (x : A) : A := monop x x .

Similar to the existing Structures based on coercive subtyping.

Matthieu Sozeau - Coq with Classes 31

Page 63: Coq with Classes

Building hierarchies of classes: subinstances

Substructures become subinstances:

Class Monoid A := { monop : A → A → A ; . . . }Class Group A := { grp mon : Monoid A ; . . . }Instance grp mon ‘{Group A} : Monoid A.

Definition foo ‘{Group A} (x : A) : A := monop x x .

Similar to the existing Structures based on coercive subtyping.

Matthieu Sozeau - Coq with Classes 31

Page 64: Coq with Classes

Fields or Parameters?

When one doesn’t have manifest types and with constraints...

Class Functor := { A : Type; B : Type;src : Category A ; dst : Category B ; . . . }

or

Class Functor A B := { src : Category A; dst : Category B; . . . }

or

Class Functor A (src : Category A) B (dst : Category B) := . . .

???

Matthieu Sozeau - Coq with Classes 32

Page 65: Coq with Classes

Sharing by equalities

Definition adjunction (F : Functor) (G : Functor),src F = dst G → dst F = src G → . . .

Obfuscates the goals and the computations, awkward to use.

Matthieu Sozeau - Coq with Classes 33

Page 66: Coq with Classes

Sharing by parameters

Class (C : Category obj , D : Category obj’) ⇒ Functor := . . .

≡Class Functor ‘(C : Category obj , D : Category obj’) := . . .

≡Record Functor {obj} (C : Category obj)

{obj’}(D : Category obj’) := . . .

Definition adjunction ‘{C : Category obj , D : Category obj’}(F : Functor C D) (G : Functor D C ) := . . .

Uses the dependent product and named, first-class instances.

Matthieu Sozeau - Coq with Classes 34

Page 67: Coq with Classes

Sharing by parameters

Class (C : Category obj , D : Category obj’) ⇒ Functor := . . .

≡Class Functor ‘(C : Category obj , D : Category obj’) := . . .

≡Record Functor {obj} (C : Category obj)

{obj’}(D : Category obj’) := . . .

Definition adjunction ‘{C : Category obj , D : Category obj’}(F : Functor C D) (G : Functor D C ) := . . .

Uses the dependent product and named, first-class instances.

Matthieu Sozeau - Coq with Classes 34

Page 68: Coq with Classes

Sharing by parameters

Class (C : Category obj , D : Category obj’) ⇒ Functor := . . .

≡Class Functor ‘(C : Category obj , D : Category obj’) := . . .

≡Record Functor {obj} (C : Category obj)

{obj’}(D : Category obj’) := . . .

Definition adjunction ‘{C : Category obj , D : Category obj’}(F : Functor C D) (G : Functor D C ) := . . .

Uses the dependent product and named, first-class instances.

Matthieu Sozeau - Coq with Classes 34

Page 69: Coq with Classes

Category

Class Category (obj : Type) (hom : obj → obj → Type) := {morphisms :> ∀ a b, Setoid (hom a b) ;id : ∀ a, hom a a;compose : ∀ {a b c}, hom a b → hom b c → hom a c ;id unit left : ∀ ‘(f : hom a b), compose f (id b) == f ;id unit right : ∀ ‘(f : hom a b), compose (id a) f == f ;assoc : ∀ a b c d (f : hom a b) (g : hom b c) (h : hom c d),

compose f (compose g h) == compose (compose f g) h }.Notation ” x ’◦’ y ” := (compose y x)

(left associativity, at level 40).

Matthieu Sozeau - Coq with Classes 35

Page 70: Coq with Classes

Abstract instances

Definition opposite (X : Type) := X .

Program Instance opposite category ‘( Category obj hom ) :Category (opposite obj) (flip hom).

Class Terminal ‘(C : Category obj hom) (one : obj) := {bang : ∀ x , hom x one ;unique : ∀ x (f g : hom x one), f == g }.

Matthieu Sozeau - Coq with Classes 36

Page 71: Coq with Classes

Abstract instances

Definition opposite (X : Type) := X .

Program Instance opposite category ‘( Category obj hom ) :Category (opposite obj) (flip hom).

Class Terminal ‘(C : Category obj hom) (one : obj) := {bang : ∀ x , hom x one ;unique : ∀ x (f g : hom x one), f == g }.

Matthieu Sozeau - Coq with Classes 36

Page 72: Coq with Classes

An abstract proof

Definition isomorphic ‘{ Category obj hom } a b :={ f : hom a b & { g : hom b a |

f ◦ g == id b ∧ g ◦ f == id a } }.Lemma terminal isomorphic ‘{C : Category obj hom} :

‘( Terminal C x → Terminal C y → isomorphic x y ).Proof.intros. red.do 2 eexists (bang ).split ; apply unique.

Qed.

Matthieu Sozeau - Coq with Classes 37

Page 73: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 38

Page 74: Coq with Classes

Boolean formulas

Inductive formula :=| cst : bool → formula| not : formula → formula| and : formula → formula → formula| or : formula → formula → formula| impl : formula → formula → formula.

Fixpoint interp f :=match f with

| cst b ⇒ if b then True else False| not b ⇒ ¬ interp b| and a b ⇒ interp a ∧ interp b| or a b ⇒ interp a ∨ interp b| impl a b ⇒ interp a → interp b

end.

Matthieu Sozeau - Coq with Classes 39

Page 75: Coq with Classes

Boolean formulas

Inductive formula :=| cst : bool → formula| not : formula → formula| and : formula → formula → formula| or : formula → formula → formula| impl : formula → formula → formula.

Fixpoint interp f :=match f with

| cst b ⇒ if b then True else False| not b ⇒ ¬ interp b| and a b ⇒ interp a ∧ interp b| or a b ⇒ interp a ∨ interp b| impl a b ⇒ interp a → interp b

end.

Matthieu Sozeau - Coq with Classes 39

Page 76: Coq with Classes

Reification

Class Reify (prop : Prop) :={ reification : formula ;

reify correct : interp reification ↔ prop }.

Check (@reification : ∀ prop : Prop, Reify prop → formula).

Implicit Arguments reification [[Reify ]].

Program Instance true reif : Reify True :={ reification := cst true }.

Program Instance not reif ‘(Rb : Reify b) : Reify (¬ b) :={ reification := not (reification b) }.

Example example prop :=reification ((True ∧ ¬ False) → ¬ ¬ False).

Check (refl equal : example prop =impl (and (cst true) (not (cst false))) (not (not (cst false)))).

Matthieu Sozeau - Coq with Classes 40

Page 77: Coq with Classes

Reification

Class Reify (prop : Prop) :={ reification : formula ;

reify correct : interp reification ↔ prop }.

Check (@reification : ∀ prop : Prop, Reify prop → formula).

Implicit Arguments reification [[Reify ]].

Program Instance true reif : Reify True :={ reification := cst true }.

Program Instance not reif ‘(Rb : Reify b) : Reify (¬ b) :={ reification := not (reification b) }.

Example example prop :=reification ((True ∧ ¬ False) → ¬ ¬ False).

Check (refl equal : example prop =impl (and (cst true) (not (cst false))) (not (not (cst false)))).

Matthieu Sozeau - Coq with Classes 40

Page 78: Coq with Classes

Reification

Class Reify (prop : Prop) :={ reification : formula ;

reify correct : interp reification ↔ prop }.

Check (@reification : ∀ prop : Prop, Reify prop → formula).

Implicit Arguments reification [[Reify ]].

Program Instance true reif : Reify True :={ reification := cst true }.

Program Instance not reif ‘(Rb : Reify b) : Reify (¬ b) :={ reification := not (reification b) }.

Example example prop :=reification ((True ∧ ¬ False) → ¬ ¬ False).

Check (refl equal : example prop =impl (and (cst true) (not (cst false))) (not (not (cst false)))).

Matthieu Sozeau - Coq with Classes 40

Page 79: Coq with Classes

Reification

Class Reify (prop : Prop) :={ reification : formula ;

reify correct : interp reification ↔ prop }.

Check (@reification : ∀ prop : Prop, Reify prop → formula).

Implicit Arguments reification [[Reify ]].

Program Instance true reif : Reify True :={ reification := cst true }.

Program Instance not reif ‘(Rb : Reify b) : Reify (¬ b) :={ reification := not (reification b) }.

Example example prop :=reification ((True ∧ ¬ False) → ¬ ¬ False).

Check (refl equal : example prop =impl (and (cst true) (not (cst false))) (not (not (cst false)))).

Matthieu Sozeau - Coq with Classes 40

Page 80: Coq with Classes

Type Classes as logic programming

Implement domain-specific proof-automation:

I Discharge separation logic disjointness side-conditions(Nanevsky et al, ICFP’11)

I Generalized rewriting tactic using proof-search for morphisms(Sozeau, JFR’09)

I Derive continuity, monotonicity conditions. . .

Matthieu Sozeau - Coq with Classes 41

Page 81: Coq with Classes

Type Classes

1 Type Classes in theoryMotivation and setupType Classes from HaskellType Classes in Coq

2 Type Classes in practicePlaying with numbersInstance InferenceDependent ClassesA programming example: Generic exponentiationA structuring tool: Building hierarchiesLogic programming: Reification

3 SummaryRelated and future work

Matthieu Sozeau - Coq with Classes 42

Page 82: Coq with Classes

Related work

Type Classes implementations:

I In Haskell by Wadler et al. (POPL’89, FO, second class)

I In Isabelle by Nipkow et al. (POPL’93, same)

I In Agda by Devriese and Piessens (ICFP’11,non-recursive proof search)

In Coq and Matita:

I Coercive Subtyping and Canonical Structures (Saıbi,POPL’97). Used by Gonthier et al. (TPHOLs’09),Nanevski et al. (ICFP’11).

I Unification hints, a more general framework studied byAsperti et al. (TPHOLs’09).

Matthieu Sozeau - Coq with Classes 43

Page 83: Coq with Classes

Experiments and formalizations in Coq

I Sets, Maps etc... (Letouzey, Lescuyer . . . )

I Domain theory, probability monad (Paulin, . . . )

I Generalized rewriting (Sozeau, JFR’09)

I ACI rewriting (Braibant & Pous, ITP’11)

I Universal algebra, category theory and computable reals(Spitters et al., ITP’10)

Matthieu Sozeau - Coq with Classes 44

Page 84: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search

⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 85: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 86: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints

⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 87: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 88: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination

⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 89: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 90: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search

⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 91: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 92: Coq with Classes

Current issues and perspectives

Proof search efficiency and control issues...

Prerequisite Proper formalization of unificationHope These are all researched in the logic programming community

I Undeterministic proof-search⇒ Determinacy inference (Kriener and King, ICLP’11)

I No forward reasoning or reordering of constraints⇒ Mode analysis (a la Prolog, Twelf)

I Risk of non-termination⇒ Termination analysis, requires modes

I Little sharing and intelligence in the proof-search⇒ Focusing, strategies.

I Scoping of instances... through modules only.

Matthieu Sozeau - Coq with Classes 45

Page 93: Coq with Classes

Summary & Conclusions

3 A lightweight and general implementation of type classes,available since Coq v8.2.

3 A type-theoretic explanation and extension of type classesconcepts (TPHOLs’08, with Oury).

Takeaway:

I An elaborated overloading mechanism

I Lightweight, first-class modules

I A logic programming language on top of Coq

Matthieu Sozeau - Coq with Classes 46