Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://280813]
and the voices are still...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2018-06-22 23:59 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.