Using Dependent Types in Coq (secure nth function)

I'm trying to learn Coq, but it's hard for me to take a leap from what I read in Software Foundations and Certified Programming with Dependent Types for my own use cases.

In particular, I thought that I would try to make a tested version of the function nthin lists. I managed to write this:

Require Import Arith.
Require Import List.
Import ListNotations.

Lemma zltz: 0 < 0 -> False.
Proof.
  intros. contradict H. apply Lt.lt_irrefl.
Qed.

Lemma nltz: forall n: nat, n < 0 -> False.
Proof.
  intros. contradict H. apply Lt.lt_n_0.
Qed.

Lemma predecessor_proof: forall {X: Type} (n: nat) (x: X) (xs: list X),
  S n < length (x::xs) -> n < length xs.
Proof.
  intros. simpl in H. apply Lt.lt_S_n. assumption.
Qed.

Fixpoint safe_nth {X: Type} (n: nat) (xs: list X): n < length xs -> X :=
  match n, xs with
  | 0, [] => fun pf: 0 < length [] => match zltz pf with end
  | S n', [] => fun pf: S n' < length [] => match nltz (S n') pf with end
  | 0, x::_ => fun _ => x
  | S n', x::xs' => fun pf: S n' < length (x::xs') => safe_nth n' xs' (predecessor_proof n' x xs' pf)
  end.

This works, but two questions arise:

  • How do experienced Coq users write this? Are three lemmas necessary? Is this used for types { | }?
  • How do I call this function from another code, i.e. How can I provide the necessary evidence?

I tried this:

Require Import NPeano.
Eval compute in if ltb 2 (length [1; 2; 3]) then safe_nth 2 [1; 2; 3] ??? else 0.

, , , , ???. (2 < length [1; 2; 3]) , Prop, 2 < length [1; 2; 3]. , . ?

+4
2

zltz , nltz 0.

Check zltz.
Check nltz 0.

2 [1; 2; 3] , lt_dec.

Eval compute in match lt_dec 2 (length [1; 2; 3]) with
  | left pf => safe_nth 2 [1; 2; 3] pf
  | right _ => 0
  end.

lt_dec, , ltb . lt_dec, , safe_nth.

.

Fixpoint safe_nth' {X: Type} (xs: list X) (n: nat): n < length xs -> X :=
  match xs, n with
  | [], _ => fun pf => match nltz n pf with end
  | x::_, 0 => fun _ => x
  | x::xs', S n' => fun pf => safe_nth' xs' n' (predecessor_proof n' x xs' pf)
  end.

, , , sig.

+3

, , .

, Coq . , Coq. , - ( Vector.t Fin.t , ). , nth, , , , , , . , Coq , , . , , , .

a nat , , , , { | }. , ssreflect, ( ordinal). nth, , , , , , , n < length l ( , tuple ssreflect, , tnth). , . , : , ssreflect.

, , . , < Coq 0 < 0 = true false = true S n < length (x :: l) = true n < length l = true, , nth . , Coq, , , , , <. , ssreflect , .

+5

Source: https://habr.com/ru/post/1568890/


All Articles