#pragma once #include #include #include #include namespace Void::Either { // ── Either ────────────────────────────────────────────────────────────── // Discriminated union: Left for error/secondary value, Right for success. // Convention: Right is the "happy path". template class Either { static_assert(!std::is_same_v, "Either: L and R must be distinct types"); public: template requires std::is_constructible_v static Either left(T&& v) { return Either{std::in_place_index<0>, std::forward(v)}; } template requires std::is_constructible_v static Either right(T&& v) { return Either{std::in_place_index<1>, std::forward(v)}; } [[nodiscard]] bool is_left() const noexcept { return var_.index() == 0; } [[nodiscard]] bool is_right() const noexcept { return var_.index() == 1; } [[nodiscard]] L& left_value() { return std::get<0>(var_); } [[nodiscard]] const L& left_value() const { return std::get<0>(var_); } [[nodiscard]] R& right_value() { return std::get<1>(var_); } [[nodiscard]] const R& right_value() const { return std::get<1>(var_); } template [[nodiscard]] auto map(F&& fn) const & -> Either> { using R2 = std::invoke_result_t; if (is_right()) return Either::right(std::invoke(fn, right_value())); return Either::left(left_value()); } template [[nodiscard]] auto map(F&& fn) && -> Either> { using R2 = std::invoke_result_t; if (is_right()) return Either::right(std::invoke(fn, std::move(right_value()))); return Either::left(std::move(left_value())); } template [[nodiscard]] auto map_left(F&& fn) const & -> Either, R> { using L2 = std::invoke_result_t; if (is_left()) return Either::left(std::invoke(fn, left_value())); return Either::right(right_value()); } template requires std::invocable [[nodiscard]] auto and_then(F&& fn) const & -> std::invoke_result_t { if (is_right()) return std::invoke(fn, right_value()); using Result = std::invoke_result_t; return Result::left(left_value()); } template requires std::invocable && std::invocable && std::is_same_v, std::invoke_result_t> [[nodiscard]] auto fold(FL&& on_left, FR&& on_right) const -> std::invoke_result_t { if (is_left()) return std::invoke(on_left, left_value()); return std::invoke(on_right, right_value()); } [[nodiscard]] Either swap() const { if (is_left()) return Either::right(left_value()); return Either::left(right_value()); } [[nodiscard]] bool operator==(const Either&) const noexcept = default; private: std::variant var_; template Either(std::in_place_index_t tag, T&& v) : var_{tag, std::forward(v)} {} }; template [[nodiscard]] Either make_left(L v) { return Either::left(std::move(v)); } template [[nodiscard]] Either make_right(R v) { return Either::right(std::move(v)); } } // namespace Void::Either