{"id":4656,"date":"2023-05-29T17:04:38","date_gmt":"2023-05-29T15:04:38","guid":{"rendered":"https:\/\/mariusbancila.ro\/blog\/?p=4656"},"modified":"2023-05-29T17:04:40","modified_gmt":"2023-05-29T15:04:40","slug":"notes-on-std-optional-monadic-operations","status":"publish","type":"post","link":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/","title":{"rendered":"Notes on std::optional&#8217;s monadic operations"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The C++23 standard includes several new functions to the <code>std::optional<\/code> class: <code>and_then<\/code>, <code>transform<\/code>, <code>or_else<\/code>. These are monadic operations and are intended to simplify the chaining of several operations that may or may not produce a value. In this post, I want to briefly present these functions and to make some observations on them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A starting example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s take the following example as a starting point for the discussion:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">enum pizza_size {small, regular};\nstruct pizza\n{\n   pizza_size  size;\n   bool        has_pepperoni;\n   bool        has_basil;\n   bool        has_artichokes;\n};\n\nstd::optional&lt;pizza> make_pizza(pizza_size const size)\n{\n   return pizza{ .size = size};\n}\n\nstd::optional&lt;pizza> add_pepperoni(std::optional&lt;pizza> p)\n{\n   if (!p->has_pepperoni)\n      p->has_pepperoni = true;\n\n   return p;\n}\n\nstd::optional&lt;pizza> add_basil(std::optional&lt;pizza> p)\n{\n   if (!p->has_basil)\n      p->has_basil = true;\n\n   return p;\n}\n\nstd::optional&lt;pizza> add_artichokes(std::optional&lt;pizza> p)\n{\n   if (!p->has_artichokes)\n      p->has_artichokes = true;\n\n   return p;\n}\n\ndouble get_price(std::optional&lt;pizza> p)\n{\n   if (p)\n   {\n      double price = p->size == pizza_size::small ? 10 : 15;\n\n      if (p->has_pepperoni)\n         price += 2;\n      if (p->has_basil)\n         price += 1;\n      if (p->has_artichokes)\n         price += 3;\n\n      return price;\n   }\n\n   return 0;\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">What we have here is:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>a function that creates a <code>pizza<\/code> object (<code>make_function<\/code>)<\/li><li>several functions that take a <code>pizza<\/code> object and modify it (<code>add_pepperoni<\/code>, <code>add_basil<\/code>, <code>add_artichokes<\/code>)<\/li><li>a function that takes a pizza and returns a double representing the price of the pizza (<code>get_price<\/code>)<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Prior to C++23, using these functions would could have looked as follows:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int main()\n{\n   auto p = make_pizza(pizza_size::regular);\n   if (!p)\n   {\n      std::cout &lt;&lt; \"Failed to create pizza\\n\";\n      return -1;\n   }\n   p = add_pepperoni(p);\n   p = add_basil(p);\n   p = add_artichokes(p);\n\n   auto cost = get_price(p);\n\n   std::cout &lt;&lt; cost &lt;&lt; '\\n';\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In C++23, this can be simplified using monadic operations to chain the calls together, as follows:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int main()\n{\n   auto p = make_pizza(pizza_size::regular)\n           .or_else([]() -> std::optional&lt;pizza> {\n               std::cout &lt;&lt; \"Failed to create pizza\\n\"; \n               return std::nullopt; })\n           .and_then(add_pepperoni)\n           .and_then(add_basil)\n           .and_then(add_artichokes)\n           .transform(get_price);\n\n   std::cout &lt;&lt; p.value_or(0) &lt;&lt; '\\n';\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at these operations in the order seen above.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">or_else<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <a href=\"https:\/\/en.cppreference.com\/w\/cpp\/utility\/optional\/or_else\" target=\"_blank\" rel=\"noopener\" title=\"\">or_else<\/a> function does the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>if the <code>optional<\/code> object contains a value, it simply returns the <code>optional<\/code> object without doing anything<\/li><li>otherwise, if the <code>optional<\/code> object is empty, it invokes the supplied callable and returns its return value, that must be itself an <code>optional<\/code> object<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you paid attention to the example above, you have noticed that the lambda passed to <code>or_else<\/code> returns an <code>optional<\/code> value itself. This differs a bit from what you can find in various articles on the web, including the original proposal by Sy Brand:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2019\/p0798r3.html#or_else\" target=\"_blank\" rel=\"noopener\" title=\"\">Monadic operations for std::optional<\/a><\/li><li><a href=\"https:\/\/github.com\/TartanLlama\/optional\" target=\"_blank\" rel=\"noopener\" title=\"\">optional<\/a><\/li><li><a href=\"https:\/\/pspdfkit.com\/blog\/2019\/the-functional-side-of-optional\/\" target=\"_blank\" rel=\"noopener\" title=\"\">The Functional Side of std::optional with C++20<\/a><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here, examples look as follows:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">get_opt().or_else([]{std::cout &lt;&lt; \"get_opt failed\";});\nget_opt().or_else([]{throw std::runtime_error(\"get_opt_failed\")});<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These examples had this form because the initial implementation was planned as this (from <a href=\"https:\/\/github.com\/TartanLlama\/optional\/blob\/master\/include\/tl\/optional.hpp\" target=\"_blank\" rel=\"noopener\" title=\"\">here<\/a>):<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">template &lt;class F \/*...*\/>\noptional&lt;T> or_else(F &amp;&amp;f) &amp; {\n  if (has_value())\n    return *this;\n\n  std::forward&lt;F>(f)();\n  return nullopt;\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">I believe that at some point during the final stages of including this in the standard it was thought that instead of <code>or_else<\/code> returning an empty <code>optional<\/code>, it could be better to allow the callable to return an alternative value. In many cases this could be <code>std::nullopt<\/code>, but in some case it could be an <code>optional<\/code> holding some other value (such as a default value).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore, the implementation now has the following form (expositional only):<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">template &lt;class F \/*...*\/>\noptional&lt;T> or_else(F &amp;&amp;f) &amp; {\n  if (has_value())\n    return *this;\n  else\n    return std::forward&lt;F>(f)();\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We can expand the previous example with a call to <code>or_else<\/code> after each invocation of a transforming function, as shown next:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">auto p = make_pizza(pizza_size::regular)\n   .or_else([]() -> std::optional&lt;pizza> {\n      std::cout &lt;&lt; \"Failed to create pizza\\n\"; \n      return std::nullopt; })\n   .and_then(add_pepperoni)\n   .or_else([]() -> std::optional&lt;pizza> {\n      std::cout &lt;&lt; \"Failed to add pepperoni\\n\"; \n      return std::nullopt; })\n   .and_then(add_basil)\n   .or_else([]() -> std::optional&lt;pizza> {\n      std::cout &lt;&lt; \"Failed to add basil\\n\"; \n      return std::nullopt; })\n   .and_then(add_artichokes)\n   .or_else([]() -> std::optional&lt;pizza> {\n      std::cout &lt;&lt; \"Failed to add pepperoni\\n\"; \n      return std::nullopt; })\n   .transform(get_price);<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">and_then<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This is the opposite of <code>or_else<\/code>. This function does the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>if the <code>optional<\/code> object contains a value, then it invokes the callable argument and returns the value returned by this invocation. This must be a specialization of <code>std::optional<\/code>, or else the program is ill-formed.<\/li><li>if the <code>optional<\/code> object is empty, it does nothing and returns an empty optional.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In our example, the functions <code>add_pepperoni<\/code>, <code>add_basil<\/code>, <code>add_artichokes<\/code> all take an <code>optional&lt;pizza><\/code> do some transformation on it and return back an <code>optional&lt;pizza><\/code>. This makes it possible to chain them in any given order.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">transform<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This function does the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>if the <code>optional<\/code> object contains a value, then it invokes the callable argument and return an <code>optional<\/code> object containing the value returned by this invocation.<\/li><li>if the <code>optional<\/code> object is empty, it does nothing and returns an empty <code>optional<\/code><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">At a first glance, this is very similar to <code>and_then<\/code>. However, there is a key difference: the callable passed to <code>and_then<\/code> must return a specialization of <code>std::optional<\/code>. There is no such requirement for the callable passed to transform. However, transform wraps the result of invoking the callable into an <code>std::optional<\/code>, so if the callable passed to transform returns a <code>std::optional&lt;T><\/code>, the result will be a <code>std::optional&lt;std::optional&lt;T>><\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the following example, <code>price<\/code> is a <code>std::optional&lt;double><\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">std::optional&lt;double> price = make_pizza(pizza_size::regular)\n                             .transform(get_price);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">But if we change <code>get_price()<\/code> to return a <code>std::optional&lt;double><\/code> instead, then <code>price<\/code> becomes a <code>std::optional&lt;std::optional&lt;double>><\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">std::optional&lt;double> get_price(std::optional&lt;pizza> p)\n{\n   if (p)\n   {\n      double price = p->size == pizza_size::small ? 10 : 15;\n\n      if (p->has_pepperoni)\n         price += 2;\n      if (p->has_basil)\n         price += 1;\n      if (p->has_artichokes)\n         price += 3;\n\n      return price;\n   }\n\n   return std::nullopt;\n}\n\nstd::optional&lt;std::optional&lt;double>> price = make_pizza(pizza_size::regular)\n                                            .transform(get_price);<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">See also<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/nicobombace.com\/c++\/monadic\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Monadic operations in C++23<\/a><\/li><li><a href=\"https:\/\/devblogs.microsoft.com\/cppblog\/cpp23s-optional-and-expected\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Functional exception-less error handling with C++23\u2019s optional and expected<\/a><\/li><li><a href=\"https:\/\/mariusbancila.ro\/blog\/2022\/08\/17\/using-the-cpp23-expected-type\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Using the C++23 std::expected type<\/a><\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>The C++23 standard includes several new functions to the std::optional class: and_then, transform, or_else. These are monadic operations and are intended to simplify the chaining of several operations that may or may not produce a value. In this post, I want to briefly present these functions and to make some observations on them. A starting &#8230; <a title=\"Notes on std::optional&#8217;s monadic operations\" class=\"read-more\" href=\"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/\" aria-label=\"Read more about Notes on std::optional&#8217;s monadic operations\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","advgb_blocks_editor_width":"","advgb_blocks_columns_visual_guide":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[7],"tags":[451,632,79],"class_list":["post-4656","post","type-post","status-publish","format-standard","hentry","category-c","tag-c","tag-c23","tag-optional"],"aioseo_notices":[],"aioseo_head":"\n\t\t<!-- All in One SEO 5.0.1.1 - aioseo.com -->\n\t<meta name=\"description\" content=\"Learn about the C++23 optional&#039;s monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.\" \/>\n\t<meta name=\"robots\" content=\"max-image-preview:large\" \/>\n\t<meta name=\"author\" content=\"Marius Bancila\"\/>\n\t<meta name=\"keywords\" content=\"c++,c++23,optional\" \/>\n\t<link rel=\"canonical\" href=\"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/\" \/>\n\t<meta name=\"generator\" content=\"All in One SEO (AIOSEO) 5.0.1.1\" \/>\n\t\t<meta property=\"og:locale\" content=\"en_US\" \/>\n\t\t<meta property=\"og:site_name\" content=\"Marius Bancila&#039;s Blog | About code. Mostly on C++\" \/>\n\t\t<meta property=\"og:type\" content=\"article\" \/>\n\t\t<meta property=\"og:title\" content=\"Notes on std::optional\u2019s monadic operations\" \/>\n\t\t<meta property=\"og:description\" content=\"Learn about the C++23 optional&#039;s monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.\" \/>\n\t\t<meta property=\"og:url\" content=\"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/\" \/>\n\t\t<meta property=\"article:published_time\" content=\"2023-05-29T15:04:38+00:00\" \/>\n\t\t<meta property=\"article:modified_time\" content=\"2023-05-29T15:04:40+00:00\" \/>\n\t\t<meta name=\"twitter:card\" content=\"summary\" \/>\n\t\t<meta name=\"twitter:title\" content=\"Notes on std::optional\u2019s monadic operations\" \/>\n\t\t<meta name=\"twitter:description\" content=\"Learn about the C++23 optional&#039;s monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.\" \/>\n\t\t<script type=\"application\/ld+json\" class=\"aioseo-schema\">\n\t\t\t{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#article\",\"name\":\"Notes on std::optional\\u2019s monadic operations\",\"headline\":\"Notes on std::optional&#8217;s monadic operations\",\"author\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/author\\\/admin\\\/#author\"},\"publisher\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/#organization\"},\"datePublished\":\"2023-05-29T17:04:38+02:00\",\"dateModified\":\"2023-05-29T17:04:40+02:00\",\"inLanguage\":\"en-US\",\"commentCount\":1,\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#webpage\"},\"isPartOf\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#webpage\"},\"articleSection\":\"C++, C++, C++23, optional\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#breadcrumblist\",\"itemListElement\":[{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog#listItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/#listItem\",\"name\":\"IT\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/#listItem\",\"position\":2,\"name\":\"IT\",\"item\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/#listItem\",\"name\":\"Software\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog#listItem\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/#listItem\",\"position\":3,\"name\":\"Software\",\"item\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/c\\\/#listItem\",\"name\":\"C++\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/#listItem\",\"name\":\"IT\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/c\\\/#listItem\",\"position\":4,\"name\":\"C++\",\"item\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/c\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#listItem\",\"name\":\"Notes on std::optional&#8217;s monadic operations\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/#listItem\",\"name\":\"Software\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#listItem\",\"position\":5,\"name\":\"Notes on std::optional&#8217;s monadic operations\",\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/category\\\/it\\\/software\\\/c\\\/#listItem\",\"name\":\"C++\"}}]},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/#organization\",\"name\":\"Marius Bancila's Blog\",\"description\":\"About code. Mostly on C++\",\"url\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/author\\\/admin\\\/#author\",\"url\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/author\\\/admin\\\/\",\"name\":\"Marius Bancila\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#authorImage\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a84dd2831d955c38355ddea55df4df260809b88f36408bc14fd4eab8f7f131c9?s=96&d=mm&r=g\",\"width\":96,\"height\":96,\"caption\":\"Marius Bancila\"}},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#webpage\",\"url\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/\",\"name\":\"Notes on std::optional\\u2019s monadic operations\",\"description\":\"Learn about the C++23 optional's monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.\",\"inLanguage\":\"en-US\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/#website\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/2023\\\/05\\\/29\\\/notes-on-std-optional-monadic-operations\\\/#breadcrumblist\"},\"author\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/author\\\/admin\\\/#author\"},\"creator\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/author\\\/admin\\\/#author\"},\"datePublished\":\"2023-05-29T17:04:38+02:00\",\"dateModified\":\"2023-05-29T17:04:40+02:00\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/\",\"name\":\"Marius Bancila's Blog\",\"description\":\"About code. Mostly on C++\",\"inLanguage\":\"en-US\",\"publisher\":{\"@id\":\"https:\\\/\\\/mariusbancila.ro\\\/blog\\\/#organization\"}}]}\n\t\t<\/script>\n\t\t<!-- All in One SEO -->\n\n","aioseo_head_json":{"title":"Notes on std::optional\u2019s monadic operations","description":"Learn about the C++23 optional's monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.","canonical_url":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/","robots":"max-image-preview:large","keywords":"c++,c++23,optional","webmasterTools":{"miscellaneous":""},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#article","name":"Notes on std::optional\u2019s monadic operations","headline":"Notes on std::optional&#8217;s monadic operations","author":{"@id":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/#author"},"publisher":{"@id":"https:\/\/mariusbancila.ro\/blog\/#organization"},"datePublished":"2023-05-29T17:04:38+02:00","dateModified":"2023-05-29T17:04:40+02:00","inLanguage":"en-US","commentCount":1,"mainEntityOfPage":{"@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#webpage"},"isPartOf":{"@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#webpage"},"articleSection":"C++, C++, C++23, optional"},{"@type":"BreadcrumbList","@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#breadcrumblist","itemListElement":[{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog#listItem","position":1,"name":"Home","item":"https:\/\/mariusbancila.ro\/blog","nextItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/#listItem","name":"IT"}},{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/#listItem","position":2,"name":"IT","item":"https:\/\/mariusbancila.ro\/blog\/category\/it\/","nextItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/#listItem","name":"Software"},"previousItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog#listItem","name":"Home"}},{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/#listItem","position":3,"name":"Software","item":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/","nextItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/#listItem","name":"C++"},"previousItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/#listItem","name":"IT"}},{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/#listItem","position":4,"name":"C++","item":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/","nextItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#listItem","name":"Notes on std::optional&#8217;s monadic operations"},"previousItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/#listItem","name":"Software"}},{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#listItem","position":5,"name":"Notes on std::optional&#8217;s monadic operations","previousItem":{"@type":"ListItem","@id":"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/#listItem","name":"C++"}}]},{"@type":"Organization","@id":"https:\/\/mariusbancila.ro\/blog\/#organization","name":"Marius Bancila's Blog","description":"About code. Mostly on C++","url":"https:\/\/mariusbancila.ro\/blog\/"},{"@type":"Person","@id":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/#author","url":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/","name":"Marius Bancila","image":{"@type":"ImageObject","@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#authorImage","url":"https:\/\/secure.gravatar.com\/avatar\/a84dd2831d955c38355ddea55df4df260809b88f36408bc14fd4eab8f7f131c9?s=96&d=mm&r=g","width":96,"height":96,"caption":"Marius Bancila"}},{"@type":"WebPage","@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#webpage","url":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/","name":"Notes on std::optional\u2019s monadic operations","description":"Learn about the C++23 optional's monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.","inLanguage":"en-US","isPartOf":{"@id":"https:\/\/mariusbancila.ro\/blog\/#website"},"breadcrumb":{"@id":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/#breadcrumblist"},"author":{"@id":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/#author"},"creator":{"@id":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/#author"},"datePublished":"2023-05-29T17:04:38+02:00","dateModified":"2023-05-29T17:04:40+02:00"},{"@type":"WebSite","@id":"https:\/\/mariusbancila.ro\/blog\/#website","url":"https:\/\/mariusbancila.ro\/blog\/","name":"Marius Bancila's Blog","description":"About code. Mostly on C++","inLanguage":"en-US","publisher":{"@id":"https:\/\/mariusbancila.ro\/blog\/#organization"}}]},"og:locale":"en_US","og:site_name":"Marius Bancila's Blog | About code. Mostly on C++","og:type":"article","og:title":"Notes on std::optional\u2019s monadic operations","og:description":"Learn about the C++23 optional's monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.","og:url":"https:\/\/mariusbancila.ro\/blog\/2023\/05\/29\/notes-on-std-optional-monadic-operations\/","article:published_time":"2023-05-29T15:04:38+00:00","article:modified_time":"2023-05-29T15:04:40+00:00","twitter:card":"summary","twitter:title":"Notes on std::optional\u2019s monadic operations","twitter:description":"Learn about the C++23 optional's monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value."},"aioseo_meta_data":{"post_id":"4656","title":null,"description":"Learn about the C++23 optional's monadic operations, and_then, transform, and or_else that allow to chain operations that may or may not produce a value.","keywords":[],"keyphrases":{"focus":{"keyphrase":"","score":0,"analysis":{"keyphraseInTitle":{"score":0,"maxScore":9,"error":1}}},"additional":[]},"primary_term":null,"canonical_url":null,"og_title":null,"og_description":null,"og_object_type":"default","og_image_type":"default","og_image_url":null,"og_image_width":null,"og_image_height":null,"og_image_custom_url":null,"og_image_custom_fields":null,"og_video":"","og_custom_url":null,"og_article_section":null,"og_article_tags":[],"twitter_use_og":false,"twitter_card":"default","twitter_image_type":"default","twitter_image_url":null,"twitter_image_custom_url":null,"twitter_image_custom_fields":null,"twitter_title":null,"twitter_description":null,"schema":{"blockGraphs":[],"customGraphs":[],"default":{"data":{"Article":[],"Course":[],"Dataset":[],"FAQPage":[],"Movie":[],"Person":[],"Product":[],"ProductReview":[],"Car":[],"Recipe":[],"Service":[],"SoftwareApplication":[],"WebPage":[]},"graphName":"","isEnabled":true},"graphs":[]},"schema_type":"default","schema_type_options":null,"pillar_content":false,"robots_default":true,"robots_noindex":false,"robots_noarchive":false,"robots_nosnippet":false,"robots_nofollow":false,"robots_noimageindex":false,"robots_noodp":false,"robots_notranslate":false,"robots_max_snippet":"-1","robots_max_videopreview":"-1","robots_max_imagepreview":"large","priority":null,"frequency":"default","location":null,"local_seo":null,"breadcrumb_settings":null,"limit_modified_date":false,"ai":null,"created":"2023-05-29 11:36:28","updated":"2025-12-12 07:58:44","seo_analyzer_scan_date":null,"focus_keyword":null,"additional_keywords":null,"truseo_locale":null},"author_meta":{"display_name":"Marius Bancila","author_link":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/"},"featured_img":null,"jetpack_publicize_connections":[],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Marius Bancila","author_link":"https:\/\/mariusbancila.ro\/blog\/author\/admin\/"},"uagb_comment_info":1,"uagb_excerpt":"The C++23 standard includes several new functions to the std::optional class: and_then, transform, or_else. These are monadic operations and are intended to simplify the chaining of several operations that may or may not produce a value. In this post, I want to briefly present these functions and to make some observations on them. A starting&hellip;","coauthors":[],"tax_additional":{"categories":{"linked":["<a href=\"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/\" class=\"advgb-post-tax-term\">C++<\/a>"],"unlinked":["<span class=\"advgb-post-tax-term\">C++<\/span>"]},"tags":{"linked":["<a href=\"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/\" class=\"advgb-post-tax-term\">C++<\/a>","<a href=\"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/\" class=\"advgb-post-tax-term\">C++23<\/a>","<a href=\"https:\/\/mariusbancila.ro\/blog\/category\/it\/software\/c\/\" class=\"advgb-post-tax-term\">optional<\/a>"],"unlinked":["<span class=\"advgb-post-tax-term\">C++<\/span>","<span class=\"advgb-post-tax-term\">C++23<\/span>","<span class=\"advgb-post-tax-term\">optional<\/span>"]}},"comment_count":"1","relative_dates":{"created":"Posted 3 years ago","modified":"Updated 3 years ago"},"absolute_dates":{"created":"Posted on May 29, 2023","modified":"Updated on May 29, 2023"},"absolute_dates_time":{"created":"Posted on May 29, 2023 5:04 pm","modified":"Updated on May 29, 2023 5:04 pm"},"featured_img_caption":"","series_order":"","jetpack_shortlink":"https:\/\/wp.me\/pYNdv-1d6","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/posts\/4656","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/comments?post=4656"}],"version-history":[{"count":8,"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/posts\/4656\/revisions"}],"predecessor-version":[{"id":4664,"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/posts\/4656\/revisions\/4664"}],"wp:attachment":[{"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/media?parent=4656"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/categories?post=4656"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mariusbancila.ro\/blog\/wp-json\/wp\/v2\/tags?post=4656"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}