Dot Product With Zip And Sum

Score two vectors with zip and sum: paired multiplications fold into one total, and mismatched lengths return None before any math.

RustData Integrity

Code

snippet
fn dot_product(a: &[f64], b: &[f64]) -> Option<f64> {
    // 长度不一致没有定义:先拒绝,而不是让 zip 静默截断
    if a.len() != b.len() {
        return None;
    }
    // zip 配对相乘,sum 一次归并出总分
    Some(a.iter().zip(b).map(|(x, y)| x * y).sum())
}

fn main() {
    let doc = [1.0, 2.0, 0.5];
    let query = [0.5, 1.5, 2.0];

    let score = dot_product(&doc, &query).expect("same length");
    println!("score: {score}");

    let short = [1.0, 2.0];
    println!("mismatch: {:?}", dot_product(&doc, &short));
}

Inside the snippet

The snippet is organized around the functions dot_product and main.

Putting it to use

The primary signature is fn dot_product(a: &[f64], b: &[f64]) -> Option<f64>

The demo output is labeled (score:, mismatch:), so every printed line maps back to its originating operation.

Running the file executes main, which drives dot_product in order.

Core lines

Some(a.iter().zip(b).map(|(x, y)| x * y).sum())
}

Interactive Tools for This Topic

FAQ

What does Dot Product With Zip And Sum print when run?
Run it as a complete program — the output lines carry labels such as `score:`, `mismatch:`.