How do I prove that two Fibonacci implementations are equal in Coq?

后端 未结 6 1236
南方客
南方客 2021-01-03 16:36

I\'ve two Fibonacci implementations, seen below, that I want to prove are functionally equivalent.

I\'ve already proved properties about natural numbers, but this ex

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 17:04

    Here is yet another answer, similar to the one using mathcomp, but this one uses "vanilla" Coq.

    First of all, we need some imports, additional definitions, and a couple of helper lemmas:

    Require Import Coq.Arith.Arith.
    
    Definition fib_v2 n := visit_fib_v2 n 0 1.
    
    Lemma visit_fib_v2_property n: forall a0 a1,
      visit_fib_v2 (S (S n)) a0 a1 =
      visit_fib_v2 (S n) a0 a1 + visit_fib_v2 n a0 a1.
    Proof. now induction n; firstorder. Qed.
    
    Lemma fib_v2_property n:
      fib_v2 (S (S n)) = fib_v2 (S n) + fib_v2 n.
    Proof. apply visit_fib_v2_property. Qed.
    

    To prove the main lemma we are going to use the standard well-founded induction lt_wf_ind principle for natural numbers with the < relation (a.k.a. complete induction):

    This time we need to prove only one subgoal, since the n = 0 case for complete induction is always vacuously true. Our induction hypothesis, unsurprisingly, looks like this:

    IH : forall m : nat, m < n -> fib_v1 m = fib_v2 m
    

    Here is the proof:

    Lemma fib_v1_eq_fib2 n :
      fib_v1 n = fib_v2 n.
    Proof.
      pattern n; apply lt_wf_ind; clear n; intros n IH.
      do 2 (destruct n; trivial).
      rewrite fib_v2_property.
      rewrite <- !IH; auto.
    Qed.
    

提交回复
热议问题