Created
July 30, 2017 06:57
-
-
Save anonymous/cb61078a624d570e8a47e870ce5934b2 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
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
#[derive(Debug, Copy, Clone)] | |
enum DotError { | |
LengthMismatch | |
} | |
trait Dot<Rhs=Self> { | |
type Output; | |
fn dot(&self, other: &Rhs) -> Self::Output; | |
} | |
impl Dot for [i32; 3] { | |
type Output = i32; | |
fn dot(&self, other: &[i32; 3]) -> Self::Output { | |
self.iter().zip(other.iter()).fold(0, |acc, (&a, &b)| { | |
acc + a * b | |
}) | |
} | |
} | |
impl Dot for Vec<i32> { | |
type Output = Result<i32, DotError>; | |
fn dot(&self, other: &Vec<i32>) -> Self::Output { | |
if self.len() == other.len() { | |
let product = self.iter().zip(other.iter()).fold(0, |acc, (&a, &b)| { | |
acc + a * b | |
}); | |
Ok(product) | |
} else { | |
Err(DotError::LengthMismatch) | |
} | |
} | |
} | |
fn main() { | |
let a = [1, 2, 3]; | |
let b = [1, 2, 3]; | |
let _c = [1, 2, 3, 4]; | |
println!("{:?}", a.dot(&b)); | |
// println!("{:?}", a.dot(&_c)); // compile time error | |
let c = vec![1, 2, 3]; | |
let mut d = vec![1, 2, 3]; | |
println!("{:?}", c.dot(&d)); | |
d.push(4); | |
println!("{:?}", c.dot(&d)); // runtime error | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment