Section tree_ind.
Variable P : tree -> Prop.
Hypothesis P_atom : forall a, P (atom a).
Hypothesis P_node : forall l, List.Forall P l -> P (node l).
Definition tree_ind (t : tree) : P t :=
tree_rect P (List.Forall P)
(List.Forall_nil _)
(fun t l Pt Pl => List.Forall_cons _ Pt Pl) P_atom P_node t.
End tree_ind.
End tree.
Fixpoint rev_rec {A} (l : list A) (acc : list A) :=
match l with
| [] => acc
| a :: l => rev_rec l (a :: acc)
end.
Definition rev' {A} (l : list A) :=
rev_rec l [].
Fixpoint map_rec {A B} (f : A -> B) (l : list A) (acc : list B) :=
match l with
| [] => rev' acc
| a :: l => map_rec f l (f a :: acc)
end.
Definition list_map' {A B} (f : A -> B) (l : list A) :=
map_rec f l [].
intros.
unfold list_map'.
now rewrite map_rec_spec.
Qed.
(* The shape of a tree can be expressed by mapping (fun _ => tt) over it. *)
Fixpoint map {A B} (f : A -> B) (t : tree A) : tree B :=
match t with
| atom a => atom (f a)
| node l => node (List.map (map f) l)
end.
Definition shape {A} (t : tree A) : tree unit :=
map (fun _ => tt) t.
Fixpoint tree_map' {A B} (f : A -> B) (t : tree A) : tree B :=
let fix tree_map_loop {A B} (f : A -> B) (l : list (tree A)) acc :=
match l with
| [] => rev_rec acc []
| a :: l => tree_map_loop f l (map f a :: acc)
end in
match t with
| atom a => atom (f a)
| node l => node (tree_map_loop f l [])
end.
Definition tree_map_loop :=
fix tree_map_loop {A B} (f : A -> B) (l : list (tree A)) acc :=
match l with
| [] => rev_rec acc []
| a :: l => tree_map_loop f l (map f a :: acc)
end.

Theorem tree_map'_spec : forall {A B} (f : A -> B) (t : tree A),
tree_map' f t = map f t.