On Fri, May 20, 2005 at 06:09:55AM -0700, Randal L. Schwartz wrote:
> >>>>> "Mark" == Mark A Biggar <[EMAIL PROTECTED]> writes:
> Mark> The usual definition of reduce in most languages that support it, is
> Mark> that reduce over the empty list produces the Identity value for the
> Mark> operation.
> In Smalltalk, the equivalent of "reduce" is "inject:into:", so a
> "sum" reduce looks like:
> sum := aList inject: 0 into: [:previous :this | previous + this]
> Now the advantage here is that if aList is empty, we get back the inject
> value. Thus, the behavior is always well-defined.
> The Perl reduce operator treats the first element of the list as the
> "inject" value above. However, if the first element is missing,
> the most Perlish thing I can think of is having it return undef,
> because it's like you've specified an undef inject value.
I think we should provide built-in operators with an attribute
called "identity". Reduce, when given an empty list, would
check if the operator has a defined identity attribute. If so,
it is returned as the result of the reduction. If the opereator
has no identity attribute, reduce throws an exception for an
Is there a built-in operator that doesn't have a meaningful
identity value? I first thought of exponentiation, but it has
an identity value of 1 - you just have to realize that since
it is a right associative operator, the identity has to be
applied from the right.
I suspect that if people ever get into writing code that works
on operators instead of data, there would be additional uses
found for the identity attribute (and there may be additional
operator attributes that make sense there too, although none
come immediately to mind). MJD will soon have to start working
on the second edition of Higher Order Perl.