|
| 1 | +# Enum(eration)s |
| 2 | + |
| 3 | +::: callout-tip |
| 4 | +## Objective |
| 5 | + |
| 6 | +Understand what `enum`s are and when you may want to use one. |
| 7 | + |
| 8 | +::: |
| 9 | + |
| 10 | +Oftentimes a variable can only take on a small number of values. This is when an **enumeration** (enum) would be useful. |
| 11 | + |
| 12 | +`enum`s are values that can only take on a select few **variants**. They are defined using the `enum` keyword. |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +## Enums in R |
| 17 | + |
| 18 | +We use enums _all the time_ in R and almost exclusively as function arguments. |
| 19 | + |
| 20 | +::: aside |
| 21 | +The tidyverse design style guide has a great section on enums. See [enumerate options](https://design.tidyverse.org/enumerate-options.html#whats-the-pattern). |
| 22 | +::: |
| 23 | + |
| 24 | +```r |
| 25 | +args(cor) |
| 26 | +``` |
| 27 | +```r |
| 28 | +function( |
| 29 | + x, y = NULL, use = "everything", |
| 30 | + method = c("pearson", "kendall", "spearman") # 👈🏼 enum! |
| 31 | +) |
| 32 | +``` |
| 33 | + |
| 34 | +::: aside |
| 35 | +I've written about this in more detail in my blog post [Enums in R: towards type safe R](https://josiahparry.com/posts/2023-11-10-enums-in-r/) |
| 36 | +::: |
| 37 | + |
| 38 | +### Example |
| 39 | + |
| 40 | +For example, it may make sense to create an `enum` that specifies a possible shape. |
| 41 | + |
| 42 | +```rust |
| 43 | +enum Shape { |
| 44 | + Triangle, |
| 45 | + Rectangle, |
| 46 | + Pentagon, |
| 47 | + Hexagon, |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +## Variant-specific behavior |
| 52 | + |
| 53 | +The `Shape` enum can take on only one of those 4 **variants**. An enum is created using the format `EnumName::Variant`. |
| 54 | + |
| 55 | +How do we actually determine behavior based on a variant? This is done using **pattern matching**. |
| 56 | + |
| 57 | +The keyword `match` lets us perform an action based on an enum's variant. It works by listing each variant and the behavior to that happens when that variant is matched. |
| 58 | + |
| 59 | +The pattern match format uses the syntax `Enum::Variant => action`. When using `match` each variant much be _enumerated_: |
| 60 | + |
| 61 | +::: aside |
| 62 | +`=>` is often referred to as "fat arrow." But if you say "chompky" I'll also get it. |
| 63 | +::: |
| 64 | + |
| 65 | +```rust |
| 66 | +match my_shape { |
| 67 | + Shape::Triangle => todo!(), |
| 68 | + Shape::Rectangle => todo!(), |
| 69 | + Shape::Pentagon => todo!(), |
| 70 | + Shape::Hexagon => todo!(), |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +::: callout-tip |
| 75 | +todo!() is a placeholder that can be used to make the compiler happy |
| 76 | +::: |
| 77 | + |
| 78 | + |
| 79 | +### Example |
| 80 | + |
| 81 | +For example we may want to print the number of verticies of a shape: |
| 82 | + |
| 83 | +```rust |
| 84 | +let my_shape = Shape::Triangle; |
| 85 | + |
| 86 | +match my_shape { |
| 87 | + Shape::Triangle => println!("A triangle has 3 vertices"), |
| 88 | + Shape::Rectangle => println!("A rectangle has 4 vertices"), |
| 89 | + Shape::Pentagon => println!("A pentagon has 5 vertices"), |
| 90 | + Shape::Hexagon => println!("A hexagon has 6 vertices"), |
| 91 | +} |
| 92 | +``` |
| 93 | + |
| 94 | +## Wildcard matching |
| 95 | + |
| 96 | +Sometimes we want to customize behavior on only a subset of variants. We can use a catch all in the match statement `_ =>` use the underscore to signify "everything else". |
| 97 | + |
| 98 | +```rust |
| 99 | +match my_shape { |
| 100 | + Shape::Hexagon => println!("Hexagons are the bestagons"), |
| 101 | + _ => println!("Every other polygon is mid"), |
| 102 | +} |
| 103 | +``` |
| 104 | + |
| 105 | +## Enums can `impl`, too |
| 106 | + |
| 107 | +Enums can have methods too just like a struct using `impl` keyword |
| 108 | + |
| 109 | +```rust |
| 110 | +impl Shape { |
| 111 | + fn is_bestagon(&self) -> bool { |
| 112 | + match self { |
| 113 | + Self::Hexagon => true, |
| 114 | + _ => false |
| 115 | + } |
| 116 | + } |
| 117 | +} |
| 118 | +``` |
| 119 | + |
| 120 | + |
| 121 | +## Exercise 1 |
| 122 | + |
| 123 | +- Create an enum called `Measure` with two variants `Euclidean` and `Haversine` |
| 124 | +- Create a method called `ndim()` which returns `2` for `Euclidean` and `3` for `Haversine` |
| 125 | + |
| 126 | +<details> |
| 127 | + <summary>View solution</summary> |
| 128 | + |
| 129 | +```rust |
| 130 | +enum Measure { |
| 131 | + Euclidean, |
| 132 | + Haversine, |
| 133 | +} |
| 134 | + |
| 135 | +impl Measure { |
| 136 | + fn ndim(&self) -> i32 { |
| 137 | + match self { |
| 138 | + Self::Euclidean => 2, |
| 139 | + Self::Haversine => 3 |
| 140 | + } |
| 141 | + } |
| 142 | +} |
| 143 | +``` |
| 144 | + |
| 145 | +</details> |
| 146 | + |
| 147 | +## Exercise 2 |
| 148 | + |
| 149 | + |
| 150 | +- Create a new method `distance()` for `Point` struct that returns an `f64` |
| 151 | + - Arguments: `&self`, `destination: &Self`, `measure: &Measure` |
| 152 | +- When `measure` is `Euclidean` use the `euclidean_distance()` method |
| 153 | +- When the variant is `Haversine` use the `haversine_distance()` method |
| 154 | + |
| 155 | +The haversine method is defined as: |
| 156 | + |
| 157 | +<details> |
| 158 | +<summary>Code for `haversine_distance()` </summary> |
| 159 | +```rust |
| 160 | +impl Point { |
| 161 | + fn haversine_distance(&self, destination: &Self) -> f64 { |
| 162 | + let radius = 6_371_008.7714; // Earth's mean radius in meters |
| 163 | + let theta1 = self.y.to_radians(); // Latitude of point 1 |
| 164 | + let theta2 = destination.y.to_radians(); // Latitude of point 2 |
| 165 | + let delta_theta = (destination.y - self.y).to_radians(); // Delta Latitude |
| 166 | + let delta_lambda = (destination.x - self.x).to_radians(); // Delta Longitude |
| 167 | + |
| 168 | + let a = (delta_theta / 2f64).sin().powi(2) |
| 169 | + + theta1.cos() * theta2.cos() * (delta_lambda / 2f64).sin().powi(2); |
| 170 | + |
| 171 | + 2f64 * a.sqrt().asin() * radius |
| 172 | + } |
| 173 | +} |
| 174 | +``` |
| 175 | + |
| 176 | +</details> |
| 177 | + |
| 178 | + |
| 179 | +<details> |
| 180 | +<summary>View solution</summary> |
| 181 | +```rust |
| 182 | + |
| 183 | +impl Point { |
| 184 | + // Demonstrates using pattern matching an enum |
| 185 | + fn distance(&self, destination: &Self, measure: &Measure) -> f64 { |
| 186 | + match measure { |
| 187 | + Measure::Euclidean => self.euclidean_distance(destination), |
| 188 | + Measure::Haversine => self.haversine_distance(destination), |
| 189 | + } |
| 190 | + } |
| 191 | +} |
| 192 | +``` |
0 commit comments