如何计算行数并在 D 中以功能方式执行操作?
How to count number of lines and perform operations in functional way in D?
我有如下一段代码:
import std.algorithm;
import std.array;
import std.csv;
import std.stdio;
import std.typecons;
import std.getopt;
import std.file;
import std.conv;
struct DataPoint{
double x,y,z;
this(double _x, double _y, double _z){
x = _x;
y = _y;
z = _z;
}
this(char[][] a){
x = to!double(a[0]);
y = to!double(a[1]);
z = to!double(a[2]);
}
DataPoint opBinary(string s)(DataPoint d) if (s == "+"){
auto ret = DataPoint(x + d.x, y + d.y, z + d.z);
return ret;
}
}
void main(string[] args)
{
string csvFile;
try{
getopt(args, std.getopt.config.required, "input|i", &csvFile);
assert(csvFile.isFile);
}
catch(Exception e){
writeln(e.msg);
return;
}
auto file = File(csvFile, "r");
int lineCount = 0;
foreach (string line; lines(file)){
++lineCount;
}
file.close();
file = File(csvFile, "r");
auto aa = file.byLine() // Read lines
.map!split // Split into words
.map!(a => DataPoint(a))
.reduce!((a,b) => a + b);
auto average = DataPoint(aa.x/lineCount, aa.y/lineCount, aa.z/lineCount);
std.stdio.writefln("After reading %d records, "
~"the average is [%.2f, %.2f, %.2f]", lineCount, average.x, average.y, average.z);
}
如何在遍历文件内容的同时计算文件中的行数? (一次通过)
您可以在拆分为单词之前映射一个恒等增量函数,如下所示:
file.byLine()
.map!((a){ lineCount++; return a; })
...
此外,您应该考虑使用 fold
而不是 reduce
,因为后者在使用起始值时参数顺序很奇怪。
它不是很实用,但你可以使用 tee
进行内联处理:
int count = 0;
auto x = stdin.byLine.tee!(_ => ++count).map!(/+ ... whatever ... +/);
我有如下一段代码:
import std.algorithm;
import std.array;
import std.csv;
import std.stdio;
import std.typecons;
import std.getopt;
import std.file;
import std.conv;
struct DataPoint{
double x,y,z;
this(double _x, double _y, double _z){
x = _x;
y = _y;
z = _z;
}
this(char[][] a){
x = to!double(a[0]);
y = to!double(a[1]);
z = to!double(a[2]);
}
DataPoint opBinary(string s)(DataPoint d) if (s == "+"){
auto ret = DataPoint(x + d.x, y + d.y, z + d.z);
return ret;
}
}
void main(string[] args)
{
string csvFile;
try{
getopt(args, std.getopt.config.required, "input|i", &csvFile);
assert(csvFile.isFile);
}
catch(Exception e){
writeln(e.msg);
return;
}
auto file = File(csvFile, "r");
int lineCount = 0;
foreach (string line; lines(file)){
++lineCount;
}
file.close();
file = File(csvFile, "r");
auto aa = file.byLine() // Read lines
.map!split // Split into words
.map!(a => DataPoint(a))
.reduce!((a,b) => a + b);
auto average = DataPoint(aa.x/lineCount, aa.y/lineCount, aa.z/lineCount);
std.stdio.writefln("After reading %d records, "
~"the average is [%.2f, %.2f, %.2f]", lineCount, average.x, average.y, average.z);
}
如何在遍历文件内容的同时计算文件中的行数? (一次通过)
您可以在拆分为单词之前映射一个恒等增量函数,如下所示:
file.byLine()
.map!((a){ lineCount++; return a; })
...
此外,您应该考虑使用 fold
而不是 reduce
,因为后者在使用起始值时参数顺序很奇怪。
它不是很实用,但你可以使用 tee
进行内联处理:
int count = 0;
auto x = stdin.byLine.tee!(_ => ++count).map!(/+ ... whatever ... +/);