simple range question

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 8 12:20:27 PDT 2016


On Friday, 8 April 2016 at 18:27:59 UTC, Laeeth Isharc wrote:
> suppose I have a forward or random access range.  what's the 
> best way to compare each element with the element 4 elements 
> prior to that element?  I could map each element to a tuple of 
> the element and the element 4 bars previously and do it that 
> way.  any neater way ?

I would recommend writing a good lag function. If we have a good 
lag function, then you could easily do something like
x.zip(x.lag(lookback)).map!(a => a[0] > a[1]);

I could think of a few different ways to implement a lag 
function, but it would take some time to write a good one 
(including NA padding, for instance). You could probably use 
popBackN or popFrontN/drop to accomplish it, depending on forward 
or backward lags.

Alternately, you could probably figure something out with .save 
that avoids the use of a lag function. You could create a range 
that saves up to four values. When full you pop off the front, 
make your comparison, and then save the latest.


More information about the Digitalmars-d-learn mailing list