quiz2.rs (2780B)
1 // Let's build a little machine in the form of a function. As input, we're going 2 // to give a list of strings and commands. These commands determine what action 3 // is going to be applied to the string. It can either be: 4 // - Uppercase the string 5 // - Trim the string 6 // - Append "bar" to the string a specified amount of times 7 // 8 // The exact form of this will be: 9 // - The input is going to be a vector of 2-length tuples, 10 // the first element is the string, the second one is the command. 11 // - The output element is going to be a vector of strings. 12 13 enum Command { 14 Uppercase, 15 Trim, 16 Append(usize), 17 } 18 19 mod my_module { 20 use super::Command; 21 22 // The solution with a loop. Check out `transformer_iter` for a version 23 // with iterators. 24 pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> { 25 let mut output = Vec::new(); 26 27 for (string, command) in input { 28 // Create the new string. 29 let new_string = match command { 30 Command::Uppercase => string.to_uppercase(), 31 Command::Trim => string.trim().to_string(), 32 Command::Append(n) => string + &"bar".repeat(n), 33 }; 34 35 // Push the new string to the output vector. 36 output.push(new_string); 37 } 38 39 output 40 } 41 42 // Equivalent to `transform` but uses an iterator instead of a loop for 43 // comparison. Don't worry, we will practice iterators later ;) 44 pub fn transformer_iter(input: Vec<(String, Command)>) -> Vec<String> { 45 input 46 .into_iter() 47 .map(|(string, command)| match command { 48 Command::Uppercase => string.to_uppercase(), 49 Command::Trim => string.trim().to_string(), 50 Command::Append(n) => string + &"bar".repeat(n), 51 }) 52 .collect() 53 } 54 } 55 56 fn main() { 57 // You can optionally experiment here. 58 } 59 60 #[cfg(test)] 61 mod tests { 62 // Import `transformer`. 63 use super::my_module::transformer; 64 65 use super::Command; 66 use super::my_module::transformer_iter; 67 68 #[test] 69 fn it_works() { 70 for transformer in [transformer, transformer_iter] { 71 let input = vec![ 72 ("hello".to_string(), Command::Uppercase), 73 (" all roads lead to rome! ".to_string(), Command::Trim), 74 ("foo".to_string(), Command::Append(1)), 75 ("bar".to_string(), Command::Append(5)), 76 ]; 77 let output = transformer(input); 78 79 assert_eq!( 80 output, 81 [ 82 "HELLO", 83 "all roads lead to rome!", 84 "foobar", 85 "barbarbarbarbarbar", 86 ] 87 ); 88 } 89 } 90 }