There's no reduce
specifically defined on CollectionOfOne; it's fallout from being a Collection (technically Sequence). We certainly wouldn't add it if it weren't present, since it is useless. But the general question stands: why have, say, map
on both Collections and Optionals, but not reduce
?
I think a big part of the answer is that it really isn't a common operation if you're not trying to chain everything in one expression, and even then, it's only useful if your "nil" value is relevant to your "non-nil" value, which I think is pretty uncommon. The fully general pattern I'd use for this is foo.map { 1 + $0 } ?? 1
(i.e. your implementation). Is foo.reduce(1, +)
simpler than that? Well, yes, but it's also more restrictive—it comes out worse for foo.map { 1 + $0 } ?? 0
. (Specifically, foo.reduce(0) { $1 + 1 }
) That certainly doesn't mean "reduce
shouldn't be added", but if it's not going to be the right tool for the job very often, does it belong in the standard library?
…But on the other hand, what harm would it do?
FWIW, the only other thread I've found on this is one you participated in: Add Optional.filter to the Standard Library - #41 by gwendal.roue. I'm personally of the opinion that (a) Optional is not a Collection, but also that (b) that shouldn't stop us from adding the Collection-like operations (monadic, foldable, whatever) that make sense on Optional.*
* Whether there should be, say, a Foldable protocol is a separate issue that unfortunately gets into binary compatibility problems.