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

Re: reduce metaoperator on an empty list

Thread Previous | Thread Next
Mark A. Biggar
May 18, 2005 18:26
Re: reduce metaoperator on an empty list
Message ID:
Matt Fowles wrote:
> All~
> What does the reduce metaoperator do with an empty list?
> my @a;
> [+] @a; # 0? exception?
> [*] @a; # 1? exception?
> [<] @a; # false?
> [||] @a; # false?
> [&&] @a; # true?
> Also if it magically supplies some correct like the above, how does it
> know what that value is?

The usual definition of reduce in most languages that support it, is 
that reduce over the empty list produces the Identity value for the 
operation.  So for the above ops the answers are: 0, 1, depends, false, 
true.  For chained ops like '<' it depends on whether x<y<z return x or 
z on being true. if x then -inf else if z then +inf (don't ask if it 
returns y).  Note that some ops (like '%') don't have an identity value 
and therefore [%] over the empty list is the equivalent to a divide by 0 
and probably throws an exception or at least returns undef.  Now this is 
  a problem for user defined operations, so reduce of a user defined op 
over the empty list is either an exception, return undef or we need a 
trait that can be specified for an infix op that specifies what to 
return for reduce over the empty list.  The compiler shouldn't bother to 
check if what you specified is really the Identity value for op, but I'd 
consider it a bug if it isn't.


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