complex: Update for 2nd edition.

pull/13/head
Jim Blandy 3 years ago
parent 88dbb7c344
commit 2927097382

@ -2,5 +2,6 @@
name = "complex" name = "complex"
version = "0.1.0" version = "0.1.0"
authors = ["You <you@example.com>"] authors = ["You <you@example.com>"]
edition = "2018"
[dependencies] [dependencies]

@ -1,192 +1,268 @@
#[derive(Clone, Copy, Debug)] //! Complex number examples.
struct Complex<T> { //!
/// Real portion of the complex number //! The chapter presents several different variations on how one might define
re: T, //! arithmetic on a generic `Complex` type, so what we have here are a bunch of
//! isolated modules, each of which defines its own `Complex` type in its own
//! way. The `first_cut` module is the most well-developed.
//!
//! If you actually need a `Complex` type for real use, consider the
//! `num_complex` crate, whose `Complex` type is incorporated into the `num`
//! crate.
/// Imaginary portion of the complex number macro_rules! define_complex {
im: T () => {
#[derive(Clone, Copy, Debug)]
struct Complex<T> {
/// Real portion of the complex number
re: T,
/// Imaginary portion of the complex number
im: T,
}
};
} }
use std::ops::Add; mod first_cut {
use std::ops::Mul; #[derive(Clone, Copy, Debug)]
struct Complex<T> {
/// Real portion of the complex number
re: T,
#[cfg(skip)] /// Imaginary portion of the complex number
impl Add for Complex<i32> { im: T,
type Output = Complex<i32>;
fn add(self, rhs: Self) -> Self {
Complex { re: self.re + rhs.re, im: self.im + rhs.im }
} }
}
impl<T> Add for Complex<T> use std::ops::Add;
where T: Add<Output=T>
{ impl<T> Add for Complex<T>
type Output = Self; where
fn add(self, rhs: Self) -> Self { T: Add<Output = T>,
Complex { re: self.re + rhs.re, im: self.im + rhs.im } {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Complex {
re: self.re + rhs.re,
im: self.im + rhs.im,
}
}
} }
}
#[cfg(skip)] use std::ops::Sub;
impl<L, R, O> Add<Complex<R>> for Complex<L>
where L: Add<R, Output=O> impl<T> Sub for Complex<T>
{ where
type Output = Complex<O>; T: Sub<Output = T>,
fn add(self, rhs: Complex<R>) -> Self::Output { {
Complex { re: self.re + rhs.re, im: self.im + rhs.im } type Output = Self;
fn sub(self, rhs: Self) -> Self {
Complex {
re: self.re - rhs.re,
im: self.im - rhs.im,
}
}
} }
}
#[cfg(skip)] use std::ops::Mul;
impl<'a, P, Rhs> Add for &'a Complex<P>
where P: Add<Output=P>, impl<T> Mul for Complex<T>
Rhs: AsRef<Complex<P>> where
{ T: Clone + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
type Output = Complex<P>; {
fn add(self, rhs: Rhs) -> Self::Output { type Output = Self;
let rhs = rhs.as_ref(); fn mul(self, rhs: Self) -> Self {
Complex { re: self.re + rhs.re, im: self.im + rhs.im } Complex {
re: self.re.clone() * rhs.re.clone()
- (self.im.clone() * rhs.im.clone()),
im: self.im * rhs.re + self.re * rhs.im,
}
}
}
#[test]
fn try_it_out() {
let mut z = Complex { re: 1, im: 2 };
let c = Complex { re: 3, im: 4 };
z = z * z + c;
std::mem::forget(z);
} }
}
use std::ops::Sub; impl<T: PartialEq> PartialEq for Complex<T> {
fn eq(&self, other: &Complex<T>) -> bool {
self.re == other.re && self.im == other.im
}
}
impl<T> Mul<Complex<T>> for Complex<T> #[test]
where T: Add<Output=T> + Sub<Output=T> + Mul<Output=T> + Copy fn test_complex_eq() {
{ let x = Complex { re: 5, im: 2 };
type Output = Self; let y = Complex { re: 2, im: 5 };
fn mul(self, rhs: Self) -> Self { assert_eq!(x * y, Complex { re: 0, im: 29 });
Complex { re: self.re * rhs.re - self.im * rhs.im,
im: self.re * rhs.im + self.im * rhs.re }
} }
}
#[test] impl<T: Eq> Eq for Complex<T> {}
fn test() {
let z = Complex { re: -2, im: 6 };
let c = Complex { re: 1, im: 2 };
assert_eq!(z + c, Complex { re: -1, im: 8 });
assert_eq!(z * c, Complex { re: -14, im: 2 });
assert_eq!(z.add(c), Complex { re: -1, im: 8 });
} }
#[test] mod non_generic_add {
fn test_explicit() { define_complex!();
use std::ops::Add;
assert_eq!(4.125f32.add(5.75), 9.875); use std::ops::Add;
assert_eq!(10.add(20), 10 + 20);
}
impl Add<Complex<f64>> for f64 { impl Add for Complex<i32> {
type Output = Complex<f64>; type Output = Complex<i32>;
fn add(self, rhs: Complex<f64>) -> Complex<f64> { fn add(self, rhs: Self) -> Self {
Complex { re: rhs.re + self, im: rhs.im } Complex {
re: self.re + rhs.re,
im: self.im + rhs.im,
}
}
} }
} }
#[test] mod somewhat_generic {
fn add_complex_to_real() { define_complex!();
assert_eq!(30f64 + Complex { re: 10.0f64, im: 20.0 },
Complex { re: 40.0, im: 20.0 });
}
use std::ops::Neg; use std::ops::Add;
impl<T, O> Neg for Complex<T> impl<T> Add for Complex<T>
where T: Neg<Output=O> where
{ T: Add<Output = T>,
type Output = Complex<O>; {
fn neg(self) -> Complex<O> { type Output = Self;
Complex { re: -self.re, im: -self.im } fn add(self, rhs: Self) -> Self {
Complex {
re: self.re + rhs.re,
im: self.im + rhs.im,
}
}
} }
}
#[test] use std::ops::Neg;
fn negate_complex() {
let z = Complex { re: 3, im: 4 }; impl<T> Neg for Complex<T>
assert_eq!(-z, Complex { re: -3, im: -4 }); where
T: Neg<Output = T>,
{
type Output = Complex<T>;
fn neg(self) -> Complex<T> {
Complex {
re: -self.re,
im: -self.im,
}
}
}
} }
use std::ops::AddAssign; mod very_generic {
define_complex!();
use std::ops::Add;
impl<T> AddAssign for Complex<T> impl<L, R> Add<Complex<R>> for Complex<L>
where T: AddAssign<T> where
{ L: Add<R>,
fn add_assign(&mut self, rhs: Complex<T>) { {
self.re += rhs.re; type Output = Complex<L::Output>;
self.im += rhs.im; fn add(self, rhs: Complex<R>) -> Self::Output {
Complex {
re: self.re + rhs.re,
im: self.im + rhs.im,
}
}
} }
} }
#[test] mod impl_compound {
fn compound_assignment() { define_complex!();
let mut z = Complex { re: 5, im: 6 };
z += Complex { re: 7, im: 8 }; use std::ops::AddAssign;
assert_eq!(z, Complex { re: 12, im: 14 });
let mut title = "Love".to_string(); impl<T> AddAssign for Complex<T>
title += ", Actually"; where
assert_eq!(title, "Love, Actually"); T: AddAssign<T>,
{
fn add_assign(&mut self, rhs: Complex<T>) {
self.re += rhs.re;
self.im += rhs.im;
}
}
} }
impl<T: PartialEq> PartialEq for Complex<T> { mod derive_partialeq {
fn eq(&self, other: &Complex<T>) -> bool { #[derive(Clone, Copy, Debug, PartialEq)]
self.re == other.re && self.im == other.im struct Complex<T> {
re: T,
im: T,
} }
} }
impl<T: Eq> Eq for Complex<T> { } mod derive_everything {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Complex<T> {
/// Real portion of the complex number
re: T,
#[test] /// Imaginary portion of the complex number
fn comparison() { im: T,
let x = Complex { re: 5, im: 2 }; }
let y = Complex { re: 2, im: 5 };
assert_eq!(x * y, Complex { re: 0, im: 29 });
} }
use std::fmt; /// Examples from Chapter 17, Strings and Text
///
/// These use a separate, non-generic `Complex` type, for simplicity.
mod formatting {
#[test]
fn complex() {
#[derive(Copy, Clone, Debug)]
struct Complex { re: f64, im: f64 }
// To make the formatting examples mesh with the rest of this file, I've adapted let third = Complex { re: -0.5, im: f64::sqrt(0.75) };
// them to work on the type `Complex<f64>`, where the book simply defines a new println!("{:?}", third);
// non-generic `Complex` type. The only changes are adding `<f64>`, and changing
// the field names.
#[cfg(skip)] use std::fmt;
impl fmt::Display for Complex<f64> {
fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result {
let i_sign = if self.i < 0.0 { '-' } else { '+' };
write!(dest, "{} {} {}i", self.r, i_sign, f64::abs(self.i))
}
}
impl fmt::Display for Complex<f64> { impl fmt::Display for Complex {
fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result {
let (r, i) = (self.re, self.im); let im_sign = if self.im < 0.0 { '-' } else { '+' };
if dest.alternate() { write!(dest, "{} {} {}i", self.re, im_sign, f64::abs(self.im))
let abs = f64::sqrt(r * r + i * i); }
let angle = f64::atan2(i, r) / std::f64::consts::PI * 180.0;
write!(dest, "{} ∠ {}°", abs, angle)
} else {
let i_sign = if i < 0.0 { '-' } else { '+' };
write!(dest, "{} {} {}i", r, i_sign, f64::abs(i))
} }
let one_twenty = Complex { re: -0.5, im: 0.866 };
assert_eq!(format!("{}", one_twenty),
"-0.5 + 0.866i");
let two_forty = Complex { re: -0.5, im: -0.866 };
assert_eq!(format!("{}", two_forty),
"-0.5 - 0.866i");
} }
}
#[test] #[test]
fn custom_display_impl() { fn complex_fancy() {
let one_twenty = Complex { re: -0.5, im: 0.866 }; #[derive(Copy, Clone, Debug)]
assert_eq!(format!("{}", one_twenty), struct Complex { re: f64, im: f64 }
"-0.5 + 0.866i");
use std::fmt;
let two_forty = Complex { re: -0.5, im: -0.866 };
assert_eq!(format!("{}", two_forty), impl fmt::Display for Complex {
"-0.5 - 0.866i"); fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result {
let (re, im) = (self.re, self.im);
let ninety = Complex { re: 0.0, im: 2.0 }; if dest.alternate() {
assert_eq!(format!("{}", ninety), let abs = f64::sqrt(re * re + im * im);
"0 + 2i"); let angle = f64::atan2(im, re) / std::f64::consts::PI * 180.0;
assert_eq!(format!("{:#}", ninety), write!(dest, "{} ∠ {}°", abs, angle)
"2 ∠ 90°"); } else {
let im_sign = if im < 0.0 { '-' } else { '+' };
write!(dest, "{} {} {}i", re, im_sign, f64::abs(im))
}
}
}
let ninety = Complex { re: 0.0, im: 2.0 };
assert_eq!(format!("{}", ninety),
"0 + 2i");
assert_eq!(format!("{:#}", ninety),
"2 ∠ 90°");
}
} }

Loading…
Cancel
Save