From 3f27099e17c33d021c0625c9638eb2d561640e0d Mon Sep 17 00:00:00 2001 From: timofey Date: Mon, 7 Aug 2023 16:22:20 +0000 Subject: [PATCH] all_errors --- src/SUMMARY.md | 1 + src/exercises/all_errors.md | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/exercises/all_errors.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index cd873c2..84bddcd 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -12,6 +12,7 @@ - [Chapter 2](./chapter_2.md) - [AnyStr](./exercises/anystr.md) - [Mode](./exercises/mode.md) + - [All Errors](./exercises/all_errors.md) - [Chapter 3](./chapter_3.md) - [Composition](./exercises/composition.md) diff --git a/src/exercises/all_errors.md b/src/exercises/all_errors.md new file mode 100644 index 0000000..8252d3f --- /dev/null +++ b/src/exercises/all_errors.md @@ -0,0 +1,36 @@ +# Report all errors (or only the first error) + +```rust +# trait Collects { +# type Error; +# type Output; +# fn push(&self, trace: Vec, next: i32) -> Result, Self::Error>; +# fn regularize(&self, result: Result, Vec>, Self::Error>) -> Result, Self::Output>; +# } +# struct First; +# struct All; +# impl Collects for First { +# type Error = i32; +# type Output = i32; +# fn push(&self, _trace: Vec, next: i32) -> Result, Self::Error> { Err(next) } +# fn regularize(&self, result: Result, Vec>, Self::Error>) -> Result, Self::Output> { result.map(|r| r.unwrap()) } +# } +# impl Collects for All { +# type Error = std::convert::Infallible; +# type Output = Vec; +# fn push(&self, mut trace: Vec, next: i32) -> Result, Self::Error> { trace.push(next); Ok(trace) } +# fn regularize(&self, result: Result, Vec>, Self::Error>) -> Result, Self::Output> { result.unwrap() } +# } +# fn first() -> impl Collects { First } +# fn all() -> impl Collects> { All } +# fn _only_postivie(numbers: Vec, c: &C) -> Result, Vec>, C::Error> { +# let mut state = Ok(vec![]); +# for x in numbers { state = if x > 0 { state.map(|mut vec| {vec.push(x); vec}) } else { Err(c.push(match state { Ok(_) => vec![], Err(vec) => vec }, x)?) } } +# Ok(state) +# } +# fn only_positive(numbers: Vec, c: C) -> Result, C::Output> { c.regularize(_only_postivie(numbers, &c)) } +assert_eq!(only_positive(vec![1, -1, 2, -4], first()), Err(-1)); +assert_eq!(only_positive(vec![1, 2, 3], first()), Ok(vec![1, 2, 3])); +assert_eq!(only_positive(vec![1, -1, 2, -4], all()), Err(vec![-1, -4])); +assert_eq!(only_positive(vec![1, 2, 3], all()), Ok(vec![1, 2, 3])); +```