Using reduce() with tuples created by zip()
Craig Dillabaugh
cdillaba at cg.scs.carleton.ca
Thu Oct 31 12:59:18 PDT 2013
On Thursday, 31 October 2013 at 19:23:56 UTC, Philippe Sigaud
wrote:
> 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?
Yep. The (e[1]-e[0])*(e[1]-e[0]) bit was, I supposed was
effectively
calculating (a[0]-b[0])^^2 and so on. I forgot about the ^^2 in
D.
>
> 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:
>
clip
>> Cheers,
>> Craig
Thanks, I will try both your, and Bearophile's ideas and see if I
can figure out how they work.
Craig
More information about the Digitalmars-d-learn
mailing list