SHARE
TWEET

Untitled

a guest Mar 19th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extern crate num_traits;
  2.  
  3. fn generic_scalar_product<T>(v: &[T], w: &[T]) -> Result<T,String>
  4. where
  5.     T: num_traits::Zero + std::ops::Mul<Output = T> + Copy
  6. {
  7.     let length = v.len();
  8.    
  9.     if length != w.len() {
  10.         return Err("The vectors have different lengths!".to_string());
  11.     }
  12.    
  13.     // We initialise `sum` to a "zero" of type T
  14.     // using the `zero` method provided by the `Zero` trait
  15.     let mut sum = T::zero();
  16.     for index in 0..length {
  17.         sum = sum + v[index] * w[index];
  18.     }
  19.     Ok(sum)
  20. }
  21.  
  22. fn main() {
  23.     // Unsigned integers
  24.     let x: Vec<u32> = vec![1, 1, 1];
  25.     let y: Vec<u32> = vec![1, 0, 1];
  26.     assert_eq!(generic_scalar_product(&x, &y).unwrap(), 2);
  27. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top