{"id":5174,"date":"2017-02-10T16:15:36","date_gmt":"2017-02-10T16:15:36","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/monads-in-c\/"},"modified":"2023-06-26T12:23:48","modified_gmt":"2023-06-26T12:23:48","slug":"monads-in-c","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/monads-in-c\/","title":{"rendered":"Monads in C++"},"content":{"rendered":"<p>Monads in C++? What a strange name for a post. But it&#8217;s not so strange. With <span style=\"font-family: courier new,courier;\">std::optional<\/span>, C++17 gets a monad. The ranges library from Eric Niebler and the extended futures are also monads. For both, we can hope for in C++20.<\/p>\n<p><!--more--><\/p>\n<p>Bjarne Stroustrup presented in his Secret Lightning Talk at the <a href=\"http:\/\/meetingcpp.com\/index.php\/schedule16.html\">Meeting C++ 2016<\/a> a few concepts of <a href=\"https:\/\/www.modernescpp.com\/index.php\/concepts-lite\">Concepts Lite <\/a>that we will get with high probability in C++20. There were also mathematical concepts such as ring and monad. My assumption becomes more and more reality. <strong>Modern C++ will be hardened for the future.<br \/><\/strong><\/p>\n<h2>std::optional<\/h2>\n<p><span style=\"font-family: courier new,courier;\">Haskell&#8217;s Maybe Monad inspires std::optional<\/span>. <span style=\"font-family: courier new,courier;\">std::optional <\/span>was initially intended to be part of C++14 stands for a calculation that maybe has a value. Therefore, a find algorithm or a hash table query has to deal with the fact that the question can not be answered. Often, you use particular values that stand for the presence of no value, the so-called no result. Often we use a null pointer, empty strings of particular integer values for no results. This technique is expensive and error-prone because you have to deal with the no-results especially. No results are of the same type as regular results. <span style=\"font-family: courier new,courier;\">std::optional<\/span> has in case of a no-result no value.<\/p>\n<p>Here is a short example.<\/p>\n<p>&nbsp;<\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29\r\n30\r\n31\r\n32\r\n33<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ optional.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;experimental\/optional&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;vector&gt;<\/span>\r\n\r\nstd::experimental::optional&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; getFirst(<span style=\"color: #0000ff;\">const<\/span> std::vector&lt;<span style=\"color: #2b91af;\">int<\/span>&gt;&amp; vec){\r\n  <span style=\"color: #0000ff;\">if<\/span> (!vec.empty()) <span style=\"color: #0000ff;\">return<\/span> std::experimental::optional&lt;<span style=\"color: #2b91af;\">int<\/span>&gt;(vec[0]);\r\n  <span style=\"color: #0000ff;\">else<\/span> <span style=\"color: #0000ff;\">return<\/span> std::experimental::optional&lt;<span style=\"color: #2b91af;\">int<\/span>&gt;();\r\n}\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n    \r\n    std::vector&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; myVec{1, 2, 3};\r\n    std::vector&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; myEmptyVec;\r\n    \r\n    <span style=\"color: #0000ff;\">auto<\/span> myInt= getFirst(myVec);\r\n    \r\n    <span style=\"color: #0000ff;\">if<\/span> (myInt){\r\n        std::cout &lt;&lt; <span style=\"color: #a31515;\">\"*myInt: \"<\/span>  &lt;&lt; *myInt &lt;&lt; std::endl;\r\n        std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myInt.value(): \"<\/span> &lt;&lt; myInt.value() &lt;&lt; std::endl;\r\n        std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myInt.value_or(2017):\"<\/span> &lt;&lt; myInt.value_or(2017) &lt;&lt; std::endl;\r\n    }\r\n    \r\n    std::cout &lt;&lt; std::endl;\r\n    \r\n    <span style=\"color: #0000ff;\">auto<\/span> myEmptyInt= getFirst(myEmptyVec);\r\n    \r\n    <span style=\"color: #0000ff;\">if<\/span> (!myEmptyInt){\r\n        std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myEmptyInt.value_or(2017):\"<\/span> &lt;&lt; myEmptyInt.value_or(2017) &lt;&lt; std::endl;\r\n    }\r\n    \r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p><span style=\"font-family: courier new,courier;\">std::optional<\/span> is currently in the namespace <span style=\"font-family: courier new,courier;\">experimental.<\/span> That will change with C++17. I use <span style=\"font-family: courier new,courier;\">std::optional<\/span> in the function <span style=\"font-family: courier new,courier;\">getFirst<\/span> (line 7). <span style=\"font-family: courier new,courier;\">getFirst<\/span> returns the first element if it exists (line 8). You will get a std::optional&lt;int&gt; object (line 9) if not. I use in the main function two vectors. The calls<span style=\"font-family: courier new,courier;\"> get first<\/span> in lines 17 and 27 return the <span style=\"font-family: courier new,courier;\">std::optiona<\/span>l objects. In the case of <span style=\"font-family: courier new,courier;\">myInt<\/span> (line 19), the object has a value; in the case of <span style=\"font-family: courier new,courier;\">myEmptyInt<\/span> (Zeile 29), the object has no value. Now I can display the value of <span style=\"font-family: courier new,courier;\">myInt<\/span> (lines 20 &#8211; 22). The method <span style=\"font-family: courier new,courier;\">value_or<\/span> in lines 22 and 30 returns the value or a default value. This is because <span style=\"font-family: courier new,courier;\">std::optional<\/span> has a value. <span style=\"font-family: courier new,courier;\"><\/span><\/p>\n<p>&nbsp;<\/p>\n<p>The screenshot shows the output of the program using the online compiler at cppreference.com<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5172\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/optional.png\" alt=\"optional\" width=\"600\" height=\"124\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/optional.png 916w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/optional-300x62.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/optional-768x158.png 768w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<\/p>\n<h2>Extended futures<\/h2>\n<p>Modern c++ supports tasks.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4759\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/05\/tasksEng.png\" alt=\"tasksEng\" width=\"500\" height=\"224\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/05\/tasksEng.png 831w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/05\/tasksEng-300x134.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/05\/tasksEng-768x344.png 768w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>Tasks are pairs of&nbsp; <span style=\"font-family: courier new,courier;\">std::promise<\/span> and <span style=\"font-family: courier new,courier;\">std::future <\/span>objects connected by a channel. Both communication endpoints may exist in different threads. The <span style=\"font-family: courier new,courier;\">std::promise<\/span> (sender) pushes its value into the channel for which the std::future (receiver) is waiting. The sender can push a value, a notification, or an exception into the channel. I&#8217;ve written a few posts about tasks. Here are the details:&nbsp; <a href=\"https:\/\/www.modernescpp.com\/index.php\/tag\/tasks\">Tasks<\/a>.<\/p>\n<p>The easiest way to create a promise is to use the function&nbsp;<a href=\"https:\/\/www.modernescpp.com\/index.php\/asynchronous-function-calls\">std::async<\/a>. <span style=\"font-family: courier new,courier;\">std::async<\/span> behaves like an asynchronous function call.<\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #2b91af;\">int<\/span> a= 2000\r\n<span style=\"color: #2b91af;\">int<\/span> b= 11;\r\nstd::future&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; sum= std::async([=]{ <span style=\"color: #0000ff;\">return<\/span> a+b; });\r\nstd::cout &lt;&lt; sum.get() &lt;&lt; std::endl;\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The call std::async performs more actions. First, it creates the communication endpoints&#8217; promise and future; second, it connects them via a channel. The lambda function <span style=\"font-family: courier new,courier;\">[=]{ return a+b;}<\/span> is the work package of the promise. It captures arguments a and b from their defining context. The C++ run time decides if the promise will run in the same or a different thread. Criteria for its decision may be the size of the work package, the load of the system, or the number of cores.<\/p>\n<p>The future calls <span style=\"font-family: courier new,courier;\">sum.get()<\/span> to get the value from the promise. You can only once call <span style=\"font-family: courier new,courier;\">sum.get().<\/span> If the promise is not made, the get call will block.<\/p>\n<p>Tasks provide similar and safer handling of threads because they have no shared state that has to be protected. Therefore, race conditions are not possible, and deadlocks are much rarer. But, the C++11 implementation of futures has a big disadvantage. The composition of<span style=\"font-family: courier new,courier;\"> std::future<\/span> objects is not possible. This will not hold true for the extended futures of C++20.<\/p>\n<p>The table shows the functions for extended futures.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5173\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/futureImprovementEng.png\" alt=\"futureImprovementEng\" width=\"700\" height=\"242\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/futureImprovementEng.png 953w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/futureImprovementEng-300x104.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/futureImprovementEng-768x266.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>Here are a few code snippets from proposal&nbsp;<a href=\"http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2013\/n3721.pdf\">n3721.<\/a><\/p>\n<p>&nbsp;<\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\">future&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; f1= async([]() {<span style=\"color: #0000ff;\">return<\/span> 123;});\r\n\r\nfuture&lt;string&gt; f2 = f1.then([](future&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; f) {\r\n     <span style=\"color: #0000ff;\">return<\/span> f.get().to_string(); \r\n});\r\n\r\nfuture&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; futures[] = {async([]() { <span style=\"color: #0000ff;\">return<\/span> intResult(125); }), \r\n                         async([]() { <span style=\"color: #0000ff;\">return<\/span> intResult(456); })};\r\n\r\nfuture&lt;vector&lt;future&lt;<span style=\"color: #2b91af;\">int<\/span>&gt;&gt;&gt; any_f = when_any(begin(futures), end(futures));\r\n\r\n\r\nfuture&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; futures[] = {async([]() { <span style=\"color: #0000ff;\">return<\/span> intResult(125); }), \r\n                         async([]() { <span style=\"color: #0000ff;\">return<\/span> intResult(456); })};\r\n\r\nfuture&lt;vector&lt;future&lt;<span style=\"color: #2b91af;\">int<\/span>&gt;&gt;&gt; all_f = when_all(begin(futures), end(futures));\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The future <span style=\"font-family: courier new,courier;\">f2<\/span> in line 3 is ready if the future <span style=\"font-family: courier new,courier;\">f2<\/span> is ready. You can enlarge the chain of futures:&nbsp; <span style=\"font-family: courier new,courier;\">f1.then(&#8230;).then(&#8230;).then(&#8230;).<\/span> The future <span style=\"font-family: courier new,courier;\">any_f<\/span> in line 10 becomes ready if any of its futures become ready. On the contrary, the future <span style=\"font-family: courier new,courier;\">all_f<\/span> in line 16 becomes ready if all its futures become ready.<\/p>\n<p>One question is still not answered. What have futures in common with functional programming? A lot! The extended futures are a monad. I explained in the post <a href=\"https:\/\/www.modernescpp.com\/index.php\/pure-functions\">Pure Functions<\/a> the idea of monads. The key idea of a monad is that a monad encapsulates a simple type in an enriched type and supports the compositions of functions on these enriched types. Therefore, the monad needs a function to lift the simple type into an enriched one. Additionally, a monad needs a function that empowers them to compose functions on enriched types. This job is for the functions <span style=\"font-family: courier new,courier;\">make_ready_future, then,<\/span> and <span style=\"font-family: courier new,courier;\">future&lt;future&lt;T&gt;&gt;. make_ready_future <\/span>maps a simple type into an enriched type, a so-called monadic value. This function is called identity and has the name <span style=\"font-family: courier new,courier;\">return<\/span> in Haskell. The two functions then and <span style=\"font-family: courier new,courier;\">future&lt;future&lt;T&gt;&gt;<\/span> are equivalent to the <span style=\"font-family: courier new,courier;\">bind <\/span>operator in Haskell. The <span style=\"font-family: courier new,courier;\">bind<\/span> operator&#8217;s job is to transform one monadic value into another monadic value. <span style=\"font-family: courier new,courier;\">bind<\/span> is the function composition in a monad.&nbsp;<\/p>\n<p>Thanks to the method <span style=\"font-family: courier new,courier;\">when_any<\/span> <span style=\"font-family: courier new,courier;\">std::future<\/span> even becomes a <a href=\"https:\/\/hackage.haskell.org\/package\/monadplus-1.4.2\/docs\/Control-Monad-Plus.html\">Monad Plus<\/a>. A Monad Plus requires from its instances that they are monads and have an operator <span style=\"font-family: courier new,courier;\">msum.<\/span> Therefore, <span style=\"font-family: courier new,courier;\">std::future<\/span> supports a kind of addition operation in C++20.<\/p>\n<p>If you want to know the details, you should read the excellent <a href=\"http:\/\/bartoszmilewski.com\/2014\/02\/26\/c17-i-see-a-monad-in-your-future\/\">blog<\/a> of Bartosz Milelweski and watch his video:&nbsp; &#8220;C++17: I See a Monad in Your Future!&#8221;.<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>In my post <a href=\"https:\/\/www.modernescpp.com\/index.php\/recursion-list-manipulation-and-lazy-evaluation\">Recursion, List Manipulation, and Lazy Evaluation<\/a>, I wrote: The story about lazy evaluation in C++ is quite short. But I made my conclusion without templates. Thanks to the CRTP idiom and expression templates C++ is lazy. Therefore, I will write about the infamous CRTP idiom in the next post.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Monads in C++? What a strange name for a post. But it&#8217;s not so strange. With std::optional, C++17 gets a monad. The ranges library from Eric Niebler and the extended futures are also monads. For both, we can hope for in C++20.<\/p>\n","protected":false},"author":21,"featured_media":5172,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[365],"tags":[508,510,482],"class_list":["post-5174","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-functional","tag-haskell","tag-monads","tag-outdated"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5174","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5174"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5174\/revisions"}],"predecessor-version":[{"id":6889,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5174\/revisions\/6889"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5172"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5174"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5174"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5174"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}