[libcxx-commits] [libcxx] [libc++] Implement `ranges::fold_right` (PR #193997)
Connector Switch via libcxx-commits
libcxx-commits at lists.llvm.org
Fri Apr 24 09:01:17 PDT 2026
https://github.com/c8ef created https://github.com/llvm/llvm-project/pull/193997
None
>From 480662cf3ae212edb4f2ec6fafdafd204fc067b8 Mon Sep 17 00:00:00 2001
From: c8ef <c8ef at outlook.com>
Date: Sat, 25 Apr 2026 00:00:21 +0800
Subject: [PATCH] implement fold_right
---
libcxx/docs/ReleaseNotes/23.rst | 4 +-
libcxx/docs/Status/Cxx23Papers.csv | 2 +-
libcxx/include/__algorithm/ranges_fold.h | 52 +++++
libcxx/include/algorithm | 8 +
libcxx/modules/std/algorithm.inc | 2 +-
.../algorithms/nonmodifying/fold.bench.cpp | 7 +-
.../libcxx/algorithms/nodiscard.verify.cpp | 4 +
.../alg.fold/ranges.fold_right.pass.cpp | 196 ++++++++++++++++++
.../niebloid.compile.pass.cpp | 1 +
9 files changed, 268 insertions(+), 8 deletions(-)
create mode 100644 libcxx/test/std/algorithms/alg.nonmodifying/alg.fold/ranges.fold_right.pass.cpp
diff --git a/libcxx/docs/ReleaseNotes/23.rst b/libcxx/docs/ReleaseNotes/23.rst
index 0160ea2179ccc..e99d821acaf8d 100644
--- a/libcxx/docs/ReleaseNotes/23.rst
+++ b/libcxx/docs/ReleaseNotes/23.rst
@@ -45,8 +45,8 @@ Implemented Papers
- P2781R9: ``std::constant_wrapper`` (`Github <https://llvm.org/PR148179>`__)
- P3978R3: ``constant_wrapper`` should unwrap on call and subscript (`Github <https://llvm.org/PR189605>`__)
- P2164R9: ``views::enumerate`` (`Github <https://llvm.org/PR105251>`__)
-- P2322R6 (partial): ``ranges::fold_left_first`` and ``ranges::fold_left_first_with_iter`` are supported
- (`Github <https://llvm.org/PR105208>`__)
+- P2322R6 (partial): ``ranges::fold_left_first``, ``ranges::fold_left_first_with_iter``, ``ranges::fold_right`` are
+ supported (`Github <https://llvm.org/PR105208>`__)
Improvements and New Features
-----------------------------
diff --git a/libcxx/docs/Status/Cxx23Papers.csv b/libcxx/docs/Status/Cxx23Papers.csv
index 80ed7dba3ead7..9ab92b2a04920 100644
--- a/libcxx/docs/Status/Cxx23Papers.csv
+++ b/libcxx/docs/Status/Cxx23Papers.csv
@@ -65,7 +65,7 @@
"`P2286R8 <https://wg21.link/P2286R8>`__","Formatting Ranges","2022-07 (Virtual)","|Complete|","16","`#105202 <https://github.com/llvm/llvm-project/issues/105202>`__",""
"`P2291R3 <https://wg21.link/P2291R3>`__","Add Constexpr Modifiers to Functions ``to_chars`` and ``from_chars`` for Integral Types in ``<charconv>`` Header","2022-07 (Virtual)","|Complete|","16","`#105204 <https://github.com/llvm/llvm-project/issues/105204>`__",""
"`P2302R4 <https://wg21.link/P2302R4>`__","``std::ranges::contains``","2022-07 (Virtual)","|Complete|","19","`#105206 <https://github.com/llvm/llvm-project/issues/105206>`__",""
-"`P2322R6 <https://wg21.link/P2322R6>`__","``ranges::fold``","2022-07 (Virtual)","|Partial|","","Only ``fold_left_with_iter``, ``fold_left``, ``fold_left_first_with_iter``, and ``fold_left_first`` are implemented."
+"`P2322R6 <https://wg21.link/P2322R6>`__","``ranges::fold``","2022-07 (Virtual)","|Partial|","","Only ``fold_left_with_iter``, ``fold_left``, ``fold_left_first_with_iter``, ``fold_left_first`` and ``fold_right`` are implemented."
"`P2374R4 <https://wg21.link/P2374R4>`__","``views::cartesian_product``","2022-07 (Virtual)","","","`#105209 <https://github.com/llvm/llvm-project/issues/105209>`__",""
"`P2404R3 <https://wg21.link/P2404R3>`__","Move-only types for ``equality_comparable_with``, ``totally_ordered_with``, and ``three_way_comparable_with``","2022-07 (Virtual)","|Complete|","22","`#105210 <https://github.com/llvm/llvm-project/issues/105210>`__","Implemented as a DR in C++20."
"`P2408R5 <https://wg21.link/P2408R5>`__","Ranges iterators as inputs to non-Ranges algorithms","2022-07 (Virtual)","","","`#105211 <https://github.com/llvm/llvm-project/issues/105211>`__",""
diff --git a/libcxx/include/__algorithm/ranges_fold.h b/libcxx/include/__algorithm/ranges_fold.h
index 50776a2f1b808..147e9cf72dc96 100644
--- a/libcxx/include/__algorithm/ranges_fold.h
+++ b/libcxx/include/__algorithm/ranges_fold.h
@@ -23,6 +23,7 @@
#include <__iterator/concepts.h>
#include <__iterator/iterator_traits.h>
#include <__iterator/next.h>
+#include <__iterator/reverse_iterator.h>
#include <__ranges/access.h>
#include <__ranges/concepts.h>
#include <__ranges/dangling.h>
@@ -83,6 +84,22 @@ concept __indirectly_binary_left_foldable =
invocable<_Fp&, _Tp, iter_reference_t<_Ip>> && //
__indirectly_binary_left_foldable_impl<_Fp, _Tp, _Ip, invoke_result_t<_Fp&, _Tp, iter_reference_t<_Ip>>>;
+template <class _Func>
+struct __flipped {
+ _Func __func;
+
+ template <class _Tp, class _Up>
+ requires invocable<_Func&, _Up, _Tp>
+ invoke_result_t<_Func&, _Up, _Tp> operator()(_Tp&&, _Up&&);
+};
+
+template <class _Func, class _Tp, class _Iter>
+concept __indirectly_binary_right_foldable =
+ __indirectly_binary_left_foldable_impl<__flipped<_Func>,
+ _Tp,
+ _Iter,
+ invoke_result_t<_Func&, _Tp, iter_reference_t<_Iter>>>;
+
struct __fold_left_with_iter {
template <input_iterator _Ip, sentinel_for<_Ip> _Sp, class _Tp, __indirectly_binary_left_foldable<_Tp, _Ip> _Fp>
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI static constexpr auto operator()(_Ip __first, _Sp __last, _Tp __init, _Fp __f) {
@@ -187,6 +204,41 @@ struct __fold_left_first {
};
inline constexpr auto fold_left_first = __fold_left_first();
+
+struct __fold_right {
+ template <bidirectional_iterator _Iter,
+ sentinel_for<_Iter> _Sp,
+ class _Tp,
+ __indirectly_binary_right_foldable<_Tp, _Iter> _Func>
+ [[nodiscard]] _LIBCPP_HIDE_FROM_ABI static constexpr auto
+ operator()(_Iter __first, _Sp __last, _Tp __init, _Func __func) {
+ using _Up = decay_t<invoke_result_t<_Func&, iter_reference_t<_Iter>, _Tp>>;
+
+ if (__first == __last)
+ return _Up(std::move(__init));
+
+ _Iter __tail = ranges::next(__first, __last);
+ --__tail;
+ _Up __result = std::invoke(__func, *__tail, std::move(__init));
+ __identity __proj;
+ std::__for_each(
+ std::make_reverse_iterator(__tail),
+ std::make_reverse_iterator(__first),
+ [&](auto&& __element) {
+ __result = std::invoke(__func, std::forward<decltype(__element)>(__element), std::move(__result));
+ },
+ __proj);
+
+ return __result;
+ }
+
+ template <bidirectional_range _Range, class _Tp, __indirectly_binary_right_foldable<_Tp, iterator_t<_Range>> _Func>
+ [[nodiscard]] _LIBCPP_HIDE_FROM_ABI static constexpr auto operator()(_Range&& __range, _Tp __init, _Func __func) {
+ return operator()(ranges::begin(__range), ranges::end(__range), std::move(__init), std::ref(__func));
+ }
+};
+
+inline constexpr auto fold_right = __fold_right();
} // namespace ranges
#endif // _LIBCPP_STD_VER >= 23
diff --git a/libcxx/include/algorithm b/libcxx/include/algorithm
index 2418d03d69f11..d332b8ce4fd70 100644
--- a/libcxx/include/algorithm
+++ b/libcxx/include/algorithm
@@ -960,6 +960,14 @@ namespace ranges {
requires constructible_from<range_value_t<R>, range_reference_t<R>>
constexpr auto ranges::fold_left_first(R&& r, F f); // since C++23
+ template<bidirectional_iterator I, sentinel_for<I> S, class T = iter_value_t<I>,
+ indirectly-binary-right-foldable<T, I> F>
+ constexpr auto ranges::fold_right(I first, S last, T init, F f);
+
+ template<bidirectional_range R, class T = range_value_t<R>,
+ indirectly-binary-right-foldable<T, iterator_t<R>> F>
+ constexpr auto ranges::fold_right(R&& r, T init, F f);
+
template<class I, class T>
using fold_left_with_iter_result = in_value_result<I, T>; // since C++23
diff --git a/libcxx/modules/std/algorithm.inc b/libcxx/modules/std/algorithm.inc
index 512145a3435c7..3a59726135fe7 100644
--- a/libcxx/modules/std/algorithm.inc
+++ b/libcxx/modules/std/algorithm.inc
@@ -169,8 +169,8 @@ export namespace std {
using std::ranges::fold_left_first_with_iter_result;
using std::ranges::fold_left_with_iter;
using std::ranges::fold_left_with_iter_result;
-# if 0
using std::ranges::fold_right;
+# if 0
using std::ranges::fold_right_last;
# endif
#endif // _LIBCPP_STD_VER >= 23
diff --git a/libcxx/test/benchmarks/algorithms/nonmodifying/fold.bench.cpp b/libcxx/test/benchmarks/algorithms/nonmodifying/fold.bench.cpp
index f6d89ea14e949..1e061cee3a07a 100644
--- a/libcxx/test/benchmarks/algorithms/nonmodifying/fold.bench.cpp
+++ b/libcxx/test/benchmarks/algorithms/nonmodifying/fold.bench.cpp
@@ -71,10 +71,9 @@ int main(int argc, char** argv) {
bm.operator()<std::deque<unsigned int>>("rng::fold_left_first(deque<int>)", std_ranges_fold_left_first);
bm.operator()<std::list<unsigned int>>("rng::fold_left_first(list<int>)", std_ranges_fold_left_first);
- // TODO: fold_right not implemented yet
- // bm.operator()<std::vector<unsigned int>>("rng::fold_right(vector<int>)", std::ranges::fold_right);
- // bm.operator()<std::deque<unsigned int>>("rng::fold_right(deque<int>)", std::ranges::fold_right);
- // bm.operator()<std::list<unsigned int>>("rng::fold_right(list<int>)", std::ranges::fold_right);
+ bm.operator()<std::vector<unsigned int>>("rng::fold_right(vector<int>)", std::ranges::fold_right);
+ bm.operator()<std::deque<unsigned int>>("rng::fold_right(deque<int>)", std::ranges::fold_right);
+ bm.operator()<std::list<unsigned int>>("rng::fold_right(list<int>)", std::ranges::fold_right);
}
benchmark::Initialize(&argc, argv);
diff --git a/libcxx/test/libcxx/algorithms/nodiscard.verify.cpp b/libcxx/test/libcxx/algorithms/nodiscard.verify.cpp
index ccedadfba7e6a..4530d8c9507f6 100644
--- a/libcxx/test/libcxx/algorithms/nodiscard.verify.cpp
+++ b/libcxx/test/libcxx/algorithms/nodiscard.verify.cpp
@@ -404,5 +404,9 @@ void test() {
// expected-warning at -1{{ignoring return value of function declared with 'nodiscard' attribute}}
std::ranges::fold_left_first_with_iter(iter, iter, std::plus());
// expected-warning at -1{{ignoring return value of function declared with 'nodiscard' attribute}}
+ std::ranges::fold_right(range, 0, std::plus());
+ // expected-warning at -1{{ignoring return value of function declared with 'nodiscard' attribute}}
+ std::ranges::fold_right(iter, iter, 0, std::plus());
+ // expected-warning at -1{{ignoring return value of function declared with 'nodiscard' attribute}}
#endif
}
diff --git a/libcxx/test/std/algorithms/alg.nonmodifying/alg.fold/ranges.fold_right.pass.cpp b/libcxx/test/std/algorithms/alg.nonmodifying/alg.fold/ranges.fold_right.pass.cpp
new file mode 100644
index 0000000000000..26437884c55b6
--- /dev/null
+++ b/libcxx/test/std/algorithms/alg.nonmodifying/alg.fold/ranges.fold_right.pass.cpp
@@ -0,0 +1,196 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <algorithm>
+
+// REQUIRES: std-at-least-c++23
+
+// template<bidirectional_iterator I, sentinel_for<I> S, class T = iter_value_t<I>,
+// indirectly-binary-right-foldable<T, I> F>
+// constexpr auto ranges::fold_right(I first, S last, T init, F f);
+
+// template<bidirectional_range R, class T = range_value_t<R>,
+// indirectly-binary-right-foldable<T, iterator_t<R>> F>
+// constexpr auto ranges::fold_right(R&& r, T init, F f);
+
+#include <algorithm>
+#include <cassert>
+#include <concepts>
+#include <deque>
+#include <functional>
+#include <iterator>
+#include <list>
+#include <ranges>
+#include <set>
+#include <string_view>
+#include <string>
+#include <vector>
+
+#include "test_macros.h"
+#include "test_range.h"
+#include "invocable_with_telemetry.h"
+#include "maths.h"
+
+using std::ranges::fold_right;
+
+template <std::ranges::input_range R, class T, class F, std::equality_comparable Expected>
+ requires std::copyable<R>
+constexpr void check_iterator(R& r, T const& init, F f, Expected const& expected) {
+ {
+ std::same_as<Expected> decltype(auto) result = fold_right(r.begin(), r.end(), init, f);
+ assert(result == expected);
+ }
+
+ {
+ auto telemetry = invocable_telemetry();
+ auto f2 = invocable_with_telemetry(f, telemetry);
+ std::same_as<Expected> decltype(auto) result = fold_right(r.begin(), r.end(), init, f2);
+ assert(result == expected);
+ assert(telemetry.invocations == std::ranges::distance(r));
+ assert(telemetry.moves == 0);
+ assert(telemetry.copies == 1);
+ }
+}
+
+template <std::ranges::input_range R, class T, class F, std::equality_comparable Expected>
+ requires std::copyable<R>
+constexpr void check_lvalue_range(R& r, T const& init, F f, Expected const& expected) {
+ {
+ std::same_as<Expected> decltype(auto) result = fold_right(r, init, f);
+ assert(result == expected);
+ }
+
+ {
+ auto telemetry = invocable_telemetry();
+ auto f2 = invocable_with_telemetry(f, telemetry);
+ std::same_as<Expected> decltype(auto) result = fold_right(r, init, f2);
+ assert(result == expected);
+ assert(telemetry.invocations == std::ranges::distance(r));
+ assert(telemetry.moves == 0);
+ assert(telemetry.copies == 1);
+ }
+}
+
+template <std::ranges::input_range R, class T, class F, std::equality_comparable Expected>
+ requires std::copyable<R>
+constexpr void check_rvalue_range(R& r, T const& init, F f, Expected const& expected) {
+ {
+ auto r2 = r;
+ std::same_as<Expected> decltype(auto) result = fold_right(std::move(r2), init, f);
+ assert(result == expected);
+ }
+
+ {
+ auto telemetry = invocable_telemetry();
+ auto f2 = invocable_with_telemetry(f, telemetry);
+ auto r2 = r;
+ std::same_as<Expected> decltype(auto) result = fold_right(std::move(r2), init, f2);
+ assert(result == expected);
+ assert(telemetry.invocations == std::ranges::distance(r));
+ assert(telemetry.moves == 0);
+ assert(telemetry.copies == 1);
+ }
+}
+
+template <std::ranges::input_range R, class T, class F, std::equality_comparable Expected>
+ requires std::copyable<R>
+constexpr void check(R r, T const& init, F f, Expected const& expected) {
+ check_iterator(r, init, f, expected);
+ check_lvalue_range(r, init, f, expected);
+ check_rvalue_range(r, init, f, expected);
+}
+
+constexpr void empty_range_test_case() {
+ auto const data = std::vector<int>{};
+ check(data, 100, std::plus(), 100);
+ check(data, -100, std::multiplies(), -100);
+}
+
+constexpr void common_range_test_case() {
+ auto const data = std::vector<int>{1, 2, 3, 4};
+ check(data, 0, std::plus(), triangular_sum(data));
+ check(data, 1, std::multiplies(), factorial(data.back()));
+
+ auto multiply_with_next = [n = 1](auto const x, auto const y) mutable {
+ auto const result = x * y * n;
+ n = x;
+ return static_cast<std::size_t>(result);
+ };
+ check(data, 1, multiply_with_next, factorial(data.size()) * factorial(data.size()));
+
+ auto fib = [n = 1](auto x, auto) mutable {
+ auto old_x = x;
+ x += n;
+ n = old_x;
+ return x;
+ };
+ check(data, 0, fib, fibonacci(data.back()));
+}
+
+constexpr void non_common_range_test_case() {
+ auto parse = [](std::string_view const s) {
+ return s == "zero" ? 0.0
+ : s == "one" ? 1.0
+ : s == "two" ? 2.0
+ : s == "three" ? 3.0
+ : s == "four" ? 4.0
+ : s == "five" ? 5.0
+ : s == "six" ? 6.0
+ : s == "seven" ? 7.0
+ : s == "eight" ? 8.0
+ : s == "nine" ? 9.0
+ : (assert(false), 10.0); // the number here is arbitrary
+ };
+
+ {
+ auto data = std::vector<std::string>{"five", "three", "two", "six", "one", "four"};
+ auto range = data | std::views::transform(parse);
+ check(range, 0, std::plus(), triangular_sum(range));
+ }
+}
+
+constexpr bool test_case() {
+ empty_range_test_case();
+ common_range_test_case();
+ non_common_range_test_case();
+ return true;
+}
+
+// Most containers aren't constexpr
+void runtime_only_test_case() {
+ {
+ auto const data = std::list<int>{2, 4, 6, 8, 10, 12};
+ auto const expected = triangular_sum(data);
+ check(data, 0, std::plus<long>(), static_cast<long>(expected));
+ }
+
+ {
+ auto const data = std::deque<double>{-1.1, -2.2, -3.3, -4.4, -5.5, -6.6};
+ auto plus = [](double const x, int const y) { return x + y; };
+ auto const expected = -21.1; // -6.6 + int( 0.0) = -6.6 + 0 = -6.6
+ // -5.5 + int(- 6.6) = -5.5 + -6 = -11.5
+ // -4.4 + int(-11.5) = -4.4 + -11 = -15.4
+ // -3.3 + int(-15.4) = -3.3 + -15 = -18.3
+ // -2.2 + int(-18.3) = -2.2 + -18 = -20.2
+ // -1.1 + int(-20.2) = -1.1 + -20 = -21.1.
+ check(data, 0.0, plus, expected);
+ }
+
+ {
+ auto const data = std::set<int>{2, 4, 6, 8, 10, 12};
+ auto const expected = triangular_sum(data);
+ check(data, 0, std::plus<long>(), static_cast<long>(expected));
+ }
+}
+
+int main(int, char**) {
+ test_case();
+ static_assert(test_case());
+ runtime_only_test_case();
+ return 0;
+}
diff --git a/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp b/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp
index ad26aefb93159..7c67e7083e88d 100644
--- a/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp
+++ b/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp
@@ -101,6 +101,7 @@ static_assert(test(std::ranges::fold_left, a, 0, std::plus()));
static_assert(test(std::ranges::fold_left_with_iter, a, 0, std::plus()));
static_assert(test(std::ranges::fold_left_first, a, std::plus()));
static_assert(test(std::ranges::fold_left_first_with_iter, a, std::plus()));
+static_assert(test(std::ranges::fold_right, a, 0, std::plus()));
#endif
static_assert(test(std::ranges::for_each, a, odd));
static_assert(test(std::ranges::for_each_n, a, 10, odd));
More information about the libcxx-commits
mailing list