Refactor iterator functions to return division results

This commit is contained in:
Rock070 2024-01-10 23:45:35 +08:00
parent 9247e98c37
commit 5d6b812293

View File

@ -9,8 +9,6 @@
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
// hint. // hint.
// I AM NOT DONE
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum DivisionError { pub enum DivisionError {
NotDivisible(NotDivisibleError), NotDivisible(NotDivisibleError),
@ -26,23 +24,36 @@ pub struct NotDivisibleError {
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error. // Otherwise, return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> { pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
todo!(); if b == 0 {
Err(DivisionError::DivideByZero)
} else if a % b == 0 {
Ok(a / b)
} else {
Err(DivisionError::NotDivisible(NotDivisibleError {
dividend: a,
divisor: b
}))
}
} }
// Complete the function and return a value of the correct type so the test // Complete the function and return a value of the correct type so the test
// passes. // passes.
// Desired output: Ok([1, 11, 1426, 3]) // Desired output: Ok([1, 11, 1426, 3])
fn result_with_list() -> () { fn result_with_list() -> Result<Vec<i32>, DivisionError> {
let numbers = vec![27, 297, 38502, 81]; let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27)); let division_results: Vec<_> = numbers.into_iter().map(|n| divide(n, 27).unwrap()).collect();
Ok(division_results)
} }
// Complete the function and return a value of the correct type so the test // Complete the function and return a value of the correct type so the test
// passes. // passes.
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
fn list_of_results() -> () { fn list_of_results() -> Vec<Result<i32, DivisionError>> {
let numbers = vec![27, 297, 38502, 81]; let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27)); let division_results: Vec<_> = numbers.into_iter().map(|n| divide(n, 27)).collect();
division_results
} }
#[cfg(test)] #[cfg(test)]