Add solutions for sheet6

This commit is contained in:
Lukas Kalbertodt
2016-12-05 17:57:47 +01:00
parent 509cdd453d
commit 08a4b2fccc
7 changed files with 197 additions and 0 deletions

View File

@ -0,0 +1,7 @@
[package]
name = "sol2"
version = "0.1.0"
authors = ["Lukas Kalbertodt <lukas.kalbertodt@gmail.com>"]
[dependencies]
num-traits = "0.1"

59
aufgaben/sheet6/sol2/src/lib.rs Executable file
View File

@ -0,0 +1,59 @@
extern crate num_traits;
use num_traits::{Zero, One};
use std::ops;
#[cfg(test)]
mod tests;
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Vector2<T> {
pub x: T,
pub y: T,
}
impl<T> Vector2<T> {
pub fn new(x: T, y: T) -> Self {
Vector2 {
x: x,
y: y,
}
}
}
impl<T: Zero> Vector2<T> {
pub fn origin() -> Self {
Self::new(T::zero(), T::zero())
}
}
impl<T: Zero + One> Vector2<T> {
pub fn unit_x() -> Self {
Self::new(T::one(), T::zero())
}
pub fn unit_y() -> Self {
Self::new(T::zero(), T::one())
}
}
impl<T, U> ops::Add<Vector2<U>> for Vector2<T>
where T: ops::Add<U>
{
type Output = Vector2<T::Output>;
fn add(self, rhs: Vector2<U>) -> Self::Output {
Vector2::new(self.x + rhs.x, self.y + rhs.y)
}
}
impl<T, U> ops::Mul<U> for Vector2<T>
where T: ops::Mul<U>,
U: Clone
{
type Output = Vector2<T::Output>;
fn mul(self, rhs: U) -> Self::Output {
Vector2::new(self.x * rhs.clone(), self.y * rhs)
}
}

View File

@ -0,0 +1,18 @@
use Vector2;
#[test]
fn constructors() {
assert_eq!(Vector2::new(27, 42), Vector2 { x: 27, y: 42 });
assert_eq!(Vector2::origin(), Vector2 { x: 0, y: 0 });
assert_eq!(Vector2::unit_x(), Vector2 { x: 1, y: 0 });
assert_eq!(Vector2::unit_y(), Vector2 { x: 0, y: 1 });
}
#[test]
fn operators() {
let a = Vector2::new(3, 7);
let b = Vector2::new(-2, 5);
assert_eq!(a + b, Vector2::new(1, 12));
assert_eq!(a * 2, Vector2::new(6, 14));
}