note
larsen
<p>The obvious answer would be to add a <i>method</i> <code>reset_count()</code> in the block, but you would have to explicitly call it before sorting, which is prone to errors.</p>
<p>Another way is to put together a state and a behaviour, building an <strong>object</strong>.</p>
But if you want to go on in a functional way, you may want to build a composition of a behaviour and a state, i.e. a <strong>closure</strong>. Here a short demonstration:
<code>
use strict;
my @list1 = qw/ box cow dog apple ant/;
my @list2 = qw/ ant apple box cow dog/;
sub make_a_profilable_sorter
{
my $criterion = shift;
return sub {
my $counter = 0;
my @list = @_;
@list = sort { $counter++; $criterion->( $a, $b ) } @list;
return ( $counter, @list );
}
}
my $sorter1 = make_a_profilable_sorter( sub{ $_[0] cmp $_[1] } );
my $sorter2 = make_a_profilable_sorter( sub{ $_[0] cmp $_[1] } );
my ($count, @res) = $sorter1->( @list1 );
print "I sorted /@list1/ in $count steps producing /@res/\n";
my ($count, @res) = $sorter2->( @list2 );
print "I sorted /@list2/ in $count steps producing /@res/\n";
</code>
In order to learn more about this subject (very interesting, in my opinion) you could refer to the following online resources:
<ul>
<li>[http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%_sec_3.2.3|Frames as repository of local state] in <i>Structure and Interpretation of Computer Programs</i></li>
<li>[http://www.paulgraham.com/onlisp.html|On Lisp] by Paul Graham. Start at page 30 (in the free pdf file)</li>
</ul>
280790
280803