Section RandomPerm.
Variable D R : Set.
Hypothesis D_EqDec : EqDec D.
Hypothesis R_EqDec : EqDec R.
Variable RndR : Comp R.
Hypothesis RndR_wf : well_formed_comp RndR.
Fixpoint inRange(f : list (D * R))(r : R) :=
match f with
| nil => false
| (d', r') :: f' =>
if (eqb r r') then true
else (inRange f' r)
end.
Definition getUnusedR(f : list (D * R)) :=
Repeat (RndR) (fun r => negb (inRange f r)).
intuition.
destruct (in_dec (EqDec_dec _) x (getSupport (getUnusedR ls1))).
unfold getUnusedR in *.
simpl in i.
apply filter_In in i; intuition.
eapply evalDist_Repeat_eq.
intuition.
rewrite H.
trivial.
eapply filter_In; intuition.
eapply sumList_permutation.
eapply NoDup_Permutation.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_NoDup.
eapply getSupport_NoDup.
intuition.
apply filter_In in H2; intuition.
eapply filter_In; intuition.
rewrite <- H.
trivial.
apply filter_In in H2; intuition.
eapply filter_In; intuition.
rewrite H.
trivial.
unfold getUnusedR in *.
simpl in n.
apply filter_not_In in n.
intuition.
simpl.
rewrite getSupport_not_In_evalDist_h; intuition.
repeat rewrite ratMult_0_r.
intuition.
simpl.
unfold indicator.
rewrite <- H.
rewrite H0.
repeat rewrite ratMult_0_l.
intuition.
Qed.
induction ls; intuition; simpl in *.
discriminate.
case_eq (eqb x b); intuition.
rewrite eqb_leibniz in H0.
subst.
intuition.
right.
eapply IHls.
rewrite H0 in H.
trivial.
Qed.
intuition.
unfold getUnusedR.
eapply (well_formed_Repeat _ _ r).
wftac.
eapply filter_In.
intuition.
rewrite H.
simpl.
trivial.
Grab Existential Variables.
unfold eq_dec; intuition.
eapply (EqDec_dec _).
Qed.
Hint Resolve getUnusedR_wf : wftac.
(* A random permutation *)
Definition randomPerm(p : (list (D * R) *  D)) : Comp (list (D * R) * R) :=
let (f, d) := p in
match (f#d) with
| None => (r <-$ getUnusedR f ; ret ((d, r) :: f, r))
| Some r => ret (f, r)
end.
intuition.
unfold randomPerm.
case_eq (ls#b0); intuition; wftac.
edestruct H; eauto.
intuition.
wftac.
Qed.
(* Many proofs involving random permutations will need to query the random permutation repeatedly.  In order to show that each call to the permutation is well-formed, we need to preserve the invariant that the state of the permutation is actually a permutation (as opposed to an arbitrary function).  The well_formed_perm is the predicate that we will use for this invariant. *)
Definition well_formed_perm ls :=
forall lsd,
NoDup lsd ->
(forall d, In d lsd -> ls#d = None) ->
exists lsr,
(forall r, In r lsr -> inRange ls r = false /\ In r (getSupport RndR)) /\
NoDup lsr /\
length lsd = length lsr.
(* Lemma well_formed_perm_nil : well_formed_perm nil.  intuition. unfold well_formed_perm. intuition. econstructor. intuition. eapply H1. eapply getSupport_NoDup.  exists lsd. intuition.  Qed. *)

Lemma well_formed_perm_1 : forall ls,
well_formed_perm ls ->
forall d,
ls#d = None ->
exists r, inRange ls r = false /\ In r (getSupport RndR).