Advertisement
Guest User

Cache results in computational graph

a guest
May 30th, 2022
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.00 KB | None | 0 0
  1. /* Implementation of a computational graph with
  2.  * caching and reused computation.
  3.  *         - -
  4.  *       /     \
  5.  * a - b - c    \
  6.  * | \    \  \   |
  7.  *  \  d - e  |  |
  8.  *   \      \ |  |
  9.  *     - - - f - g
  10.  */
  11.  
  12.  
  13. #[derive(Debug)]
  14. pub struct ResultsA{}
  15.  
  16. #[derive(Debug)]
  17. pub struct ResultsB{}
  18.  
  19. #[derive(Debug)]
  20. pub struct ResultsC{}
  21.  
  22. #[derive(Debug)]
  23. pub struct ResultsD{}
  24.  
  25. #[derive(Debug)]
  26. pub struct ResultsE{}
  27.  
  28. #[derive(Debug)]
  29. pub struct ResultsF{}
  30.  
  31. #[derive(Debug)]
  32. pub struct ResultsG{}
  33.  
  34.  
  35. fn a() -> ResultsA {
  36.     ResultsA {}
  37. }
  38.  
  39. fn b(_a:&ResultsA) -> ResultsB {
  40.     ResultsB {}
  41. }
  42.  
  43. fn d(_a:&ResultsA) -> ResultsD {
  44.     ResultsD {}
  45. }
  46.  
  47. fn c(_b:&ResultsB) -> ResultsC {
  48.     ResultsC {}
  49. }
  50.  
  51. fn e(_b:&ResultsB, _d:&ResultsD) -> ResultsE {
  52.     ResultsE {}
  53. }
  54.  
  55. fn f(_c:&ResultsC, _e:&ResultsE) -> ResultsF {
  56.     ResultsF {}
  57. }
  58.  
  59. fn g(_b:&ResultsB, _f:&ResultsF) -> ResultsG {
  60.     ResultsG {}
  61. }
  62.  
  63.  
  64. pub fn direct_compute() -> ResultsG {
  65.     g(&b(&a()), &f(&c(&b(&a())), &e(&b(&a()), &d(&a()))))
  66.  
  67. }
  68.  
  69. struct Cache {
  70.     a:Option<ResultsA>,
  71.     b:Option<ResultsB>,
  72.     c:Option<ResultsC>,
  73.     d:Option<ResultsD>,
  74.     e:Option<ResultsE>,
  75.     f:Option<ResultsF>,
  76. }
  77.  
  78.  
  79. impl Cache {
  80.     fn new() -> Cache{
  81.         Cache {a:None, b:None, c:None, d:None, e:None, f:None}
  82.     }
  83. }
  84.  
  85.  
  86. pub fn cached_compute() -> ResultsG {
  87.     let mut cache = Cache::new();
  88.  
  89.     let _a = a();
  90.  
  91.     cache.a = Some(_a);
  92.  
  93.     let _b = b(cache.a.as_ref().unwrap());
  94.     let _d = d(cache.a.as_ref().unwrap());
  95.  
  96.     cache.b = Some(_b);
  97.     cache.d = Some(_d);
  98.  
  99.     let _c = c(cache.b.as_ref().unwrap());
  100.     let _e = e(cache.b.as_ref().unwrap(), cache.d.as_ref().unwrap());
  101.  
  102.     cache.c = Some(_c);
  103.     cache.e = Some(_e);
  104.  
  105.     let _f = f(cache.c.as_ref().unwrap(), cache.e.as_ref().unwrap());
  106.  
  107.     cache.f = Some(_f);
  108.  
  109.     g(cache.b.as_ref().unwrap(), cache.f.as_ref().unwrap())
  110. }
  111.  
  112.  
  113. fn main() {
  114.     println!("{:?}", direct_compute());
  115.     println!("{:?}", cached_compute());
  116. }
  117.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement