Software Foundations
Michael Clarkson's Open Online Course (on Youtube) Michael Charkson's Course (on Bilibili)
Xiong Yingfei's Course Webpage (2023 Spring)
This note is used as a brief summary and supplementofr the textbook and courses.
Poly
Polymorphism
Omit Type Argument
1 | Inductive list (X:Type) : Type := |
The type list is thus parameterized on another type X.
When we want to avoid typing the type, and let Coq to infer it. We
can set: 1
2
3
4
5
6
7
8
9Arguments nil {X}.
Arguments cons {X}.
Arguments repeat {X}.
Fixpoint app {X : Type} (l1 l2 : list X) : list X :=
match l1 with
| nil => l2
| cons h t => cons h (app t l2)
end.
Catesian Product
1 | Inductive prod (X Y : Type) : Type := |
Higher-Order Functions
Functions that manipulate other functions are often called higher-order functions.
For example, we have filter
function 1
2
3
4
5
6
7Fixpoint filter {X:Type} (test: X->bool) (l:list X) : list X :=
match l with
| [] => []
| h :: t =>
if test h then h :: (filter test t)
else filter test t
end.
Functions That Construct Functions
Functions that return the given functor whatever the argument is.
1
2
3
4
5
6
7Definition constfun {X: Type} (x: X) : nat -> X :=
fun (k:nat) => x.
Definition ftrue := constfun true.
Example constfun_example1 : ftrue 0 = true.
Proof. reflexivity. Qed.
This function seems useless, but there is a usage of higher-order
functions, let's now mock function currying: 1
2
3
4Definition plus3 := plus 3.
Example test_plus3 : plus3 4 = 7.
Proof. reflexivity. Qed.
Anonymous Functions
Just like \(\lambda\) function in
Haskell, the difference is that Coq use fun
instead of
\
to denote this.
1 | Example test_filter2': |
Map & Fold
map
is also a function that is useful and interesting:
1
2
3
4
5Fixpoint map {X Y : Type} (f : X->Y) (l : list X) : list Y :=
match l with
| [] => []
| h :: t => (f h) :: (map f t)
end.
Take None
value into consideration, we define:
1
2
3
4
5
6Definition option_map {X Y : Type} (f : X -> Y) (xo : option X)
: option Y :=
match xo with
| None => None
| Some x => Some (f x)
end.
And you can't miss fold
, another fantastic function:
1
2
3
4
5
6Fixpoint fold {X Y: Type} (f : X->Y->Y) (l : list X) (b : Y)
: Y :=
match l with
| nil => b
| h :: t => f h (fold f t b)
end.