История изменений
Исправление quasimoto, (текущая версия) :
#include <iostream>
#include <functional>
#include <vector>
template <typename T>
struct stream {
T first;
std::function<stream()> rest;
};
template <typename T>
std::vector<T> take(std::size_t n, stream<T> stream)
{
std::vector<T> result;
for (; n > 0; --n, stream = stream.rest())
result.push_back(stream.first);
return result;
}
stream<int> f(int a, int b)
{
return { a, [=]() { return f(b, a); } };
}
int main()
{
auto xs = take(10, f(1, 2));
for (auto &x : xs)
std::cout << x << ' ';
std::cout << std::endl;
}
/*
total heap usage: 16 allocs, 16 frees, 212 bytes allocated
*/
Исходная версия quasimoto, :
#include <iostream>
#include <functional>
#include <vector>
template <typename T>
struct stream {
T first;
std::function<stream()> rest;
};
template <typename T>
std::vector<T> take(std::size_t n, stream<T> stream)
{
std::vector<T> result;
for (std::size_t i = 0; i < n; ++i, stream = stream.rest())
result.push_back(stream.first);
return result;
}
stream<int> f(int a, int b)
{
return { a, [=]() { return f(b, a); } };
}
int main()
{
auto xs = take(10, f(1, 2));
for (auto &x : xs)
std::cout << x << ' ';
std::cout << std::endl;
}
/*
total heap usage: 16 allocs, 16 frees, 212 bytes allocated
*/