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


In reply to Re^3: RFC: Tool::Box by tmoertel
in thread RFC: Tool::Box by Limbic~Region

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.