| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- #include <vector>
- #include <iostream>
- #include <iterator>
- #include "streams.hpp"
- namespace stream {
- template <typename T, typename F>
- auto make_map_t(F&& func) -> map_t<T, decltype(func(std::declval<T>()))> {
- return map_t<T, decltype(func(std::declval<T>()))>{func};
- }
-
- template <typename T, typename F>
- auto make_flatmap_t(F&& func) -> flatmap_t<T, decltype(func(std::declval<T>()))> {
- return flatmap_t<T, decltype(func(std::declval<T>()))>{func};
- }
- template <typename T, typename F>
- auto make_filter_t(F&& func) -> filter_t<T> {
- return filter_t<T>{func};
- }
- }
- #define map(t, x, expr) stream::make_map_t<t>([](t x) { return expr; })
- #define filter(t, x, expr) stream::make_filter_t<t>([](t x) { return expr; })
- #define flatmap(t, x, expr) stream::make_flatmap_t<t>([](t x) { return expr; })
- #define fold(t, x, y, expr, init) stream::make_fold_t<t>([](t x, t y) { return expr; })
- template <typename T>
- std::ostream& operator<<(std::ostream& os, std::vector<T> const& tmp) {
- os << "{ ";
- for (auto it = tmp.begin(); it != tmp.end(); ++it) {
- os << *it << ", ";
- }
- return os << "\b\b }";
- }
- std::vector<int> iota(int max) {
- std::vector<int> r(3);
- std::iota(r.begin(), r.end(), max);
- return r;
- }
- int main(int argc, const char**argv) {
- std::vector<int> vec{1,2,3,4,5};
- // auto s = stream::make_stream(vec) | stream::map_t<int, int>([](int x) { return x*2; });
- auto s = stream::make_stream(vec) | filter(int, x, x%2==0) | map(int, x, x*2);
- std::cout << "The result of the expression 'stream(vec) | filter(x,x%2==0) | map(x,x*2)' is:\n\t";
- std::cout << "{ ";
- for (auto it = s.begin(); it != s.end(); ++it) {
- std::cout << *it << ", ";
- }
- std::cout << "\b\b }" << std::endl;
- std::cout << "The result of the expression 'stream(vec) | filter(x,x%2==0) | map(x,x*2) | fold(i,j,i*j,1)' is:\n\t";
- std::cout << s.accumulate([](int i, int j){return i*j;},1);
- std::cout << std::endl;
- auto t = s | flatmap(int, x, std::vector<double>{1/(double)x});
- std::cout << "The result of the expression 'stream(vec) | filter(x,x%2==0) | map(x,x*2) | map(x, [1/x])' is:\n\t";
- std::cout << "{ ";
- for (auto it = t.begin(); it != t.end(); ++it) {
- std::cout << *it << ", ";
- }
- std::cout << "\b\b }" << std::endl;
- auto q = stream::make_stream(vec) | filter(int, x, x%2==1) | map(int, x, iota(x));
- std::cout << "The result of the expression 'stream(vec) | filter(x,x%2==1) | map(x,iota(x))' is:\n\t";
- std::cout << "{ ";
- for (auto it = q.begin(); it != q.end(); ++it) {
- std::cout << *it << ", ";
- }
- std::cout << "\b\b }" << std::endl;
- return 0;
- }
|