Stuart Cook wrote: > In Haskell, there is a distinction between foldl and foldl1 (similar > remarks apply to foldr/foldr1[1]): > The former (foldl) requires you to give an explicit 'left unit'[2], > which is implicitly added to the left of the list being reduced. This > means that folding an empty list will just give you the unit. > i.e. > foldl (+) 0 [a,b,c] = ((0+a)+b)+c > foldl (+) 0 [] = 0 > The latter (foldl1) doesn't use a unit value, but this means that you > can't fold empty lists. > i.e. > foldl1 (+) [a,b,c] = (a+b)+c > foldl1 (+) [] = ***error*** sure. Maybe the identity values could be supplied by making the reduce operator for them a curried version of reduce, where reduce requires a list with at least one element (or DIES :)) eg, something similar to; (sorry for the psuedo-perl6, corrections welcome :)) sub prefix:<[+]> (*@args) ::= &reduce.assuming(func => &infix:<+>, first => 0); sub prefix:<[*]> (*@args) ::= &reduce.assuming(func => &infix:<*>, first => 1); This would mean that unless the operator specifically defines a curried reduce version of itself, then the [] version of it on an empty list will be a hard run-time error. Then again, maybe an identity trait is more elegant and covers the varied ways that multiple operators combine inside reduce.. > You /could/ try to do something 'sensible' and return 0 or undef, but > this seems likely to result in more confusion. Personally I think returning an undef for this kind of situation would be as wrong as returning undef for 0/0. Sam.Thread Previous | Thread Next