{"id":5144,"date":"2017-01-24T20:10:38","date_gmt":"2017-01-24T20:10:38","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/first-class-functions\/"},"modified":"2017-01-24T20:10:38","modified_gmt":"2017-01-24T20:10:38","slug":"first-class-functions","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/first-class-functions\/","title":{"rendered":"First-Class Functions"},"content":{"rendered":"<p>One of the characteristics of functional programming is first-class functions. First-class functions behave like data and are heavily used in the Standard Template Library.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<h2>First-class functions<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5141\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/CharakteristikenFunktionaleProgrammierungFirstClassFunctionsEng.png\" alt=\"CharakteristikenFunktionaleProgrammierungFirstClassFunctionsEng\" style=\"margin: 15px;\" width=\"481\" height=\"442\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/CharakteristikenFunktionaleProgrammierungFirstClassFunctionsEng.png 481w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/CharakteristikenFunktionaleProgrammierungFirstClassFunctionsEng-300x276.png 300w\" sizes=\"auto, (max-width: 481px) 100vw, 481px\" \/><\/p>\n<p>Do first-class functions behave like data? What does that mean?<\/p>\n<p>First-class functions can be<\/p>\n<ul>\n<li><strong>an argument of a function.<br \/><\/strong><\/li>\n<\/ul>\n<p style=\"padding-left: 30px;\">&nbsp; &nbsp; std::accumulate(vec.begin(), vec.end(), 1, []{ <span style=\"color: #2b91af;\">int<\/span> a, <span style=\"color: #2b91af;\">int<\/span> b}{ <span style=\"color: #0000ff;\">return<\/span> a * b; })<\/p>\n<ul>\n<li><strong>returned from a function.<br \/><\/strong><\/li>\n<\/ul>\n<pre style=\"margin: 0px; line-height: 125%;\"><code><samp>       std::function&lt;<span style=\"color: #2b91af;\">int<\/span>(<span style=\"color: #2b91af;\">int<\/span>, <span style=\"color: #2b91af;\">int<\/span>)&gt; makeAdd(){\r\n         <span style=\"color: #0000ff;\">return<\/span> [](<span style=\"color: #2b91af;\">int<\/span> a, <span style=\"color: #2b91af;\">int<\/span> b){ <span style=\"color: #0000ff;\">return<\/span> a + b; };\r\n       }\r\n       std::function&lt;<span style=\"color: #2b91af;\">int<\/span>(<span style=\"color: #2b91af;\">int<\/span>, <span style=\"color: #2b91af;\">int<\/span>)&gt; myAdd= makeAdd();\r\n       myAdd(2000, 11);  <span style=\"color: #008000;\">\/\/ 2011<\/span><\/samp><\/code><\/pre>\n<ul>\n<li><strong>stored in a variable.<br \/><\/strong><\/li>\n<\/ul>\n<p>One short remark on the second point. The function <span style=\"font-family: courier new,courier;\">makeAdd<\/span> returns the lambda function <span style=\"color: #008000;\"><span style=\"color: #000000;\"><span style=\"font-family: courier new,courier;\">[](int a, int b){ return a + b; }<\/span>. This function needs two <span style=\"font-family: courier new,courier;\">int<\/span> arguments and returns an <span style=\"font-family: courier new,courier;\">int<\/span> value: <span style=\"font-family: courier new,courier;\">std::function&lt;int(int,int)&gt;<\/span>. You can bind the return value of <span style=\"font-family: courier new,courier;\">makeAdd<\/span> to the generic function wrapper <span style=\"font-family: courier new,courier;\">myAdd<\/span> and execute it.<span style=\"font-family: courier new,courier;\"><\/span><span style=\"font-family: courier new,courier;\"><\/span><\/span> <\/span><\/p>\n<p>My post Functional in C++11 and C++14: Dispatch Table and Generic Lambdas show which power lies in first-class functions<a href=\"https:\/\/www.modernescpp.com\/index.php\/functional-in-c-dispatch-table\">. <\/a> Have a look at the dispatch table in C++.<\/p>\n<p>Function pointers are the first-class functions of the poor man. Even C has function pointers. C++ goes a few steps further. In particular, you can connect the evolution of the function concept with the evolution of C++.<\/p>\n<\/p>\n<h2>The evolution of the function concept<\/h2>\n<p>Simplified, evolution consists of four steps.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5142\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/FunctionEvolutionEng.png\" alt=\"FunctionEvolutionEng\" width=\"399\" height=\"492\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/FunctionEvolutionEng.png 399w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/FunctionEvolutionEng-243x300.png 243w\" sizes=\"auto, (max-width: 399px) 100vw, 399px\" \/><\/p>\n<p>C knows functions. C++ added function objects. These are objects which behave like functions because their call operator is overloaded. C++11 added lambda functions; C++14 made them generic. Each step made functions in C++ even more powerful.<\/p>\n<ul>\n<li><strong>Functions =&gt; Function objects: <\/strong>Function objects can have a state contrary to functions. Therefore, they have a memory, and you can configure them.<\/li>\n<li><strong>Function objects =&gt; Lambda functions: <\/strong>Lambda functions are usually implemented just in place of their usage. That improves the readability of the code, reduces your typing to its bare minimum, and gives the optimizer maximum insight into your code. Therefore, the optimizer has more opportunities to do its job.<\/li>\n<li><strong>Lambda functions =&gt; Generic lambda functions: <\/strong>Generic lambda functions are similar to function templates but are much easier to implement. They can be widely used because, as <a href=\"https:\/\/en.wikipedia.org\/wiki\/Closure_(computer_programming)\">closures<\/a>, they capture their environment, and you can parametrize their type.&nbsp;<\/li>\n<\/ul>\n<p>Admittedly, that was a lot of theory. Therefore, the example is following right now. Here are the four steps of the function concepts in C++.<\/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\r\n34\r\n35\r\n36\r\n37\r\n38\r\n39\r\n40\r\n41\r\n42\r\n43\r\n44\r\n45\r\n46\r\n47\r\n48\r\n49\r\n50\r\n51\r\n52\r\n53\r\n54\r\n55\r\n56\r\n57\r\n58\r\n59\r\n60\r\n61\r\n62\r\n63\r\n64\r\n65\r\n66\r\n67\r\n68\r\n69\r\n70\r\n71\r\n72\r\n73\r\n74\r\n75<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ evolutionOfFunctions.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;numeric&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;string&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;vector&gt;<\/span>\r\n\r\nstd::string addMe(std::string fir, std::string sec){\r\n  <span style=\"color: #0000ff;\">return<\/span> fir + <span style=\"color: #a31515;\">\" \"<\/span> + sec;\r\n};\r\n\r\n<span style=\"color: #0000ff;\">struct<\/span> AddMe{\r\n  \r\n  AddMe()= <span style=\"color: #0000ff;\">default<\/span>;\r\n  AddMe(std::string gl): glue(gl) {}\r\n  \r\n  std::string <span style=\"color: #0000ff;\">operator<\/span>()(std::string fir, std::string sec) <span style=\"color: #0000ff;\">const<\/span> {\r\n    <span style=\"color: #0000ff;\">return<\/span> fir + glue + sec;\r\n  }\r\n  \r\n  std::string glue= <span style=\"color: #a31515;\">\" \"<\/span>;\r\n  \r\n};\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n  \r\n  std::vector&lt;std::string&gt; myStrings={<span style=\"color: #a31515;\">\"The\"<\/span>, <span style=\"color: #a31515;\">\"evolution\"<\/span>, <span style=\"color: #a31515;\">\"of\"<\/span>, <span style=\"color: #a31515;\">\"the\"<\/span>, <span style=\"color: #a31515;\">\"function\"<\/span>, <span style=\"color: #a31515;\">\"concept\"<\/span>, <span style=\"color: #a31515;\">\"in\"<\/span>, <span style=\"color: #a31515;\">\"C++.\"<\/span>};\r\n  \r\n  std::string fromFunc= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, addMe);\r\n  \r\n  std::cout &lt;&lt; fromFunc &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n  \r\n  std::string fromFuncObj= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, AddMe());\r\n  \r\n  std::cout &lt;&lt; fromFuncObj &lt;&lt; std::endl;\r\n  \r\n  std::string fromFuncObj2= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, AddMe(<span style=\"color: #a31515;\">\":\"<\/span>));\r\n  \r\n  std::cout &lt;&lt; fromFuncObj2 &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n  \r\n  std::string fromLambdaFunc= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, [](std::string fir, std::string sec){ <span style=\"color: #0000ff;\">return<\/span> fir + <span style=\"color: #a31515;\">\" \"<\/span> + sec; });\r\n  \r\n  std::cout &lt;&lt; fromLambdaFunc &lt;&lt; std::endl;\r\n  \r\n  std::string glue=<span style=\"color: #a31515;\">\":\"<\/span>;\r\n  \r\n  <span style=\"color: #0000ff;\">auto<\/span> lambdaFunc= [glue](std::string fir, std::string sec){ <span style=\"color: #0000ff;\">return<\/span> fir + glue + sec; };\r\n  \r\n  std::string fromLambdaFunc2=  std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, lambdaFunc);\r\n  \r\n  std::cout &lt;&lt; fromLambdaFunc2 &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n  \r\n  std::string fromLambdaFuncGeneric= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, [glue](<span style=\"color: #0000ff;\">auto<\/span> fir, <span style=\"color: #0000ff;\">auto<\/span> sec){ <span style=\"color: #0000ff;\">return<\/span> fir + glue + sec; });\r\n  \r\n  std::cout &lt;&lt; fromLambdaFuncGeneric &lt;&lt; std::endl;\r\n  \r\n  <span style=\"color: #0000ff;\">auto<\/span> lambdaFuncGeneric= [](<span style=\"color: #0000ff;\">auto<\/span> fir, <span style=\"color: #0000ff;\">auto<\/span> sec){ <span style=\"color: #0000ff;\">return<\/span> fir + sec; };\r\n  \r\n  <span style=\"color: #0000ff;\">auto<\/span> fromLambdaFuncGeneric1= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}, lambdaFuncGeneric);\r\n  \r\n  std::cout &lt;&lt; fromLambdaFuncGeneric1 &lt;&lt; std::endl;\r\n  \r\n  std::vector&lt;<span style=\"color: #2b91af;\">int<\/span>&gt; myInts={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\r\n  \r\n  <span style=\"color: #0000ff;\">auto<\/span> fromLambdaFuncGeneric2= std::accumulate(myInts.begin(), myInts.end(), <span style=\"color: #2b91af;\">int<\/span>{}, lambdaFuncGeneric);\r\n  \r\n  std::cout &lt;&lt; fromLambdaFuncGeneric2 &lt;&lt; std::endl;\r\n  \r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The program begins with the function <span style=\"font-family: courier new,courier;\">addMe<\/span> (line 8 &#8211; 10), the function object <span style=\"font-family: courier new,courier;\">AddMe<\/span> (line 12 &#8211; 23), the lambda function (line 45 and 51), and the generic lambda function in line 59, 63, and 64. The program&#8217;s purpose is to concatenate the strings of the vector myString (line 27) in different ways with the help of the algorithm <span style=\"font-family: courier new,courier;\">std::accumulate.<\/span> Therefore, it is pretty comfortable that <span style=\"font-family: courier new,courier;\">std::accumulate<\/span> is a higher-order function (wait for my next post) and can accept first-class functions. I use a function pointer, a function object, and a (generic) lambda function as the first-class function.<\/p>\n<p>I apply in line 29 the function pointer <span style=\"font-family: courier new,courier;\">addMe.<\/span> The function objects <span style=\"font-family: courier new,courier;\">AddMe<\/span> and <span style=\"font-family: courier new,courier;\">AddMe(:)<\/span> (lines 35 and 39) are more comfortable to use because I can parametrize the glue between the strings. The lambda functions offer the same comfort (lines 45 and 51). In particular, the lambda function <span style=\"font-family: courier new,courier;\">lambdaFunc<\/span> uses a copy of the variable <span style=\"font-family: courier new,courier;\">glue<\/span> (line 49). Therefore, the lambda function is a closure. The generic lambda function <span style=\"font-family: courier new,courier;\">[glue](auto fir, auto sec){ return fir + glue + sec; })<\/span> (line 59) is the most interesting one. As closure, they also use variable <span style=\"font-family: courier new,courier;\">glue.<\/span> I apply the generic lambda function<span style=\"font-family: courier new,courier;\"><\/span> <span style=\"font-family: courier new,courier;\">lambdaFuncGeneric<\/span> to a <span style=\"font-family: courier new,courier;\">std::vector&lt;std::string&gt; (line 27) <\/span>and a<span style=\"font-family: courier new,courier;\"> <\/span><span style=\"font-family: courier new,courier;\">std::vector&lt;int&gt;<\/span> (line 69). In the case of <span style=\"font-family: courier new,courier;\">std::vector&lt;int&gt;<\/span>, the result is 55.<\/p>\n<p>In the end, the output of the program.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5143\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/evolutionOfFunctions.png\" alt=\"evolutionOfFunctions\" width=\"588\" height=\"312\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/evolutionOfFunctions.png 588w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/evolutionOfFunctions-300x159.png 300w\" sizes=\"auto, (max-width: 588px) 100vw, 588px\" \/><\/p>\n<p><em>The evolution will not end with C++14. In C++20, we get high-probability coroutines, which generalize functions. Coroutines can be suspended and resumed. I will write a post about it. So, stay tuned.<br \/><\/em><\/p>\n<h3>But that can be done more easily<\/h3>\n<p>For didactical reasons, I used <span style=\"font-family: courier new,courier;\">std::accumulate<\/span> to add pairs of elements together. That can be done much more straightforward &#8211; even for generic lambda functions &#8211; because std::accumulate has a simple version that needs no callable. The simple version adds their elements together, starting with the first element. Therefore, I can write line 65 a lot simpler: <span style=\"font-family: courier new,courier;\">auto fromLambdaFuncGeneric1= std::accumulate(myStrings.begin(), myStrings.end(), std::string{}). <\/span>The same holds for<span style=\"font-family: courier new,courier;\"> <span style=\"font-family: courier new,courier;\">fromLambdaFuncGeneric2<\/span><\/span>.<span style=\"font-family: courier new,courier;\"> <\/span><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>I already mentioned it in the post. The classical counterpart to first-class functions is higher-order functions because they get first-class functions. The <a href=\"https:\/\/www.modernescpp.com\/index.php\/higher-order-functions\">next post<\/a> will be about higher-order functions\u2014the following property of functional programming.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the characteristics of functional programming is first-class functions. First-class functions behave like data and are heavily used in the Standard Template Library.<\/p>\n","protected":false},"author":21,"featured_media":5141,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[365],"tags":[],"class_list":["post-5144","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-functional"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5144","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=5144"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5144\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5141"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5144"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5144"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5144"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}