fold.h 923 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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/forward.h>
  10. #include <stream/detail/identity.h>
  11. #include <stream/detail/traits.h>
  12. #include <stream/detail/macro.h>
  13. namespace stream::ranges {
  14. template <typename It, typename S, typename T, typename F>
  15. auto fold_left(It it, S end, T init, F reduce) {
  16. for (; it != end; ++it) {
  17. init = std::invoke(reduce, init, *it);
  18. }
  19. return init;
  20. }
  21. template <typename Stream, typename T, typename F>
  22. auto fold_left(Stream && stream, T init, F reduce) {
  23. for (auto && elem : FWD(stream)) {
  24. init = std::invoke(reduce, init, FWD(elem));
  25. }
  26. return init;
  27. }
  28. template <typename Stream, typename F>
  29. auto fold_left_with_first(Stream && stream, F reduce) {
  30. return fold_left(++stream.begin(), stream.end(), *stream.begin(),
  31. std::ref(reduce));
  32. }
  33. }
  34. #include <stream/detail/undef.h>