cached schwartzian transform
- by davidk01
I'm going through "Intermediate Perl" and it's pretty cool. I just finished the section on "The Schwartzian Transform" and after it sunk in I started to wonder why the transform doesn't use a cache. In lists that have several repeated values the transform recomputes the value for each one so I thought why not use a hash to cache results. Here' some code:
# a place to keep our results
my %cache;
# the transformation we are interested in
sub foo {
# expensive operations
}
# some data
my @unsorted_list = ....;
# sorting with the help of the cache
my @sorted_list = sort {
($cache{$a} or $cache{$a} = &foo($a)) <=> ($cache{$b} or $cache{$b} = &foo($b))
} @unsorted_list;
Am I missing something? Why isn't the cached version of the Schwartzian transform listed in books and in general just better circulated because on first glance I think the cached version should be more efficient?