(* Import necessary libraries *)
Require Import List.
Import ListNotations.
Require Import Arith.
Require Import Lia.
(* Define the missing_number function *)
Definition missing_number (nums: list nat) : nat :=
let n := length nums in
let expected_sum := n * (n + 1) / 2 in
let actual_sum := fold_right plus 0 nums in
expected_sum - actual_sum.
(* Example usage *)
Compute missing_number [3; 0; 1]. (* Should compute to 2 *)
(* Theorem stating the correctness of missing_number *)
Theorem missing_number_correct:
forall (nums: list nat) (n missing: nat),
length nums = n ->
NoDup nums ->
(forall x, In x nums -> x <= n) ->
sum_list nums = (n * (n + 1)) / 2 - missing ->
missing_number nums = missing.
Proof.
intros nums n missing Hlen Hnodup Hbounds Hsum.
unfold missing_number.
rewrite Hlen.
unfold sum_list in Hsum.
rewrite Hsum.
lia.
Qed.
Explanation
Imports:
List: For list operations.
Arith: For arithmetic operations.
Lia: For linear integer arithmetic, useful in proofs.
missing_number Function:
Calculates n as the length of the list.
Computes the expected sum using the formula ( \frac{n(n + 1)}{2} ).
Calculates the actual sum of the list using fold_right.
Returns the difference as the missing number.
Example Usage:
Demonstrates the function with the list [3; 0; 1], which should return 2.
Theorem: missing_number_correct:
Parameters:
nums: The input list.
n: The length of nums.
missing: The missing number to prove.
Hypotheses:
length nums = n: The list has length n.
NoDup nums: All elements are distinct.
forall x, In x nums -> x <= n: All elements are within [0, n].
sum_list nums = (n * (n + 1)) / 2 - missing: The sum condition relates to the missing number.
Conclusion:
missing_number nums = missing: The function correctly identifies the missing number.
Proof:
Unfolds the definition of missing_number.
Substitutes the hypotheses into the expression.
Uses the lia tactic to solve the arithmetic.
Proof of Correctness
The theorem missing_number_correct formally verifies that the missing_number function correctly identifies the missing number under the specified conditions.
Proof Steps
Unfold Definitions:
Expand the definition of missing_number.
Substitute Hypotheses:
Replace length nums with n.
Replace sum_list nums with (\frac{n(n + 1)}{2} - \text{missing}).
Simplify Expression:
Show that the expected sum minus the actual sum equals the missing number.
Conclude with lia:
The lia tactic (Linear Integer Arithmetic) automatically solves the remaining arithmetic, confirming that the function's output equals the missing number.
This formal proof ensures that, given the constraints, the missing_number function reliably returns the correct missing number from the list.