I am currently working with Coq and I am encountering a problem that I don't know how to solve.
Let's say we are working with a given type, I'll take nat
for the example, and I want to use a function f
that might fail. To compensate the failure, we define f
to be of type nat -> option nat
.
Now I have a given hypothesis H: nat -> bool
under which f doesn't fail, and I have even proved the lemma
Lemma no_error_in_f : forall (n:nat), H n = true -> exists (u:nat), f n = Some u.
I want to define a function g: nat->nat
which gives the result of f
on n
if H n
is satisfied, and just gives n
otherwise. This function should be well defined, but I don't know how to define it properly.
If I try something naive like
Definition g (n:nat) := if H n then f n else n.
, there is a problem in the typing system.
Does anyone knows how to gather all the elements and tell the system that the definition is legal?
I give here a solution that works with the same hypotheses as the ones given in the question.
Axiom f : nat -> option nat.
Axiom H : nat -> bool.
Axiom no_error_in_f : forall n,
H n = true -> exists u, f n = Some u.
Lemma no_error_in_f_bis : forall n,
H n = true -> f n <> None.
Proof.
intros. apply no_error_in_f in H0. destruct H0. rewrite H0. discriminate.
Qed.
Definition g n :=
match H n as b return H n = b -> _ with
| true => fun H =>
match f n as f0 return f n = f0 -> _ with
| Some n0 => fun _ => n0
| None => fun H0 => match no_error_in_f_bis n H H0 with end
end eq_refl
| false => fun _ => n
end eq_refl.
I use another lemma than no_error_in_f
, which is more convenient to prove False
.
Note that the two ideas of this function (use the return
construct of match
, destruct a proof of False
to show that a branch is not reachable) are explained here: http://adam.chlipala.net/cpdt/html/Subset.html.