Advertisement
Guest User

Untitled

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