Comprehensive collection of algorithms and data structures with well-documented loop invariants for correctness reasoning
///|
test "doc example runs" {
debug_inspect(1 + 1, content="2")
}"After processing the first i elements, sum equals their total."
///|
test "invariant sum example" {
let xs : Array[Int] = [1, 2, 3, 4]
let n = xs.length()
let total = for i = 0, sum = 0; i < n; {
continue i + 1, sum + xs[i]
} {
sum
} {
proof_invariant: 0 <= i && i <= n,
proof_reasoning: "sum equals the total of xs[0..i).",
}
debug_inspect(total, content="10")
}"best is the maximum of elements seen so far."
///|
test "invariant max example" {
let xs : Array[Int] = [2, 7, 1, 5]
let n = xs.length()
let best = for i = 0, best = xs[0]; i < n; {
let v = xs[i]
continue i + 1, if v > best { v } else { best }
} {
best
} {
proof_invariant: 0 <= i && i <= n,
proof_reasoning: "best is max of xs[0..i).",
}
debug_inspect(best, content="7")
}///|
test "simple loop example" {
let xs : Array[Int] = [1, 2, 3]
let sum = for v in xs; sum = 0 {
continue sum + v
} {
sum
}
debug_inspect(sum, content="6")
}moon check
moon test
moon info
moon fmt
moon run cmd/mainComprehensive collection of algorithms and data structures with well-documented loop invariants for correctness reasoning