Advertisement
Guest User

Untitled

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