Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. #![warn(rust_2018_idioms)]
  2.  
  3.  
  4. fn reduce_async_with_store<'a, I, A, F, C>(
  5. store: &mut Store,
  6. mut iterator: I,
  7. accumulator: A,
  8. mut f: F,
  9. continuation: C,
  10. ) where
  11. I: Iterator + 'a,
  12. F: FnMut(&mut Store, I::Item, A, Box<dyn FnOnce(&mut Store, A) + 'a>) + Clone + 'a,
  13. C: FnOnce(&mut Store, A) + 'a,
  14. {
  15. match iterator.next() {
  16. None => continuation(store, accumulator),
  17. Some(item) => {
  18. let next: Box<dyn FnOnce(&mut Store, A) + 'a> = {
  19. let f = f.clone();
  20. Box::new(move |store, accumulator| {
  21. reduce_async_with_store(store, iterator, accumulator, f, continuation)
  22. })
  23. };
  24. f(store, item, accumulator, next);
  25. }
  26. }
  27. }
  28. fn some_operation(state: &mut Store, continuation: Box<dyn FnOnce(&mut Store) + 'static>) {
  29. let mut new_state = Store { foo: state.foo };
  30. continuation(&mut new_state);
  31. }
  32.  
  33. #[derive(Debug)]
  34. pub struct Store {
  35. foo: u8,
  36. }
  37.  
  38. fn main() {
  39. let mut some_state = Store { foo: 0 };
  40. let arr = vec![1u8, 2u8, 3u8];
  41. reduce_async_with_store(
  42. &mut some_state,
  43. arr.into_iter(),
  44. Vec::new(),
  45. |store, item, mut acc, continuation| {
  46. println!("Item: {}", item);
  47. store.foo += item;
  48. acc.push(item);
  49. some_operation(
  50. store,
  51. Box::new(move |stor| {
  52. continuation(stor, acc);
  53. }),
  54. );
  55. },
  56. |store, acc| {
  57. println!("Done!! {:?} {:?}", store, acc);
  58. },
  59. )
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement