Using reduce() with tuples created by zip()
bearophile
bearophileHUGS at lycos.com
Thu Oct 31 13:07:23 PDT 2013
> alias sum(T) = curry!(reduce!q{a + b}, cast(T)0);
>
> double euclidDistance(double[] xs, double[] ys)
> in {
> assert(xs.length == ys.length);
> } body {
> return zip(xs, ys)
> .map!(xy => (xy[0] - xy[1]) ^^ 2)
> .sum!double
> .sqrt;
> }
>
> void main() {
> auto xs = [0.0, 1.0, 0.1];
> auto ys = [1.0, -1.0, 0.0];
> euclidDistance(xs, ys).writeln;
> }
In D functions are written in camelCase like euclidDistance,
instead of euclid_distance.
Function pre-conditions and post-conditions are generally better
put in the pre and post part of functions.
I have defined a sum because it's a generally useful function,
but it's a toy because it assumes cast(T)0 as the identity
element of the monoid with the plus operator.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list