Using algorithms with ranges
mipri
mipri at minimaltype.com
Thu Oct 3 05:33:04 UTC 2019
On Thursday, 3 October 2019 at 05:20:47 UTC, mipri wrote:
> It'd be nicer to do compose a range over iota, as in
>
> iota(1, 10).newThingWithHistory
>
> but I don't know how to do that yet. I guess c.f.
> std.range.retro
This is a bit better:
#! /usr/bin/env rdmd
import std.stdio;
auto withHistory(Range)(Range r) {
import std.traits : Unqual;
import std.range.primitives : ElementType;
static struct Result {
private:
alias R = Unqual!Range;
alias T = ElementType!R;
R source;
T[] history;
public:
bool empty() {
return source.empty;
}
void popFront() {
source.popFront;
}
T front() {
T x = source.front;
history ~= x;
if (history.length > 1) {
return x + history[$-2];
} else {
return x;
}
}
}
return Result(r);
}
void main() {
import std.range : iota;
foreach (x; iota(1, 10).withHistory)
writeln(x);
}
More information about the Digitalmars-d-learn
mailing list