== Quote from Walter Bright ([email protected])'s article
> This can be defined instead as:
> alias reduce!"a+b" sum;
But then you have to write:
sum(sequence, 0)
which is very unintuitive.
Haskell has foldl1 and foldr1 in addition to foldl and foldr, which partially
take care of this issue (by
assuming a non-zero length list), but this is not ideal as it's perfectly
reasonable to expect a sum of a
zero-length range of integers to be 0.
In an ideal world, we would be able to define reduce something like:
auto reduce(alias Func, Range)(Range range, ElementType!Range init =
Identity!(Func,
ElementType!Range))
where
Identity!("a+b", int) = 0
Identity!("a*b", int) = 1
Identity!("a~b", char[]) = "";
etc.
However, what if people wrote reduce!((a, b) { return a+b; })(...) instead?
There's no way you could
easily relate the two; you would have to try and equate the expression trees of
the functions, which I
imagine would be no easy task, and even then you have to figure out a common
syntax for Identity...
Actually, I'm now curious as to how Andrei plans on adding sum to the standard
library in a way that
supports all summable types. Simply using 0 as the initialiser is incorrect, as
it won't work for vectors
or matrices, and requiring the user to specify the 0 (for ints) seems
unacceptable in my opinion.