Skip to content

Instantly share code, notes, and snippets.

@jnthn
Created December 2, 2011 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnthn/1423496 to your computer and use it in GitHub Desktop.
Save jnthn/1423496 to your computer and use it in GitHub Desktop.
my role CachedRoutine[$orig] {
has %!cache;
method postcircumfix:<( )>($c) {
my $key := $c.gist;
%!cache.exists($key) ??
%!cache{$key} !!
(%!cache{$key} = $orig(|$c))
}
}
sub trait_mod:<is>(Routine $r, :$cached!) {
$r does CachedRoutine[$r.clone()]
}
sub foo($a) is cached {
say "I was called with $a";
return 2 * $a;
}
say foo(1);
say foo(2);
say foo(1);
say foo(2);
sub trait_mod:<is>(Routine $r, :$cached!) {
my %cache;
$r.wrap(-> |$c {
my $key := $c.gist;
%cache.exists($key) ??
%cache{$key} !!
(%cache{$key} = callsame)
})
}
sub foo($a) is cached {
say "I was called with $a";
return 2 * $a;
}
say foo(1);
say foo(2);
say foo(1);
say foo(2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment