Skip to content

Instantly share code, notes, and snippets.

@mpapierski
Created May 5, 2015 17:45
Show Gist options
  • Save mpapierski/507988c10b6830cfd55b to your computer and use it in GitHub Desktop.
Save mpapierski/507988c10b6830cfd55b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <stdexcept>
#include <fstream>
#include <memory>
struct stop : std::runtime_error
{
stop() : std::runtime_error("nie dla psa xD") {}
};
struct generator
{
};
struct readlines_impl
: generator
{
std::shared_ptr<std::ifstream> ifs_;
readlines_impl(std::string filename)
: ifs_(new std::ifstream(filename))
{
}
std::string operator()()
{
std::string line;
if (!std::getline(*ifs_, line))
{
throw stop();
}
return line;
}
};
namespace File {
readlines_impl readlines(std::string filename)
{
return readlines_impl(filename);
}
}
struct range_impl
: generator
{
int from_;
int to_;
range_impl(int from, int to)
: from_(from)
, to_(to)
{}
int operator()()
{
int value = from_++;
if (value > to_)
{
throw stop();
}
return value;
}
};
range_impl range(int from, int to)
{
return range_impl(from, to);
}
template <typename T>
struct iter_impl
{
T t_;
iter_impl(T t)
: t_(t)
{}
template <typename Callback>
void map(Callback callback)
{
while (true)
{
try
{
auto value = t_();
callback(value);
}
catch (stop &)
{
break;
}
}
}
};
template <typename T>
iter_impl<T> iter(T t)
{
return iter_impl<T>(t);
}
int
main(int argc, char * argv[])
{
if (argc < 2)
{
std::cerr << "usage: " << argv[0] << " [filename]" << std::endl;
return 1;
}
iter(File::readlines(argv[1]))
.map([&](std::string huj) {
std::cout << "Line: " << huj << std::endl;
});
iter(range(1, 10))
.map([](int value) { std::cout << value << std::endl; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment