Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
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:

Replies are listed 'Best First'.
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?
[LanX]: ugh ... wouldn't want a ring around the neck
[marto]: hmm, verify httpscert, hosted on IIS, created on $client Windows PKI infrastructure from perl on an old Solaris box
[marto]: I really hate our clients network/infrastruc ture :P

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2017-10-20 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My fridge is mostly full of:

















    Results (261 votes). Check out past polls.

    Notices?