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.
Code
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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.