Skip to content

Instantly share code, notes, and snippets.

@dariost
Created March 15, 2017 10:48
Show Gist options
  • Save dariost/71f47baa202328617e3fadcad535ed41 to your computer and use it in GitHub Desktop.
Save dariost/71f47baa202328617e3fadcad535ed41 to your computer and use it in GitHub Desktop.
Generic scalar product in Rust
use std::default::Default;
use std::ops::{Add, Mul};
fn scalar<T: Add<Output = T> + Default>(a: &[T], b: &[T]) -> T
where for<'a> T: Mul<&'a T, Output = T>,
for<'a, 'b> &'a T: Mul<&'b T, Output = T>
{
assert_eq!(a.len(), b.len());
a.iter()
.zip(b.iter())
.map(|x| x.0 * x.1)
.fold(Default::default(), |acc, x| acc + x)
}
fn main()
{
let a = [3.0, 2.0, -1.5, 1.0];
let b = [1.0, 2.0, 3.0, -2.5];
println!("{}", scalar(&a, &b));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment