Macaulay2 » Documentation
Packages » Macaulay2Doc » The Macaulay2 language » caching computation results
next | previous | forward | backward | up | index | toc

caching computation results

Here is a simple example of caching a computation in a CacheTable, using the augmented null coalescing operator ??=.

i1 : pdim' = M -> M.cache.pdim' ??= ( printerr "computing pdim'"; pdim M );
i2 : R = QQ[x,y,z];
i3 : M = coker vars R;
i4 : elapsedTime pdim' M
 -- computing pdim'
 -- .00332455s elapsed

o4 = 3
i5 : elapsedTime pdim' M
 -- 9.81e-7s elapsed

o5 = 3
i6 : peek M.cache

o6 = CacheTable{cache => MutableHashTable{}                                              }
                isHomogeneous => true
                minimalPresentation => (OptionTable{Exclude => {}}) => cokernel | z y x |
                pdim' => 3
                presentation => | x y z |

In the example above, the function is only executed if M.cache.pdim' is not already defined, and once it is executed the result is stored there for future reference.

In more complicated situations, one may need to create a new table under cache first.

i7 : code(hh, Sequence, ProjectiveVariety)

o7 = -- code for method: hh(Sequence,ProjectiveVariety)
     ../../../../Macaulay2/packages/Varieties.m2:800:34-809:7: --source code:
     hh(Sequence,ProjectiveVariety) := (pq,X) -> if X.cache.?hh and X.cache.hh#?pq then X.cache.hh#pq else (
          (p,q) := pq;
          if class p =!= ZZ or class q =!= ZZ then error "expected integer superscripts";
          d := dim X;
          pqs := { (p,q), (q,p), (d-p,d-q), (d-q,d-p) };
          (p,q) = min { (p,q), (q,p), (d-p,d-q), (d-q,d-p) };
          h := rank HH^q cotangentSheaf(p,X);
          if not X.cache.?hh then X.cache.hh = new MutableHashTable;
          scan(pqs, pq -> X.cache.hh#pq = h);
          h)

See also

Menu


The source of this document is in Macaulay2Doc/ov_caching.m2:71:0.