0

我在这里读到,在有限列表上可以通过以下方式(使用 coq)根据 foldL 编写 foldR:

Fixpoint fold {A : Type} {B : Type} (f : A -> B -> B) (v : B) (l : list A) :=
  match l with
  | nil => v
  | x :: xs => f x (fold f v xs)
  end.

Fixpoint foldL {A : Type} {B : Type} (f : B -> A -> B) (v : B) (l : list A) :=
  match l with
  | nil => v
  | x :: xs => foldL f (f v x) xs
  end.

Definition fold' {A B : Type} (f : B -> A -> A) (a : A) (xs : list B) :=
  foldL (fun g b x => g (f b x)) id xs a.

现在我想证明foldfold'是平等的:

Theorem fold_eq_fold' {A : Type} {B : Type} :
  forall
    (f : B -> A -> A) 
    (v : A),
      fold f v = fold' f v.
Proof.
  intros.
  unfold fold'.
  apply functional_extensionality.
  intros.
  induction x; intros; simpl in *.
  - trivial.
  - rewrite IHx. 
Abort.

但我无法关闭这个定理。

有人可以帮助我吗?

编辑

感谢 Meven Lennon-Bertrand 的回答,我能够关闭这个定理:

Lemma app_cons {A: Type} :
  forall 
    (l1 : list A)
    (l2 : list A)
    (a : A),
      l1 ++ a :: l2 = (l1 ++ [a]) ++ l2.
Proof.
  intros.
  rewrite <- app_assoc. 
  trivial.
Qed.

Theorem fold_eq_fold' {A : Type} {B : Type} :
  forall
    (f : B -> A -> A) 
    (a : A)
    (l : list B),
      fold f a l = fold' f a l.
Proof.
  intros.
  unfold fold'.
  change id with (fun x => fold f x nil).
  change l with (nil ++ l) at 1.
  generalize (@nil B).
  induction l; intros; simpl.
  - rewrite app_nil_r. trivial.
  - rewrite app_cons. rewrite IHl. 
    assert((fun x : A => fold f x (l0 ++ [a0])) = (fun x : A => fold f (f a0 x) l0)).
    + apply functional_extensionality; intros.
      induction l0; simpl.
      * trivial.
      * rewrite IHl0. trivial.
    + rewrite H. trivial.
Qed.
4

1 回答 1

1

问题在于您的归纳假设:它不够普遍,因为它谈论的是id,这在您的第二个目标中没有用。您可以使用以下方法使其足够通用:

Theorem fold_eq_fold' {A : Type} {B : Type} :
  forall
    (f : B -> A -> A) 
    (a : A)
    (l : list B),
      fold f a l = fold' f a l.
Proof.
  intros.
  unfold fold'.
  change id with (fun x => fold f x nil).
  change l with (nil ++ l) at 1.
  generalize (@nil B).

这为您提供了一个更一般形状的目标,将您的目标作为nil. 现在这个应该更容易通过归纳处理l

于 2021-04-09T09:47:08.270 回答