develooper Front page | perl.perl6.language | Postings from June 2005

Re: reduce metaoperator on an empty list

Thread Previous | Thread Next
Damian Conway
June 1, 2005 02:37
Re: reduce metaoperator on an empty list
Message ID:
Deborah Pickett wrote:

> You are going to see empty lists more often than you think in expressions like
>   $product = [*] @array;
> and having to write that as
>   $product = [*] 1, @array;
> just to protect against a common case doesn't exactly flaunt Perl's DWIMmery 
> to me.  I *have* to write 1 there, or otherwise the reduce meta-operator 
> isn't calculating the product when there are items in @array.  This hardly 
> makes sense from a Huffman perspective.  Someone please convince me 
> otherwise.

The problem is that writing 1 there is still wrong in the "no arguments" case. 
The product of zero numbers cannot possibly be one in any common sense 
interpretation. (And, yes, I'm perfectly well aware of the mathematical 
interpretations in which it does make sense...that's not the point.)

What you want is:

	$product = ([*] @values err 0);


	$factorial = ([*] 1..$n err 1);

So what you want is not an identity value as default (which isn't even 
possible for many operators, as Luke pointed out), but a predictable failure 
value as default, so you can intercept that failure and choose your own 
outcome in the edge case.


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About