Added support for monadic operations on the named tuples

This commit is contained in:
Patrick Urbanke
2024-03-06 14:21:33 +01:00
parent 1e6bf03387
commit 58f1e41c83
9 changed files with 318 additions and 21 deletions
+59
View File
@@ -114,6 +114,65 @@ person.apply([]<typename Field>(Field& f) {
});
```
### Monadic operations: `.transform` and `.and_then`
Named tuples also contain compile-time monadic operations.
`.transform(f)` expects a function `f` of type `Field -> Field`.
`transform` then applies that function to each field of the named tuple.
It can be used to change either the values or the names of the fields, but
not their overall number.
```cpp
const auto lisa =
Person{.first_name = "Lisa", .last_name = "Simpson", .age = 8};
const auto to_bart = [](auto field) {
if constexpr (decltype(field)::name() == "first_name") {
field = "Bart";
return field;
} else if constexpr (decltype(field)::name() == "age") {
field = 10;
return field;
} else {
return field;
}
};
// bart will now be a named tuple with first_name="Bart",
// last_name="Simpson", age=10
const auto bart = rfl::to_named_tuple(lisa).transform(to_bart);
```
`.and_then(f)` expects a function `f` of type `Field -> NamedTuple`.
`and_then` then applies that function to each field of the named tuple
and finally concatenates the resulting named tuple to form a new named tuple.
Note that the named tuple returned by `f` may be empty. `.and_then(f)` can be used
to change either the values or the names of the fields, and can also affect
their overall number.
```cpp
const auto lisa =
Person{.first_name = "Lisa", .last_name = "Simpson", .age = 8};
const auto to_bart = [](auto field) {
if constexpr (decltype(field)::name() == "first_name") {
field = "Bart";
return rfl::make_named_tuple(field);
} else if constexpr (decltype(field)::name() == "age") {
return rfl::make_named_tuple();
} else {
return rfl::make_named_tuple(field);
}
};
// bart will now be a named tuple with first_name="Bart",
// last_name="Simpson". Since we have returned and empty
// named tuple for the field "age", there will be no such
// field in bart.
const auto bart = rfl::to_named_tuple(lisa).and_then(to_bart);
```
### `rfl::replace`
`rfl::replace` works for `rfl::NamedTuple` as well:
+147 -13
View File
@@ -18,6 +18,13 @@ namespace rfl {
/// A named tuple behaves like std::tuple,
/// but the fields have explicit names, which
/// allows for reflection.
/// IMPORTANT: We have two template specializations. One with fields, one
/// without fields.
template <class... FieldTypes>
class NamedTuple;
// ----------------------------------------------------------------------------
template <class... FieldTypes>
class NamedTuple {
public:
@@ -162,24 +169,51 @@ class NamedTuple {
std::forward<Tail>(_tail)...);
}
/// Invokes a callable object once for each field in order.
/// Creates a new named tuple by applying the supplied function to
/// field. The function is expected to return a named tuple itself.
template <typename F>
void apply(F&& f) {
std::apply(
[&f]<typename... AFields>(AFields&&... fields) {
((f(std::forward<AFields>(fields))), ...);
},
fields());
auto and_then(const F& _f) {
const auto transform_field = [&_f](auto... _fields) {
return std::tuple_cat(_f(std::move(_fields)).fields()...);
};
const auto to_nt = []<class... NewFields>(std::tuple<NewFields...>&& _tup) {
return NamedTuple<NewFields...>(_tup);
};
auto new_fields = std::apply(transform_field, std::move(fields()));
return to_nt(std::move(new_fields));
}
/// Creates a new named tuple by applying the supplied function to
/// field. The function is expected to return a named tuple itself.
template <typename F>
auto and_then(const F& _f) const {
const auto transform_field = [&_f](auto... _fields) {
return std::tuple_cat(_f(std::move(_fields)).fields()...);
};
const auto to_nt = []<class... NewFields>(std::tuple<NewFields...>&& _tup) {
return NamedTuple<NewFields...>(_tup);
};
auto new_fields = std::apply(transform_field, std::move(fields()));
return to_nt(std::move(new_fields));
}
/// Invokes a callable object once for each field in order.
template <typename F>
void apply(F&& f) const {
std::apply(
[&f]<typename... AFields>(AFields&&... fields) {
((f(std::forward<AFields>(fields))), ...);
},
fields());
void apply(const F& _f) {
const auto apply_to_field =
[&_f]<typename... AFields>(AFields&&... fields) {
((_f(std::forward<AFields>(fields))), ...);
};
std::apply(apply_to_field, fields());
}
/// Invokes a callable object once for each field in order.
template <typename F>
void apply(const F& _f) const {
const auto apply_to_field = [&_f](const auto&... fields) {
((_f(fields)), ...);
};
std::apply(apply_to_field, fields());
}
/// Returns a tuple containing the fields.
@@ -312,6 +346,34 @@ class NamedTuple {
/// Returns the size of the named tuple
static constexpr size_t size() { return std::tuple_size_v<Values>; }
/// Creates a new named tuple by applying the supplied function to every
/// field.
template <typename F>
auto transform(const F& _f) {
const auto transform_field = [&_f](auto... fields) {
return std::make_tuple(_f(std::move(fields))...);
};
const auto to_nt = []<class... NewFields>(std::tuple<NewFields...>&& _tup) {
return NamedTuple<NewFields...>(_tup);
};
auto new_fields = std::apply(transform_field, std::move(fields()));
return to_nt(std::move(new_fields));
}
/// Creates a new named tuple by applying the supplied function to every
/// field.
template <typename F>
auto transform(const F& _f) const {
const auto transform_field = [&_f](auto... fields) {
return std::make_tuple(_f(std::move(fields))...);
};
const auto to_nt = []<class... NewFields>(std::tuple<NewFields...>&& _tup) {
return NamedTuple<NewFields...>(_tup);
};
auto new_fields = std::apply(transform_field, std::move(fields()));
return to_nt(std::move(new_fields));
}
/// Returns the underlying std::tuple.
Values& values() { return values_; }
@@ -488,6 +550,78 @@ class NamedTuple {
// ----------------------------------------------------------------------------
/// We need a special template instantiation for empty named tuples.
template <>
class NamedTuple<> {
public:
using Fields = std::tuple<>;
using Values = std::tuple<>;
NamedTuple(){};
~NamedTuple() = default;
/// Returns a new named tuple with additional fields.
template <class Head, class... Tail>
auto add(Head&& _head, Tail&&... _tail) const {
if constexpr (sizeof...(Tail) > 0) {
return NamedTuple<std::remove_cvref_t<Head>>(std::forward<Head>(_head))
.add(std::forward<Tail>(_tail)...);
} else {
return NamedTuple<std::remove_cvref_t<Head>>(std::forward<Head>(_head));
}
}
/// Template specialization for std::tuple, so we can pass fields from other
/// named tuples.
template <class... TupContent, class... Tail>
auto add(std::tuple<TupContent...>&& _tuple, Tail&&... _tail) const {
if constexpr (sizeof...(Tail) > 0) {
return NamedTuple<TupContent...>(
std::forward<std::tuple<TupContent...>>(_tuple))
.add(std::forward<Tail>(_tail)...);
} else {
return NamedTuple<TupContent...>(
std::forward<std::tuple<TupContent...>>(_tuple));
}
}
/// Template specialization for NamedTuple, so we can pass fields from other
/// named tuples.
template <class... TupContent, class... Tail>
auto add(NamedTuple<TupContent...>&& _named_tuple, Tail&&... _tail) const {
return add(std::forward<std::tuple<TupContent...>>(_named_tuple.fields()),
std::forward<Tail>(_tail)...);
}
/// Returns an empty named tuple.
template <typename F>
auto and_then(const F& _f) const {
return NamedTuple<>();
}
/// Does nothing at all.
template <typename F>
void apply(const F& _f) const {}
/// Returns an empty tuple.
auto fields() const { return std::tuple(); }
/// Must always be 0.
static constexpr size_t size() { return 0; }
/// Returns an empty named tuple.
template <typename F>
auto transform(const F& _f) const {
return NamedTuple<>();
}
/// Returns an empty tuple.
auto values() const { return std::tuple(); }
};
// ----------------------------------------------------------------------------
template <class... FieldTypes>
inline bool operator==(const rfl::NamedTuple<FieldTypes...>& _nt1,
const rfl::NamedTuple<FieldTypes...>& _nt2) {
+2 -2
View File
@@ -14,7 +14,7 @@ namespace rfl {
/// Generates the struct T from a named tuple.
template <class T, class NamedTupleType>
auto from_named_tuple(NamedTupleType&& _n) {
T from_named_tuple(NamedTupleType&& _n) {
using RequiredType = std::remove_cvref_t<rfl::named_tuple_t<T>>;
if constexpr (!std::is_same<std::remove_cvref_t<NamedTupleType>,
RequiredType>()) {
@@ -36,7 +36,7 @@ auto from_named_tuple(NamedTupleType&& _n) {
/// Generates the struct T from a named tuple.
template <class T, class NamedTupleType>
auto from_named_tuple(const NamedTupleType& _n) {
T from_named_tuple(const NamedTupleType& _n) {
using RequiredType = std::remove_cvref_t<rfl::named_tuple_t<T>>;
if constexpr (!std::is_same<std::remove_cvref_t<NamedTupleType>,
RequiredType>()) {
+9 -6
View File
@@ -8,20 +8,23 @@
namespace rfl {
/// Convenience constructor that doesn't require you
/// to explitly defined the field types.
/// to explitly define the field types.
template <class... FieldTypes>
auto make_named_tuple(FieldTypes&&... _args) {
inline auto make_named_tuple(FieldTypes&&... _args) {
return NamedTuple<std::remove_cvref_t<FieldTypes>...>(
std::forward<FieldTypes>(_args)...);
}
/// Convenience constructor that doesn't require you
/// to explitly defined the field types.
template <class Head, class... Tail>
auto make_named_tuple(const Head& _h, const Tail&... _t) {
return NamedTuple<Head, Tail...>(_h, _t...);
/// to explitly define the field types.
template <class... FieldTypes>
inline auto make_named_tuple(const FieldTypes&... _args) {
return NamedTuple<FieldTypes...>(_args...);
}
/// Explicit overload for creating empty named tuples.
inline auto make_named_tuple() { return NamedTuple<>(); }
} // namespace rfl
#endif // RFL_MAKENAMEDTUPLE_HPP_
+43
View File
@@ -0,0 +1,43 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <type_traits>
#include <vector>
#include "test_replace.hpp"
#include "write_and_read.hpp"
namespace test_and_then {
struct Person {
std::string first_name;
std::string last_name;
int age;
};
void test() {
std::cout << std::source_location::current().function_name() << std::endl;
const auto lisa =
Person{.first_name = "Lisa", .last_name = "Simpson", .age = 8};
const auto to_bart = [](auto field) {
if constexpr (decltype(field)::name() == "first_name") {
field = "Bart";
return rfl::make_named_tuple(field);
} else if constexpr (decltype(field)::name() == "age") {
return rfl::make_named_tuple();
} else {
return rfl::make_named_tuple(field);
}
};
const auto bart = rfl::to_named_tuple(lisa).and_then(to_bart);
write_and_read(bart, R"({"first_name":"Bart","last_name":"Simpson"})");
}
} // namespace test_and_then
+4
View File
@@ -0,0 +1,4 @@
namespace test_and_then {
void test();
}
+45
View File
@@ -0,0 +1,45 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <type_traits>
#include <vector>
#include "test_replace.hpp"
#include "write_and_read.hpp"
namespace test_transform {
struct Person {
std::string first_name;
std::string last_name;
int age;
};
void test() {
std::cout << std::source_location::current().function_name() << std::endl;
const auto lisa =
Person{.first_name = "Lisa", .last_name = "Simpson", .age = 8};
const auto to_bart = [](auto field) {
if constexpr (decltype(field)::name() == "first_name") {
field = "Bart";
return field;
} else if constexpr (decltype(field)::name() == "age") {
field = 10;
return field;
} else {
return field;
}
};
const auto bart = rfl::to_named_tuple(lisa).transform(to_bart);
write_and_read(bart,
R"({"first_name":"Bart","last_name":"Simpson","age":10})");
}
} // namespace test_transform
+4
View File
@@ -0,0 +1,4 @@
namespace test_transform {
void test();
}
+5
View File
@@ -1,6 +1,7 @@
#include "test_all_of.hpp"
#include "test_alphanumeric_map.hpp"
#include "test_alphanumeric_unordered_map.hpp"
#include "test_and_then.hpp"
#include "test_anonymous_fields.hpp"
#include "test_any_of.hpp"
#include "test_apply.hpp"
@@ -69,6 +70,7 @@
#include "test_tagged_union.hpp"
#include "test_tagged_union2.hpp"
#include "test_timestamp.hpp"
#include "test_transform.hpp"
#include "test_unique_ptr.hpp"
#include "test_unique_ptr2.hpp"
#include "test_unnamed_namespace.hpp"
@@ -154,8 +156,11 @@ int main() {
test_as::test();
test_as2::test();
test_as_flatten::test();
test_view::test();
test_apply::test();
test_transform::test();
test_and_then::test();
test_custom_constructor::test();