| 1 |
From Coq Require Import List. |
| 2 |
Require Import Crypto.Util.Option. |
| 3 |
Require Import Crypto.Util.Tactics.BreakMatch. |
| 4 |
|
| 5 |
Module List. |
| 6 |
Section IndexOf. |
| 7 |
Context {A} (f : A -> bool). |
| 8 |
Fixpoint indexof (l : list A) : option nat := |
| 9 |
match l with |
| 10 |
| nil => None |
| 11 |
| cons a l => |
| 12 |
if f a then Some 0 |
| 13 |
else option_map S (indexof l ) |
| 14 |
end. |
| 15 |
Lemma indexof_Some l i (H : indexof l = Some i) : |
| 16 |
exists a, nth_error l i = Some a /\ f a = true. |
| 17 |
Proof using Type. |
| 18 |
revert dependent i; induction l; cbn in *; try congruence; []. |
| 19 |
destruct (f a) eqn:?; cbn. |
| 20 |
{ inversion 1; subst. eexists. split. exact eq_refl. eassumption. } |
| 21 |
{ cbv [option_map]; destruct (indexof l) eqn:?; inversion 1; subst; eauto. } |
| 22 |
Qed. |
| 23 |
|
| 24 |
Lemma indexof_None l (H : indexof l = None) : |
| 25 |
forall i a, nth_error l i = Some a -> f a = false. |
| 26 |
Proof using Type. |
| 27 |
induction l, i. |
| 28 |
all: repeat first [ reflexivity |
| 29 |
| progress cbn in * |
| 30 |
| progress cbv [option_map] in * |
| 31 |
| progress intros |
| 32 |
| progress inversion_option |
| 33 |
| progress subst |
| 34 |
| progress break_innermost_match_hyps |
| 35 |
| solve [ eauto ] ]. |
| 36 |
Qed. |
| 37 |
|
| 38 |
Lemma indexof_app l1 l2 |
| 39 |
: indexof (l1 ++ l2) = Option.sequence (indexof l1) (option_map (fun x => List.length l1 + x) (indexof l2)). |
| 40 |
Proof using Type. |
| 41 |
revert l2; induction l1 as [|x xs IH]; cbn; intros; [ | rewrite IH ]. |
| 42 |
all: cbv [option_map Option.sequence]; break_innermost_match; reflexivity. |
| 43 |
Qed. |
| 44 |
End IndexOf. |
| 45 |
End List. |