From Undecidability.L.Prelim Require Import ARS MoreBase.
Definition loopSum {X} {Y} :=
fix loopSum n (f:X -> X + Y) (x:X) {struct n}:=
match n with
0 => None
| S n => match f x with
| inl x' => loopSum n f x'
| inr y => Some y
end
end.
Arguments loopSum _ _ !_.
Definition loopSum_mono X Y f x y n n':
n <= n' -> @loopSum X Y n f x = Some y -> loopSum n' f x = Some y.

Lemma loopSum_rel_correct2 X Y {R:X->X->Prop} k x y (f: X -> X + Y):
(forall x, match f x with
| inl y => R x y
| inr _ => terminal R x
end)->
loopSum k f x = Some y ->
exists i x', i < k /\ loopSum k f x = loopSum (k-i) f x'
/\ pow R i x x'
/\ terminal R x'
/\ f x' = inr y.