Caching the Schwartz transform would be useful if you call foo() on several transforms:
@sorted1 = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, foo($_)] } @unsorted1; @sorted2 = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, foo($_)] } @unsorted2;
If @unsorted1 and @unsorted2 have basically the same values, you will call foo() for the same values twice. If this feature is an expensive computing machine, you probably want to cache the results.
The easiest way to do this is to use the Memoize module :
use Memoize; memoize('foo');
If you add these two lines, you do not need to worry about setting the cache for foo() yourself, Memoize processes it for you.
Edit: I just noticed that your species does not perform the Black Forest transformation. The whole point behind ST is that you only perform your expensive function once for each member of the list, so you make the whole map sort map construct. Although you could probably do some handwritten caching as it was, it would be non-standard Perl (in the sense that someone expected to see ST, and then would have to sit there and find out what your code is ) and can quickly become a service nightmare.
But yes, if your list has duplicate values, using a cache (manual or with Memoize ) can lead to faster Schwartz conversion. I say “maybe” because there may be times when searching for hashes is actually more expensive than calling foo() ( Memoize docs use sub foo { my $x = shift; return $x * $x } as an example of one of of these instances).
source share