Skip to content

Instantly share code, notes, and snippets.

@Ovid
Last active July 24, 2018 20:59
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 Ovid/dd9743e81192fdcb0c3c0c763290fac8 to your computer and use it in GitHub Desktop.
Save Ovid/dd9743e81192fdcb0c3c0c763290fac8 to your computer and use it in GitHub Desktop.
Sample LRU cache in Perl 6?
# Turns out this doesn't work because OrderedHash
# is sorted, not ordered
class Cache::LRU {
use OrderedHash;
has %.cache = {} does OrderedHash;
has UInt $.max_size = 20;
method get($key) {
return %.cache{$key};
}
method set($pair) {
if $.cache{$pair.key}:exists {
# delete it to make sure that it gets
# added as most-recently used
$.cache{$pair.key}:delete;
}
elsif %.cache.pairs.elems >= $.max_size {
# key doesn't exist, so make room for it
%.cache{ %.cache.keys.tail }:delete;
}
%.cache{$pair.key} = $pair.value;
}
method pairs() {
return %.cache.pairs;
}
}
my $cache = Cache::LRU.new( max_size => 3 );
for (1, 2, 3, 4, 5, 4, 3, 2).kv -> $i, $num {
say "# Setting $num to $i";
$cache.set( $num => $i );
# by the time we get to herre, 2, 3, and 4 are our last items, but I'm
# getting ("5" => 4, "1" => 0, "2" => 7).Seq
say "# " ~ $cache.pairs.perl;
}
# Setting 1 to 0
# ("1" => 0,).Seq
# Setting 2 to 1
# ("1" => 0, "2" => 1).Seq
# Setting 3 to 2
# ("1" => 0, "3" => 2, "2" => 1).Seq
# Setting 4 to 3
# ("1" => 0, "4" => 3, "3" => 2).Seq
# Setting 5 to 4
# ("5" => 4, "1" => 0, "4" => 3).Seq
# Setting 4 to 5
# ("5" => 4, "1" => 0, "4" => 5).Seq
# Setting 3 to 6
# ("5" => 4, "1" => 0, "3" => 6).Seq
# Setting 2 to 7
# ("5" => 4, "1" => 0, "2" => 7).Seq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment