unfold qs.
fold body.
apply fix_measure_utils.rect.
apply body_eq.
intros.
destruct x...
simpl.
apply Pcons; apply H; unfold MR; simpl...
Qed.
End rect.
(*Eval vm_compute in qs numbers.*)
End nonmonadic.
End nonmonadic.
(* Module nonmonadic_using_wf_ind.  Definition qs (l: list nat): list nat. Proof with unfold MR; simpl; auto with arith. apply (well_founded_induction (measure_wf lt_wf (@length nat))). intro x. refine ( match x as x return _ with | nil => fun _ => nil | pivot :: t => fun q => q (filter (geb pivot) t) _ ++ pivot :: nil ++ q (filter (ltb pivot) t) _ end)... Defined.  Eval compute in qs numbers.  End nonmonadic_using_wf_ind. *)
Module mon_det. (* monadic, deterministic. This is the version used for the worst-case proof. *)
Section mon_det. (* For variable discharging. *)
Variables (M: Monad) (T: Set).
Definition filter (c: T -> M bool) (l: list T): M { l': list T | length l' <= length l }.
(* Something with result type  M (list T)  is not good enough, because then   refine (u <- filter ... ; _)   just gives   u: list T, which is useless. *)
Proof with auto with arith.
induction l.
refine (ret (exist _ nil _))...
refine (
b <- c a ;
t <- IHl ;
ret (if b then exist _ (a :: proj1_sig t) _ else exist _ (proj1_sig t) _)
); simpl; destruct t...
Defined.

(* Specifications: *)
Lemma hm (e: extMonad M) c l: forall U (f: list T -> M U) g,
ext_eq g (f ∘ @proj1_sig _ _) -> filter c l >>= g = filterM c l >>= f.