Zulip Chat Archive
Stream: lean4
Topic: Unfold repeat until loop
Gavin Zhao (Jul 30 2025 at 23:54):
I have a repeat ... until loop that only runs for one iteration. Is it possible to sort of "unfold" the monadic action that represents the loop so that I can prove the result of its execution?
abbrev M := StateT Nat (Except String)
def repeat_example : M Nat := do
let final_loop_state ← (do
let mut loop_state := (false, 1)
repeat
let (_, n) := loop_state
let x ← get
loop_state ← pure (true, n + x)
until loop_state.1
pure loop_state.2
)
pure final_loop_state
theorem unfold_repeat : repeat_example.run 2 = .ok (3, 2) :=
by
sorry
I know this might not be idiomatic Lean, but this code is machine-generated so I can't really change it.
Aaron Liu (Jul 31 2025 at 00:01):
repeat is opaque
Aaron Liu (Jul 31 2025 at 00:02):
repeat .. until is also opaque
Aaron Liu (Jul 31 2025 at 00:02):
that means you're not allowed to unfold it
Gavin Zhao (Jul 31 2025 at 00:02):
Hmm so what would be alternatives that are not opaque but still represent loops? Maybe while?
Aaron Liu (Jul 31 2025 at 00:03):
while is also opaque
Aaron Liu (Jul 31 2025 at 00:03):
anything that lets you represent an infinite loop will usually be opaque
Gavin Zhao (Jul 31 2025 at 00:03):
repeatis opaque
I'm surprised the reference manual doesn't mention it.
Gavin Zhao (Jul 31 2025 at 00:05):
anything that lets you represent an infinite loop will usually be opaque
That makes sense. Thank you for the info! I'll have to think of other representations.
Devon Tuma (Jul 31 2025 at 01:57):
for loops unfold into List.forIn if you know the looping is bounded
Devon Tuma (Jul 31 2025 at 01:58):
Or at least loops over lists do
Gavin Zhao (Jul 31 2025 at 01:59):
Yeah, but unfortunately this one uses a boolean variable as the termination variable (i.e. repeat ... until) so that pattern doesn't hold.
Gavin Zhao (Jul 31 2025 at 02:00):
As you mentioned, for for loops over lists I did find that it can unfold it.
Last updated: Dec 20 2025 at 21:32 UTC