coqfoldfoldleft

FoldR using FoldL on finite lists


I have read here that on finite lists is possible to write foldR in term of foldL in the following way (using coq):

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.

Now I want to demonstrate that fold and fold' are equals:

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.

but I'm unable to close this theorem.

Could someone help me?

Edit

Thanks to Meven Lennon-Bertrand answer, I was able to close the theorem:

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.

Solution

  • The problem is with your induction hypothesis: it is not general enough, since it talks about id, which is of no use in your second goal. You can make it general enough with something like this:

    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).
    

    This gives you a goal of a more general shape, that has yours as a special case with nil. Now this one should be easier to handle by induction on l.