Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: RFC: Tool::Box

by tmoertel (Chaplain)
on Nov 23, 2004 at 01:49 UTC ( [id://409779]=note: print w/replies, xml ) Need Help??


in reply to Re^2: RFC: Tool::Box
in thread RFC: Tool::Box

In order for a library to be useful, programmers must understand it. A chimera-like interface that shifts depending on the number of arguments passed to a function or upon magic use-time flags only places hurdles on the track to understanding. I'm squarely with diotalevi: The interface should be clear and unchanging.

I recommend having separate functions for each behavior. For example, we could use the _acc suffix to denote accumulating functions that can be used to accumulate results iteratively. As long as we are clear and consistent in our usage, we can deliver both accumulating and non-accumulating functionality without making the library harder to understand.

One possible implementation:

# factor out accumulating behavior: sub make_acc_fn(&@) { my $f = shift; $f->(@_); $f; } # mean sub mean { mean_acc(@_)->() } # all-at-once version sub mean_acc { # accumulating-function version my ($tot, $cnt); make_acc_fn { $cnt += @_; $tot += $_ for @_; $cnt ? $tot / $cnt : undef; } @_ ; } # uniq sub uniq { uniq_acc(@_)->() } sub uniq_acc { my %uniq; make_acc_fn { @uniq{ @_ } = (); wantarray ? keys %uniq : scalar keys %uniq; } @_ ; } # examples print mean(1,2,3,5), $/; # 2.5 my $m = mean_acc(); print "$_ => ", $m->($_), $/ for 1..5; # 1 => 1 # 2 => 1.5 # 3 => 2 # 4 => 2.5 # 5 => 3 print uniq(1,2,3,1..5), $/; # 41325 my $u = uniq_acc(1,2,3); print "$_ => ", $u->($_), $/ for 1..5; # 1 => 132 # 2 => 132 # 3 => 132 # 4 => 4132 # 5 => 41325

Cheers,
Tom

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-04-25 08:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found