Add monadic mapping function to coral::optional

This commit is contained in:
kayomn 2023-02-20 15:26:27 +00:00
parent f2694b61cb
commit 1e87aa7fcf
1 changed files with 12 additions and 0 deletions

View File

@ -2,6 +2,7 @@ module;
#include <cstdint>
#include <cstddef>
#include <type_traits>
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<typename functor> std::invoke_result_t<functor, element> 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.
*/