How do I use monadic ops for optional/expected (where available) in C++23?

Learn how to use monadic operations with the Optional and Expected types available in C++23, allowing for cleaner and more efficient handling of values that may not exist or operations that may fail.
Optional, Expected, Monadic Operations, C++23, Functional Programming
#include <optional>
#include <expected>
#include <iostream>

// Example using std::optional
std::optional<int> divide(int numerator, int denominator) {
    if (denominator == 0) {
        return std::nullopt; // Return empty optional if division by zero
    }
    return numerator / denominator;
}

int main() {
    std::optional<int> result = divide(10, 2);
    if (result) {
        std::cout << "Result: " << *result << std::endl; // Output: Result: 5
    } else {
        std::cout << "Division by zero!" << std::endl;
    }

    // Example using std::expected
    std::expected<int, std::string> safe_divide(int numerator, int denominator) {
        if (denominator == 0) {
            return std::unexpected<"Division by zero">; // Return unexpected error string
        }
        return numerator / denominator;
    }

    int main() {
        auto result = safe_divide(10, 0);
        if (result) {
            std::cout << "Result: " << *result << std::endl; // Not executed
        } else {
            std::cout << "Error: " << result.error() << std::endl; // Output: Error: Division by zero
        }
    }

Optional Expected Monadic Operations C++23 Functional Programming