Created
March 15, 2017 10:48
-
-
Save dariost/71f47baa202328617e3fadcad535ed41 to your computer and use it in GitHub Desktop.
Generic scalar product in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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