Verified Element Index
Description:
Verified Element Index
Prerequisites
A basic aptitude in Coq. Being able to complete all the non-advanced, non-optional exercises in the first 7 chapters of Logical Foundations (i.e. up to and including Inductively Defined Propositions (IndProp)) will suffice.
Task
The Haskell standard library provides a useful utility function elemIndex
for searching for an element in a list and returning the index at which it first occurs (if it is present in the list) or reports that the element cannot be found in the list.
An implementation of elemIndex
in Coq (renamed elem_index
to better suit Coq naming conventions) is as follows:
Fixpoint elem_index {A : Type}
(eq_dec : forall x y : A, {x = y} + {x <> y})
(n : A) (l : list A) : option nat :=
match l with
| [] => None
| x :: xs =>
if eq_dec n x
then Some O
else
match elem_index eq_dec n xs with
| Some idx => Some (S idx)
| None => None
end
end.
A complete specification of the (expected) behavior of elemIndex
is as follows - given some element x
that we want to search for and a list xs
to search for x
in:
- If
elemIndex
returns some indexi
then all of the following conditions must hold simultaneously:- The input list
xs
must contain at leasti + 1
elements - The first
i
elements inxs
cannot bex
- The
i + 1
th element inxs
must bex
- The input list
- Otherwise, if
elemIndex
reports thatx
cannot be found inxs
thenxs
cannot containx
Convince yourself that the specification outlined above fully describes the expected behavior of elemIndex
and then proceed to formally verify in Coq that the implementation of elemIndex
given above correctly implements this specification.
Preloaded
The full source code of the Preloaded section is displayed below for your reference:
From Coq Require Import List.
Import ListNotations.
Fixpoint elem_index {A : Type}
(eq_dec : forall x y : A, {x = y} + {x <> y})
(n : A) (l : list A) : option nat :=
match l with
| [] => None
| x :: xs =>
if eq_dec n x
then Some O
else
match elem_index eq_dec n xs with
| Some idx => Some (S idx)
| None => None
end
end.
Too easy?
Then here's an open challenge for you that you might find interesting ;-)
Similar Kata:
Stats:
Created | Nov 26, 2019 |
Published | Nov 26, 2019 |
Warriors Trained | 130 |
Total Skips | 4 |
Total Code Submissions | 46 |
Total Times Completed | 40 |
Coq Completions | 40 |
Total Stars | 2 |
% of votes with a positive feedback rating | 100% of 9 |
Total "Very Satisfied" Votes | 9 |
Total "Somewhat Satisfied" Votes | 0 |
Total "Not Satisfied" Votes | 0 |
Total Rank Assessments | 3 |
Average Assessed Rank | 6 kyu |
Highest Assessed Rank | 6 kyu |
Lowest Assessed Rank | 7 kyu |