Skip to content

Instantly share code, notes, and snippets.

Created July 30, 2017 06:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/cb61078a624d570e8a47e870ce5934b2 to your computer and use it in GitHub Desktop.
Save anonymous/cb61078a624d570e8a47e870ce5934b2 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
#[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