fluent.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // fluent.hpp
  3. // stream
  4. //
  5. // Created by Sam Jaffe on 1/28/17.
  6. //
  7. #pragma once
  8. #include "../streams.hpp"
  9. #include <numeric>
  10. namespace stream {
  11. template <typename T, typename R>
  12. struct map {
  13. template <typename F>
  14. explicit map(F&& f) : func(f) {}
  15. std::function<R(const T&)> func;
  16. };
  17. template <typename T, typename R>
  18. struct flatmap {
  19. template <typename F>
  20. explicit flatmap(F&& f) : func(f) {}
  21. std::function<R(const T&)> func;
  22. };
  23. template <typename T>
  24. struct filter {
  25. template <typename F>
  26. explicit filter(F&& f) : pred(f) {}
  27. std::function<bool(const T&)> pred;
  28. };
  29. template <typename L, typename R>
  30. struct fold_left {
  31. template <typename F>
  32. explicit fold_left(F&& f) : init(), fold(f) {}
  33. template <typename F>
  34. fold_left(L const & i, F&& f) : init(i), fold(f) {}
  35. L init;
  36. std::function<L(const L&, const R&)> fold;
  37. };
  38. }
  39. namespace stream { namespace detail {
  40. template <typename T, typename R>
  41. stream_base<R> operator|(stream_base<T> const&s, ::stream::map<T, R>&& f) {
  42. return s.map(f.func);
  43. }
  44. template <typename T, typename C>
  45. stream_base<typename C::value_type> operator|(stream_base<T> const&s, ::stream::flatmap<T, C>&& f) {
  46. return s.flatmap(f.func);
  47. }
  48. template <typename T>
  49. stream_base<T> operator|(stream_base<T> const&s, ::stream::filter<T>&& f) {
  50. return s.filter(f.pred);
  51. }
  52. template <typename L, typename R>
  53. L operator >(stream_base<R> const &s, ::stream::fold_left<L, R> && f) {
  54. return std::accumulate(s.begin(), s.end(), f.init, f.fold);
  55. }
  56. } }