[libcxx-commits] [libcxx] [libc++] Add `ranges::fold_left_first` and `ranges::fold_left_first_with_iter` (PR #121558)

Connector Switch via libcxx-commits libcxx-commits at lists.llvm.org
Fri Feb 6 07:52:28 PST 2026


================
@@ -118,6 +122,53 @@ struct __fold_left {
 };
 
 inline constexpr auto fold_left = __fold_left();
+
+struct __fold_left_first_with_iter {
+  template <input_iterator _Ip, sentinel_for<_Ip> _Sp, __indirectly_binary_left_foldable<iter_value_t<_Ip>, _Ip> _Fp>
+    requires constructible_from<iter_value_t<_Ip>, iter_reference_t<_Ip>>
+  [[nodiscard]] _LIBCPP_HIDE_FROM_ABI static constexpr auto operator()(_Ip __first, _Sp __last, _Fp __f) {
+    using _Up = decltype(fold_left(std::move(__first), __last, iter_value_t<_Ip>(*__first), __f));
+
+    // case of empty range
+    if (__first == __last)
+      return fold_left_first_with_iter_result<_Ip, optional<_Up>>{std::move(__first), optional<_Up>()};
+
+    _Up __result(*__first);
+    for (++__first; __first != __last; ++__first)
+      __result = std::invoke(__f, std::move(__result), *__first);
+
+    return fold_left_first_with_iter_result<_Ip, optional<_Up>>{std::move(__first), optional<_Up>(std::move(__result))};
+  }
+
+  template <input_range _Rp, __indirectly_binary_left_foldable<range_value_t<_Rp>, iterator_t<_Rp>> _Fp>
+    requires constructible_from<range_value_t<_Rp>, range_reference_t<_Rp>>
+  [[nodiscard]] _LIBCPP_HIDE_FROM_ABI static constexpr auto operator()(_Rp&& __r, _Fp __f) {
+    auto __result = operator()(ranges::begin(__r), ranges::end(__r), std::ref(__f));
+
+    using _Up = decltype(fold_left(ranges::begin(__r), ranges::end(__r), range_value_t<_Rp>(*ranges::begin(__r)), __f));
+    return fold_left_first_with_iter_result<borrowed_iterator_t<_Rp>, optional<_Up>>{
+        std::move(__result.in), std::move(__result.value)};
+  }
----------------
c8ef wrote:

https://github.com/llvm/llvm-project/pull/180214/changes#r2774809922

https://github.com/llvm/llvm-project/pull/121558


More information about the libcxx-commits mailing list