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

Re: reduce metaoperator on an empty list

Thread Previous | Thread Next
From:
Damian Conway
Date:
June 1, 2005 02:37
Subject:
Re: reduce metaoperator on an empty list
Message ID:
429D81CA.5010803@conway.org
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);

Or:

	$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.

Damian

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About