Using reduce() with tuples created by zip()

Philippe Sigaud philippe.sigaud at gmail.com
Thu Oct 31 12:23:44 PDT 2013


I think reduce takes two arguments: the growing seed and the current front.
You're trying to get (a[0]-b[0])^^2 + (a[1]-b[1])^^2 + ..., right?

Try this:

module euclid;


import std.stdio;

double euclid_dist( double[] pt1, double[] pt2 ) {
    assert( pt1.length == pt2.length );
    import std.algorithm;
    import std.math;
    import std.range;

    return sqrt(0.0.reduce!( (sum,pair) => sum + (pair[0]-pair[1])^^2
)(zip(pt1, pt2)));
}

void main()
{
    double[] arr1 = [0.0, 1.0, 0.1];
    double[] arr2 = [1.0, -1.0, 0.0];
    writeln(euclid_dist(arr1,arr2));
}



On Thu, Oct 31, 2013 at 8:12 PM, Craig Dillabaugh <
cdillaba at cg.scs.carleton.ca> wrote:

> I am trying to calculate the Euclidean Distance between two
> points. I currently have the following function (that doesn't
> compile):
>
> double euclid_dist( double[] pt1, double[] pt2 ) {
>    assert( pt1.length == pt2.length );
>
>    return sqrt(
>      zip(pt1, pt2).reduce!(function(e) { return
> (e[1]-e[0])*(e[1]-e[0]); })(0.0)
>    );
> }
>
> Hopefully it is clear what I am trying to do.  I want zip to
> create a range that is a tuple of the point's coordinate pairs,
> and then use reduce to sum the squared differences.  I get the
> following error but can't figure out how to fix my syntax:
>
> euclid.d(13): Error: template
> euclid.euclid_dist.reduce!(__**funcliteral2).reduce does not match
> any function template declaration. Candidates are:
> /usr/include/dmd/phobos/std/**algorithm.d(688):
> euclid.euclid_dist.reduce!(__**funcliteral2).reduce(Args...)(**Args
> args) if (Args.length > 0 && Args.length <= 2 &&
> isIterable!(Args[__dollar - 1]))
> euclid.d(13): Error: template
> euclid.euclid_dist.reduce!(__**funcliteral2).reduce(Args...)(**Args
> args) if (Args.length > 0 && Args.length <= 2 &&
> isIterable!(Args[__dollar - 1])) cannot deduce template function
> from argument types !()(Zip!(double[], double[]), double)
> Failed: 'dmd' '-v' '-o-' 'euclid.d' '-I.'
>
>
> I know I could use a simple foreach loop with my zip command, or
> even std.numeric.euclidean( ... ), but I am trying to be cute
> here!
>
> Cheers,
> Craig
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20131031/8b0f3f0a/attachment.html>


More information about the Digitalmars-d-learn mailing list