From: Ralf Jung Date: Tue, 23 Jun 2015 16:00:35 +0000 (+0200) Subject: tuning, exercises and solutions X-Git-Url: https://git.ralfj.de/rust-101.git/commitdiff_plain/e7fafa765963c465b1601ae2204564c55ee11571?ds=sidebyside;hp=5e5b934f2df7852e021c6cc3f89e313a08345560 tuning, exercises and solutions --- diff --git a/solutions/src/vec.rs b/solutions/src/vec.rs new file mode 100644 index 0000000..8eff916 --- /dev/null +++ b/solutions/src/vec.rs @@ -0,0 +1,127 @@ +pub mod part01 { + use std; + + /// A number, or nothing + pub enum NumberOrNothing { + Number(i32), + Nothing + } + use self::NumberOrNothing::{Number,Nothing}; + + /// Compute the minimum element of the vector + pub fn vec_min(v: Vec) -> NumberOrNothing { + let mut min = Nothing; + for e in v { + min = Number(match min { + Nothing => e, + Number(n) => std::cmp::min(n, e) + }); + } + min + } + + /// Compute the sum of elements in the vector + pub fn vec_sum(v: Vec) -> i32 { + let mut sum = 0; + for e in v { + sum += e; + } + sum + } + + /// Print all elements in the vector + pub fn vec_print(v: Vec) { + for e in v { + println!("{}", e) + } + } +} + +pub mod part0203 { + // A polymorphic (generic) "some value, or no value" + pub enum SomethingOrNothing { + Something(T), + Nothing, + } + pub use self::SomethingOrNothing::*; + type NumberOrNothing = SomethingOrNothing; + + /// This trait is used to compute the minimum of two elements of the given type + pub trait Minimum : Copy { + fn min(self, b: Self) -> Self; + } + + /// Return the minimum element of the vector + pub fn vec_min(v: Vec) -> SomethingOrNothing { + let mut min = Nothing; + for e in v { + min = Something(match min { + Nothing => e, + Something(n) => e.min(n) + }); + } + min + } + + /// We can compute the minimum of two integers + impl Minimum for i32 { + fn min(self, b: Self) -> Self { + if self < b { self } else { b } + } + } + + /// Sample program to call vec_min + impl NumberOrNothing { + pub fn print(self) { + match self { + Nothing => println!("The number is: "), + Something(n) => println!("The number is: {}", n), + }; + } + } + fn read_vec() -> Vec { + vec![18,5,7,3,9,27] + } + pub fn main_i32() { + let vec = read_vec(); + let min = vec_min(vec); + min.print(); + } + + // Now, all the same for calling it on f32 + impl Minimum for f32 { + fn min(self, b: Self) -> Self { + if self < b { self } else { b } + } + } + + impl SomethingOrNothing { + pub fn print_f32(self) { + match self { + Nothing => println!("The number is: "), + Something(n) => println!("The number is: {}", n), + }; + } + } + + fn read_vec_f32() -> Vec { + vec![18.01,5.2,7.1,3.,9.2,27.123] + } + pub fn main_f32() { + let vec = read_vec_f32(); + let min = vec_min(vec); + min.print_f32(); + } + + /// Add a `Display` implementation to `SomethingOrNothing` + use std::fmt; + impl fmt::Display for SomethingOrNothing { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Something(ref t) => t.fmt(f), + Nothing => "Nothing".fmt(f), + } + } + } +} + diff --git a/src/part05.rs b/src/part05.rs index 03c10d3..84f14ff 100644 --- a/src/part05.rs +++ b/src/part05.rs @@ -110,6 +110,9 @@ impl Clone for SomethingOrNothing { // Again, Rust will generate this implementation automatically if you add // `#[derive(Clone)]` right before the definition of `SomethingOrNothing`. +// **Exercise 05.2**: Write some more functions on `BigInt`. What about a function that returns the number of +// digits? The number of non-zero digits? The smallest/largest digit? + // ## Mutation + aliasing considered harmful (part 2) // Now that we know how to borrow a part of an `enum` (like `v` above), there's another example for why we // have to rule out mutation in the presence of aliasing. First, we define an `enum` that can hold either diff --git a/src/part06.rs b/src/part06.rs index e159ca5..e357d0e 100644 --- a/src/part06.rs +++ b/src/part06.rs @@ -25,7 +25,8 @@ impl BigInt { } } -// Now we can write `vec_min`. In order to make it type-check, we have make a deep copy of e. +// Now we can write `vec_min`. However, in order to make it type-check, we have to make a full (deep) copy of e +// by calling `clone()`. fn vec_min(v: &Vec) -> Option { let mut min: Option = None; for e in v { diff --git a/src/part07.rs b/src/part07.rs index 65d6823..85fe071 100644 --- a/src/part07.rs +++ b/src/part07.rs @@ -13,7 +13,7 @@ pub trait Minimum { // Now we can implement a generic function `vec_min` that works on above trait. // The code is pretty much straight-forward, and Rust checks that all the -// lifetimes actually work out. +// lifetimes actually work out. Observe that we don't have to make any copies! pub fn vec_min(v: &Vec) -> Option<&T> { let mut min: Option<&T> = None; for e in v { @@ -33,8 +33,9 @@ pub fn vec_min(v: &Vec) -> Option<&T> { // as `NULL`. This is another great example of a zero-cost abstraction: `Option<&T>` is exactly like // a pointer in C(++), if you look at what happens during execution - but it's much safer to use. -// For our `vec_min` to be usable with `BigInt`, we need to provide an implementation of -// `Minimum`. You should be able to pretty much copy the code you wrote for exercise 06.1. +// **Exercise 07.1**: For our `vec_min` to be usable with `BigInt`, you will have to provide an implementation of +// `Minimum`. You should be able to pretty much copy the code you wrote for exercise 06.1. You should *not* +// make any copies! impl Minimum for BigInt { fn min<'a>(&'a self, other: &'a Self) -> &'a Self { unimplemented!() @@ -43,12 +44,13 @@ impl Minimum for BigInt { // ## Operator Overloading // How can we know that our `min` function actually does what we want it to do? One possibility -// here is to do *testing*. Rust comes with nice build-in support for both unit tests and integration +// here is to do *testing*. Rust comes with nice built-in support for both unit tests and integration // tests. However, before we go there, we need to have a way of checking whether the results of function calls are // correct. In other words, we need to define how to test equality of `BigInt`. Being able to // test equality is a property of a type, that - you guessed it - Rust expresses as a trait: `PartialEq`. -// Doing this for `BigInt` is fairly easy, thanks to our requirement that there be no trailing zeros. +// Doing this for `BigInt` is fairly easy, thanks to our requirement that there be no trailing zeros. We simply +// re-use the equality test on vectors, which compares all the elements individually. // The `inline` attribute tells Rust that we will typically want this function to be inlined. impl PartialEq for BigInt { #[inline] @@ -62,7 +64,8 @@ impl PartialEq for BigInt { // the "partial", I suggest you check out the documentation of [`PartialEq`](http://doc.rust-lang.org/std/cmp/trait.PartialEq.html) // and [`Eq`](http://doc.rust-lang.org/std/cmp/trait.Eq.html). `Eq` can be automatically derived as well. -// Now we can compare `BigInt`s using `==`! Speaking in C++ terms, we just overloaded the `==` operator +// Now we can compare `BigInt`s. Rust treats `PratialEq` special in that it is wired to the operator `==`: +// That operator can not be used on our numbers! Speaking in C++ terms, we just overloaded the `==` operator // for `BigInt`. Rust does not have function overloading (i.e., it will not dispatch to different // functions depending on the type of the argument). Instead, one typically finds (or defines) a // trait that catches the core characteristic common to all the overloads, and writes a single @@ -73,6 +76,13 @@ impl PartialEq for BigInt { // that trait to be immediately usable with all the functions out there that generalize over `ToString`. // Compare that to C++ or Java, where the only chance to add a new overloading variant is to // edit the class of the receiver. +// +// Why can we also use `!=`, even though we just overloaded `==`? The answer lies in what's called a *default implementation*. +// If you check out the documentation of `PartialEq` I linked above, you will see that the trait actually provides +// two methods: `eq` to test equality, and `ne` to test inequality. As you may have guessed, `!=` is wired to `ne`. +// The trait *definition* also provides a default implementation of `ne` to be the negation of `eq`. Hence you can just +// provide `eq`, and `!=` will work fine. Or, if you have a more efficient way of deciding inequality, you can provide +// `ne` for your type yourself. fn compare_big_ints() { let b1 = BigInt::new(13); let b2 = BigInt::new(37); @@ -133,6 +143,7 @@ fn test_vec_min() { // trailing zeros). Finally, break one of your functions in a subtle way and watch the test fail. // // **Exercise 07.2**: Go back to your good ol' `SomethingOrNothing`, and implement `Display` for it. (This will, -// of course, need a `Display` bound on `T`.) Then you should be able to use them with `println!` just like you do with numbers. +// of course, need a `Display` bound on `T`.) Then you should be able to use them with `println!` just like you do +// with numbers, and get rid of the inherent functions to print `SomethingOrNothing` and `SomethingOrNothing`. // [index](main.html) | [previous](part06.html) | [next](main.html) diff --git a/workspace/.gitignore b/workspace/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/workspace/.gitignore @@ -0,0 +1 @@ +target/