cached schwartzian transform

Posted by davidk01 on Stack Overflow See other posts from Stack Overflow or by davidk01
Published on 2011-01-13T18:20:57Z Indexed on 2011/01/13 18:53 UTC
Read the original article Hit count: 310

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?

© Stack Overflow or respective owner

Related posts about perl

Related posts about caching