read-file-lines function added
This commit is contained in:
26
ml.cpp
26
ml.cpp
@@ -19,6 +19,7 @@
|
||||
#include <sstream>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <ctime>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
@@ -1126,6 +1127,30 @@ namespace builtin {
|
||||
return MlValue::string(read_file_contents(args[0].as_string()));
|
||||
}
|
||||
|
||||
// Reads file line by line and call passed lambda
|
||||
MlValue read_file_lines(std::vector<MlValue> args, MlEnvironment &env) {
|
||||
eval_args(args, env);
|
||||
|
||||
if (args.size() != 2)
|
||||
throw MlError(MlValue("read-file-lines", read_file_lines), env, args.size() > 1 ? TOO_MANY_ARGS : TOO_FEW_ARGS);
|
||||
// TODO check args[1].is_lambda
|
||||
|
||||
long lines_nr = 0;
|
||||
std::vector<MlValue> lambda_par{MlValue::nil()};
|
||||
std::ifstream file(args[0].as_string());
|
||||
if (file.is_open()) {
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
lines_nr++;
|
||||
lambda_par[0] = MlValue::string(line);
|
||||
args[1].apply(lambda_par, env);
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
|
||||
return MlValue{lines_nr};
|
||||
}
|
||||
|
||||
// Write a string to a file
|
||||
MlValue write_file(std::vector<MlValue> args, MlEnvironment &env) {
|
||||
eval_args(args, env);
|
||||
@@ -1978,6 +2003,7 @@ MlValue MlEnvironment::get(const std::string &name) const {
|
||||
if (name == "random") return MlValue("random", builtin::random);
|
||||
if (name == "include") return MlValue("include", builtin::include);
|
||||
if (name == "read-file") return MlValue("read-file", builtin::read_file);
|
||||
if (name == "read-file-lines") return MlValue("read-file-lines", builtin::read_file_lines);
|
||||
if (name == "write-file") return MlValue("write-file", builtin::write_file);
|
||||
if (name == "read-url") return MlValue("read-url", builtin::read_url);
|
||||
if (name == "system-cmd") return MlValue("system-cmd", builtin::system_cmd);
|
||||
|
||||
Reference in New Issue
Block a user