Can you read the next line while iterating over byLine?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 2 11:42:19 PST 2017
On 02/02/2017 11:30 AM, Daniel Kozak via Digitalmars-d-learn wrote:
>
> More range aproach, untested written on the fly from mobile phone
>
> import std.stdio : File;
> import std.range : chunks;
> import.std.algorithm : map, filter, array;
>
> void main()
> {
> auto r = File("text.txt").byLine
> .filter!(a=>a.length)
> .chunks(2)
> .map!(a=>[a[0].dup, a[1].dup])
> .array;
>
> writeln(r);
> }
>
>
I tried that as well but chunks() requires ForwardRange. I wrote a rough
sketch of byPairs almost :) on the fly:
import std.range;
import std.stdio;
import std.algorithm;
import std.typecons;
struct ByPairs(R)
if (isInputRange!R) {
alias E = ElementType!R;
R range;
Tuple!(E, E) pair;
this (R range) {
this.range = range;
if (!empty) {
prime();
}
}
void prime() {
this.pair[0] = range.front;
range.popFront();
this.pair[1] = range.front;
range.popFront();
}
bool empty() {
return range.empty;
}
auto front() {
return pair;
}
void popFront() {
assert(!empty);
prime();
}
}
auto byPairs(R)(R r) {
return ByPairs!R(r);
}
void main() {
struct Data {
string url;
string num;
}
auto result = File("deneme.txt", "r")
.byLineCopy
.filter!(line => !line.empty)
.byPairs;
// Also try appending .map!(t => Data(t[0], t[1]))
writefln("%-(%s\n%)", result);
}
Having to decide on Tuple (or requiring a factory method) is bothersome.
It would be great if the programmer need not deal with the intermediate
Tuple and just get their Data. So, a 'map' without needing explicit
construction like
.byPairs.make!Data
should somehow work. Or perhaps
.mapFromTuple!Data(byPairs)
(Not tested.)
Ali
More information about the Digitalmars-d-learn
mailing list