Skip to content

Commit

Permalink
all_errors
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheyca committed Aug 7, 2023
1 parent 029da81 commit 3f27099
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
36 changes: 36 additions & 0 deletions src/exercises/all_errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Report all errors (or only the first error)

```rust
# trait Collects {
# type Error;
# type Output;
# fn push(&self, trace: Vec<i32>, next: i32) -> Result<Vec<i32>, Self::Error>;
# fn regularize(&self, result: Result<Result<Vec<i32>, Vec<i32>>, Self::Error>) -> Result<Vec<i32>, Self::Output>;
# }
# struct First;
# struct All;
# impl Collects for First {
# type Error = i32;
# type Output = i32;
# fn push(&self, _trace: Vec<i32>, next: i32) -> Result<Vec<i32>, Self::Error> { Err(next) }
# fn regularize(&self, result: Result<Result<Vec<i32>, Vec<i32>>, Self::Error>) -> Result<Vec<i32>, Self::Output> { result.map(|r| r.unwrap()) }
# }
# impl Collects for All {
# type Error = std::convert::Infallible;
# type Output = Vec<i32>;
# fn push(&self, mut trace: Vec<i32>, next: i32) -> Result<Vec<i32>, Self::Error> { trace.push(next); Ok(trace) }
# fn regularize(&self, result: Result<Result<Vec<i32>, Vec<i32>>, Self::Error>) -> Result<Vec<i32>, Self::Output> { result.unwrap() }
# }
# fn first() -> impl Collects<Output = i32> { First }
# fn all() -> impl Collects<Output = Vec<i32>> { All }
# fn _only_postivie<C: Collects>(numbers: Vec<i32>, c: &C) -> Result<Result<Vec<i32>, Vec<i32>>, 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<C: Collects>(numbers: Vec<i32>, c: C) -> Result<Vec<i32>, 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]));
```

0 comments on commit 3f27099

Please sign in to comment.