From 1e87aa7fcfdbc1fa6c1e25775f8e36e32f22a260 Mon Sep 17 00:00:00 2001 From: kayomn Date: Mon, 20 Feb 2023 15:26:27 +0000 Subject: [PATCH] Add monadic mapping function to coral::optional --- source/coral.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/source/coral.cpp b/source/coral.cpp index 6661ddf..405a3e7 100644 --- a/source/coral.cpp +++ b/source/coral.cpp @@ -2,6 +2,7 @@ module; #include #include +#include export module coral; @@ -296,6 +297,17 @@ export namespace coral { return this->buffer[sizeof(element)] == 1; } + /** + * Attempts to call `apply` on the contained value, returning a new [optional] of whatever type `apply` returns. + * + * If the optional is empty, an empty optional will always be returned. + */ + template std::invoke_result_t map(functor const & apply) const { + if (this->has_value()) return apply(this->value()); + + return {}; + } + /** * Returns the contained value or `fallback` if the optional is empty. */