Created
February 5, 2026 10:58
-
-
Save pboyd/8b211023ade6db2010202139d80a139c to your computer and use it in GitHub Desktop.
Aggressive Memoizer
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
| #!/bin/env perl | |
| use strict; | |
| use warnings; | |
| use v5.12; | |
| sub aggressively_memoize { | |
| my $caller_num = shift // 1; | |
| my $caller = (caller($caller_num))[3]; | |
| return unless $caller; | |
| my ($package, $sub_name) = $caller =~ /(.*)::(.*?)$/; | |
| return if $sub_name eq '__ANON__'; | |
| my $orig = $package->can($sub_name); | |
| my %cache; | |
| my $new_sub = sub { | |
| aggressively_memoize(2); | |
| my $key = join("\0", @_); | |
| # FIXME: Should check wantarray, this doesn't work in list context. | |
| unless (exists $cache{$key}) { | |
| $cache{$key} = $orig->(@_); | |
| } | |
| # Uncomment this if you wonder whether or not the cache is getting hit: | |
| #else { | |
| # warn 'hit'; | |
| #} | |
| return $cache{$key}; | |
| }; | |
| { | |
| no strict 'refs'; | |
| no warnings 'redefine'; | |
| *{$caller} = $new_sub; | |
| } | |
| return; | |
| } | |
| sub add { | |
| # Comment this out to see the performance difference | |
| aggressively_memoize(); | |
| my $result = 0; | |
| $result += $_ for @_; | |
| return $result; | |
| } | |
| sub fib { | |
| my $n = shift; | |
| return 0 if $n <= 0; | |
| return 1 if $n == 1; | |
| return fib(add($n, -1)) + fib(add($n, -2)); | |
| } | |
| say fib(40); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment