Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How would I solve the following problem? ## Operator overloading A common use of traits is to [overload operators](https://doc.rust-lang.org/book/operators-and-overloading.html). This is an example of polymorphism

How would I solve the following problem? ## Operator overloading A common use of traits is to [overload operators](https://doc.rust-lang.org/book/operators-and-overloading.html). This is an example of polymorphism in object-oriented paradigm. It allows you define existing operators on your custom types. ## Example The following program overloads the `+`, `-`, and `*` operators and implements the `Display` trait on the `Complex` type. ``` use std::{ops, fmt}; #[derive(PartialEq, Debug)] pub struct Complex { re: T, im: T, } impl> ops::Add for Complex { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Complex { re: self.re + rhs.re, im: self.im + rhs.im, } } } impl> ops::Sub for Complex { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { Complex { re: self.re - rhs.re, im: self.im - rhs.im, } } } impl + ops::Sub + ops::Mul + Copy> ops::Mul for Complex { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { Complex{ re: self.re * rhs.re - self.im * rhs.im, im: self.re * rhs.im + self.im * rhs.re } } } impl fmt::Display for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}{:+}j", self.re, self.im) } } #[cfg(test)] mod tests { use super::*; #[test] fn test0() { let x = Complex{ re: 1, im: 2 } + Complex{ re: -2, im: -3 } * Complex{ re: 2, im: 3 }; assert_eq!(x, Complex{ re: 6, im: -10 }); } #[test] fn test1() { let x = Complex{ re: 1.0, im: 2.0 } + Complex{ re: -2.0, im: -3.0 } * Complex{ re: 2.0, im: 3.0 }; assert_eq!(x, Complex{ re: 6.0, im: -10.0 }); } #[test] fn test2() { assert_eq!(format!("{}", Complex{ re: 1, im: -2 }), "1-2j"); assert_eq!(format!("{}", Complex{ re: -1, im: 2 }), "-1+2j"); } } ``` ## Matrix You will define a `Matrix` type, overload the `+`, `-`, and `*` operators, and implement the `Display` trait on it by providing the following API: ``` use std::{ops, fmt}; #[derive(PartialEq, Debug)] pub struct Matrix { /// Stores elements in [row-major order](https://en.wikipedia.org/wiki/Row-major_order) data: Vec, /// Number of rows row: usize, /// Number of columns col: usize, } impl Matrix { /// Creates a new matrix of `row` rows and `col` columns, and initializes /// the matrix with the elements in `values` in row-major order. pub fn new(row: usize, col: usize, values: &[T]) -> Matrix { unimplemented!(); } /// Creates a new, empty matrix of `row` rows and `col` columns. /// `data` contains no element. pub fn new_empty(row: usize, col: usize) -> Matrix { unimplemented!(); } /// Returns a shared reference to `data` pub fn data(&self) -> &Vec { unimplemented!(); } /// Returns a mutable reference to `data` pub fn mut_data(&mut self) -> &mut Vec { unimplemented!(); } /// Returns the number of rows and columns in the first and second /// elements of the tuple, respectively. pub fn size(&self) -> (usize, usize) { unimplemented!(); } } impl<'a, T: ops::Add + Copy> ops::Add for &'a Matrix { type Output = Matrix; /// Returns the sum of `self` and `rhs`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn add(self, rhs: Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Add + Copy> ops::Add> for &'a Matrix { type Output = Matrix; /// Returns the sum of `self` and `rhs`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn add(self, rhs: Matrix) -> Self::Output { unimplemented!(); } } impl + Copy> ops::Add for Matrix { type Output = Self; /// Returns the sum of `self` and `rhs`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn add(self, rhs: Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Add + Copy> ops::Add<&'a Self> for Matrix { type Output = Self; /// Returns the sum of `self` and `rhs`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn add(self, rhs: &Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Sub + Copy> ops::Sub for &'a Matrix { type Output = Matrix; /// Returns the subtraction of `rhs` from `self`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn sub(self, rhs: Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Sub + Copy> ops::Sub> for &'a Matrix { type Output = Matrix; /// Returns the subtraction of `rhs` from `self`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn sub(self, rhs: Matrix) -> Self::Output { unimplemented!(); } } impl + Copy> ops::Sub for Matrix { type Output = Self; /// Returns the subtraction of `rhs` from `self`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn sub(self, rhs: Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Sub + Copy> ops::Sub<&'a Self> for Matrix { type Output = Self; /// Returns the subtraction of `rhs` from `self`. If `self.row != rhs.row || self.col != rhs.col`, panic. fn sub(self, rhs: &Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Add + ops::Mul + Copy> ops::Mul for &'a Matrix { type Output = Matrix; /// Returns the multiplication of `self` by `rhs`. If `self.col != rhs.row`, panic. fn mul(self, rhs: Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Add + ops::Mul + Copy> ops::Mul> for &'a Matrix { type Output = Matrix; /// Returns the multiplication of `self` by `rhs`. If `self.col != rhs.row`, panic. fn mul(self, rhs: Matrix) -> Self::Output { unimplemented!(); } } impl + ops::Mul + Copy> ops::Mul for Matrix { type Output = Self; /// Returns the multiplication of `self` by `rhs`. If `self.col != rhs.row`, panic. fn mul(self, rhs: Self) -> Self::Output { unimplemented!(); } } impl<'a, T: ops::Add + ops::Mul + Copy> ops::Mul<&'a Self> for Matrix { type Output = Self; /// Returns the multiplication of `self` by `rhs`. If `self.col != rhs.row`, panic. fn mul(self, rhs: &Self) -> Self::Output { unimplemented!(); } } impl fmt::Display for Matrix { /// Formats the matrix as follows: /// * Writes each row on a separate line. No empty lines before or after any row. /// * On each row, writes each element followed by a single space, except no space following the last element of the row. /// Outputs using `write!(f, ...)`. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unimplemented!(); } } ``` ### Tests Create comprehensive test cases for your program. Here is an example: ``` #[test] fn test() { let x = Matrix::new(2, 3, &[-2, -1, 0, 1, 2, 3]); let y = Matrix::new(2, 3, &[1, 2, 3, 4, 5, 6]); assert_eq!(&x + &y - &y, x); assert_eq!(format!("{}", x), "-2 -1 0 1 2 3 "); } ``` ## References * [Operators and overloading](https://doc.rust-lang.org/book/first-edition/operators-and-overloading.html) * [Traits](http://gradebot.org/doc/ipur/trait.html) * [Associated types](http://gradebot.org/doc/ipur/trait.html#associated-types) 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Intelligent Information And Database Systems Asian Conference Aciids 2012 Kaohsiung Taiwan March 19 21 2012 Proceedings Part 3 Lnai 7198

Authors: Jeng-Shyang Pan ,Shyi-Ming Chen ,Ngoc-Thanh Nguyen

2012th Edition

3642284922, 978-3642284922

More Books

Students also viewed these Databases questions

Question

What is paper chromatography?

Answered: 1 week ago

Question

Explain the cost of capital.

Answered: 1 week ago

Question

=+j Explain the relationship between unions and MNEs.

Answered: 1 week ago