fold.h 883 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // accumulate.h
  3. // stream
  4. //
  5. // Created by Sam Jaffe on 3/29/23.
  6. //
  7. #pragma once
  8. #include <optional>
  9. #include <stream/detail/identity.h>
  10. #include <stream/detail/traits.h>
  11. #define FWD(x) std::forward<decltype(x)>(x)
  12. namespace stream::ranges {
  13. template <typename It, typename S, typename T, typename F>
  14. auto fold_left(It it, S end, T init, F reduce) {
  15. for (; it != end; ++it) {
  16. init = std::invoke(reduce, init, *it);
  17. }
  18. return init;
  19. }
  20. template <typename Stream, typename T, typename F>
  21. auto fold_left(Stream && stream, T init, F reduce) {
  22. for (auto && elem : FWD(stream)) {
  23. init = std::invoke(reduce, init, FWD(elem));
  24. }
  25. return init;
  26. }
  27. template <typename Stream, typename F>
  28. auto fold_left_with_first(Stream && stream, F reduce) {
  29. return fold_left(++stream.begin(), stream.end(), *stream.begin(),
  30. std::ref(reduce));
  31. }
  32. }
  33. #undef FWD