Created
December 2, 2011 14:49
-
-
Save jnthn/1423496 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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