Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Re: Re: Closures and sort

by larsen (Parson)
on Aug 04, 2003 at 21:37 UTC ( #280813=note: print w/ replies, xml ) Need Help??


in reply to Re: Re: Closures and sort
in thread Closures and sort

The obvious answer would be to add a method reset_count() in the block, but you would have to explicitly call it before sorting, which is prone to errors.

Another way is to put together a state and a behaviour, building an object.

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 closure. Here a short demonstration:
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";
In order to learn more about this subject (very interesting, in my opinion) you could refer to the following online resources:


Comment on Re: Re: Re: Closures and sort
Select or Download Code
Re: Re: Re: Re: Closures and sort
by traveler (Parson) on Aug 04, 2003 at 21:44 UTC
    Thank you. In case it is not obvious I am trying to learn to do functional programming in perl. I have done it in lisp, but am trying to move my understanding to perl. Your code is where I thought I was going in the first place. My mistake was trying to put the sort outside the closure.

    --traveler

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://280813]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (20)
As of 2015-07-01 19:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (19 votes), past polls