use std::fmt;
// 使用 Rust 的枚举和常量定义
const A: i32 = -125;
const X: i32 = 4;
const K_START: i32 = 1;
const K_END: i32 = 998;
// 自定义错误类型
#[derive(Debug)]
enum CalculationError {
InvalidParameter(&'static str),
ArithmeticOverflow,
}
impl fmt::Display for CalculationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CalculationError::InvalidParameter(msg) => write!(f, "Invalid parameter: {}", msg),
CalculationError::ArithmeticOverflow => write!(f, "Arithmetic operation overflowed"),
}
}
}
impl std::error::Error for CalculationError {}
// 使用泛型和 trait bound 实现更通用的 term 函数
fn term(k: K) -> i64
where
K: Into,
{
(A as i64) * (X as i64).pow(2) + (k.into() * X as i64)
}
// 使用迭代器和闭包实现更 Rust 风格的求和
fn sum_with_loop() -> Result<i64, CalculationError> {
// 验证参数
if A >= 0 {
return Err(CalculationError::InvalidParameter("A must be negative"));
}
if X.pow(2) != 16 {
return Err(CalculationError::InvalidParameter("X squared must be 16"));
}
if K_START != 1 || K_END != 998 {
return Err(CalculationError::InvalidParameter("K range must be 1..=998"));
}
// 使用迭代器求和
(K_START..=K_END)
.map(|k| term(k))
.try_fold(0i64, |acc, x| acc.checked_add(x).ok_or(CalculationError::ArithmeticOverflow))
}
// 使用数学公式实现闭式解
fn closed_form() -> Result<i64, CalculationError> {
let n = (K_END - K_START + 1) as i64;
let sum_k = n * (K_START + K_END) as i64 / 2;
let term1 = n.checked_mul(A as i64)
.and_then(|x| x.checked_mul(X as i64 * X as i64))
.ok_or(CalculationError::ArithmeticOverflow)?;
let term2 = X as i64.checked_mul(sum_k)
.ok_or(CalculationError::ArithmeticOverflow)?;
term1.checked_add(term2)
.ok_or(CalculationError::ArithmeticOverflow)
}
// 使用 trait 实现更通用的打印功能
trait ResultPrinter {
fn print_result(&self);
}
impl ResultPrinter for Result<i64, CalculationError> {
fn print_result(&self) {
match self {
Ok(value) => println!("y = {}", value),
Err(e) => eprintln!("Error: {}", e),
}
}
}
fn main() {
// 使用模式匹配验证两种方法的结果
match (sum_with_loop(), closed_form()) {
(Ok(loop_result), Ok(math_result)) => {
assert_eq!(loop_result, math_result, "Σ loop != closed form");
println!("Both methods agree: y = {}", loop_result);
}
(Err(e), ) | (, Err(e)) => eprintln!("Calculation failed: {}", e),
}
// 展示 trait 的使用
sum_with_loop().print_result();
closed_form().print_result();
// 展示 Rust 的模式匹配和错误处理
let result = sum_with_loop().and_then(|sum| {
println!("Sum calculated successfully: {}", sum);
Ok(())
});
if let Err(e) = result {
eprintln!("Final error: {}", e);
}
}