:cached cached

Documentation for :cached cached assembled from the following types:

language documentation Experimental features

From Experimental features

(Experimental features) :cached cached

The following pragma:

use experimental :cached;

turns on the is cached trait, which stores the result of a routine call, returning the same value if called with the same arguments.

It can be used when heavy calculations are involved, as in this sample that uses amicable numbers, taken from the 2018 Advent Calendar:

use experimental :cached;
 
sub aliquot-parts$number ) is cached {
    (^$number).grep: $number %% *;
}
 
sub infix:<amic>$m$n ) {
    $m == aliquot-parts($n).sum &&
    $n == aliquot-parts($m).sum;
}
 
# Taken from https://en.wikipedia.org/wiki/Amicable_numbers 
my @numbers = [2620292450205564623263686692866992];
 
say "Aliquot parts of $_ are "aliquot-parts $_ for @numbers;
 
for @numbers X @numbers -> @pair {
    say "@pair[0] and @pair[1] are ",
        @pair[0amic @pair[1]??" "!!"not ""amicable";
}

This code caches the computation of the aliquot parts, so that when the amic operator is called, it's only computed once; as a matter of fact, the first loop which prints these aliquot parts will be the only one that actually perform the computation.

See also the description of the trait for additional information and examples.