{"id":5160,"date":"2017-02-01T20:46:33","date_gmt":"2017-02-01T20:46:33","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/recursion-list-manipulation-and-lazy-evaluation\/"},"modified":"2024-07-22T16:34:09","modified_gmt":"2024-07-22T16:34:09","slug":"recursion-list-manipulation-and-lazy-evaluation","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/recursion-list-manipulation-and-lazy-evaluation\/","title":{"rendered":"Recursion, List Manipulation, and Lazy Evaluation"},"content":{"rendered":"<p>The remaining three characteristics of functional programming are told quite quickly: Recursion, manipulation of lists, and lazy e Ihop valuation.<\/p>\n<p><!--more--><\/p>\n<h2>Recursion<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5156\" style=\"margin: 15px;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikRecursionEng.png\" alt=\"CharakteristikRecursionEng\" width=\"467\" height=\"447\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikRecursionEng.png 467w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikRecursionEng-300x287.png 300w\" sizes=\"auto, (max-width: 467px) 100vw, 467px\" \/><\/p>\n<p>Pure functional languages support no mutable data. Instead of a loop, they use recursion. The meta-function from <a href=\"https:\/\/www.modernescpp.com\/index.php\/pure-functions\">Pure Functions<\/a> showed it already. At compile time, I use recursion instead of loops. The factorial function in C++<\/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: #0000ff;\">template<\/span> &lt;<span style=\"color: #2b91af;\">int<\/span> N&gt;\n<span style=\"color: #0000ff;\">struct<\/span> Fac{\n  <span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #2b91af;\">int<\/span> <span style=\"color: #0000ff;\">const<\/span> value= N * Fac&lt;N-1&gt;::value;\n};\n\n<span style=\"color: #0000ff;\">template<\/span> &lt;&gt;\n<span style=\"color: #0000ff;\">struct<\/span> Fac&lt;0&gt;{\n  <span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #2b91af;\">int<\/span> <span style=\"color: #0000ff;\">const<\/span> value = 1;\n};\n<\/pre>\n<\/div>\n<p>can be written quite easily in Haskell:<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">fac 0<span style=\"color: #0000ff;\">=<\/span> 1<\/div>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">fac n<span style=\"color: #0000ff;\">=<\/span> n * fac (n-1)<\/div>\n<div>But, there is a small difference between the recursive factorial function in Haskell and C++. To be precise, the C++ version is not recursive. Each invocation of the general class template with the template argument N instantiates a new class template with the template argument N-1. The graphic shows the process.<\/div>\n<div><\/div>\n<div><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5157\" style=\"margin: 15px;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/TemplateInstantiation.png\" alt=\"TemplateInstantiation\" width=\"500\" height=\"299\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/TemplateInstantiation.png 654w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/TemplateInstantiation-300x179.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/div>\n<div><\/div>\n<div>You can create powerful functions using recursion with lists and pattern matching. But that only holds partially for C++.<\/div>\n<div><\/div>\n<h2>Manipulation of lists<\/h2>\n<h2>\u00a0<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5158\" style=\"margin: 15px;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikListManipulationEng.png\" alt=\"CharakteristikListManipulationEng\" width=\"452\" height=\"435\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikListManipulationEng.png 452w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikListManipulationEng-300x289.png 300w\" sizes=\"auto, (max-width: 452px) 100vw, 452px\" \/><\/h2>\n<p><strong>LIS<\/strong>t <strong>P<\/strong>rocessing (LISP) is a characteristic of functional programming languages. The list is the foundation of the potent function composition in a functional language because it is the general data structure.<\/p>\n<p>The processing of lists follows a simple pattern:<\/p>\n<ol>\n<li>Process the first element of the list.<\/li>\n<li>Recursively process the rest of the list, reducing each iteration by the first element.<\/li>\n<\/ol>\n<p>Because list processing is so idiomatic in functional programming, there exist special names for the first element and the rest of the list: (x, xs), (head, tail), or (car, cdr).<\/p>\n<p>The pattern for processing the list is directly applicable in Haskell and C++.<\/p>\n<p>Firstly, the concise version of C++. The function <span style=\"font-family: courier new,courier;\">mySum<\/span> sums up the numbers from 1 to 5.<\/p>\n<p><!-- HTML generated using hilite.me --><\/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%;\">mySum <span style=\"color: #2b91af;\">[]<\/span>     <span style=\"color: #0000ff;\">=<\/span> 0\nmySum (x<span style=\"color: #2b91af;\">:<\/span>xs) <span style=\"color: #0000ff;\">=<\/span> x + mySum xs\nmySum [1,2,3,4,5]  <span style=\"color: #008000;\">-- 15<\/span>\n<\/pre>\n<\/div>\n<p>And here is the C++ version.<\/p>\n<p><!-- HTML generated using hilite.me --><\/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\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n13\n14<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0000ff;\">template<\/span>&lt;<span style=\"color: #2b91af;\">int<\/span> ...&gt; \n<span style=\"color: #0000ff;\">struct<\/span> mySum;\n\n<span style=\"color: #0000ff;\">template<\/span>&lt;&gt;\n<span style=\"color: #0000ff;\">struct<\/span> mySum&lt;&gt;{\n  <span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #0000ff;\">const<\/span> <span style=\"color: #2b91af;\">int<\/span> value= 0;\n};\n\n<span style=\"color: #0000ff;\">template<\/span>&lt;<span style=\"color: #2b91af;\">int<\/span> head, <span style=\"color: #2b91af;\">int<\/span> ... tail&gt;\n<span style=\"color: #0000ff;\">struct<\/span> mySum&lt;head,tail...&gt;{\n  <span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #0000ff;\">const<\/span> <span style=\"color: #2b91af;\">int<\/span> value= head + mySum&lt;tail...&gt;::value;\n};\n\n<span style=\"color: #2b91af;\">int<\/span> sum= mySum&lt;1,2,3,4,5&gt;::value;  <span style=\"color: #008000;\">\/\/ 15<\/span>\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>The Haskell version is relatively easy to get. Or? But the C++ version is quite heavyweight. The C++ syntax requires that the primary, also called the general template, must be declared. Line 4 to line 7 is the fully specialized template (meta-metafunction) used for the empty argument list. If at least one template argument is used, the partially specialized class template (lines 9 &#8211; 12) kicks in. Let me say a few words to the three dots, the so-called ellipse. That is why the class in line 14 can take an arbitrary number of arguments. The three dots in lines 1 and 9 pack the template parameter pack; the three dots in lines 10 and 11 unpack the function parameter pack.<\/p>\n<p>Haskell and C++ apply pattern matching to use the right function.<\/p>\n<h3>Pattern matching<\/h3>\n<p>There is a subtle difference between Haskell and C++. Haskell&#8217;s matching strategy is the first match. That&#8217;s the reason you have to define the particular case first. C++ matching strategy is the best to match. You can use pattern matching to define the multiplication of two numbers by successively applying addition.<\/p>\n<p>For the sake of elegance, C++ first.<\/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\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0px; line-height: 125%;\">mult n 0 <span style=\"color: #0000ff;\">=<\/span> 0\nmult n 1 <span style=\"color: #0000ff;\">=<\/span> n\nmult n m <span style=\"color: #0000ff;\">=<\/span> (mult n (m - 1)) + n\n\n\n\nmult 3 2 <span style=\"color: #0000ff;\">=<\/span> (mult 3 (<span style=\"color: #000000;\">2 - <\/span>1)) + 3\n         <span style=\"color: #0000ff;\">=<\/span> (mult 3 1 ) + 3\n         <span style=\"color: #0000ff;\">=<\/span> 3 + 3\n         <span style=\"color: #0000ff;\">=<\/span> 6\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>Lines 7 &#8211; 10 show the enrolled multiplication of the two numbers, 3 and 2. Line 1 is applied if <span style=\"font-family: courier new,courier;\">m == 0<\/span> holds. If <span style=\"font-family: courier new,courier;\">m == 1<\/span> holds, line 2 is used. The general case is line 3.<\/p>\n<p>C++ applies a similar strategy. The difference is that the C++ version is more verbose, and I must first define the general case.<\/p>\n<p><!-- HTML generated using hilite.me --><\/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\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n13\n14\n15<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0000ff;\">template<\/span> &lt;<span style=\"color: #2b91af;\">int<\/span> N, <span style=\"color: #2b91af;\">int<\/span> M&gt;\n<span style=\"color: #0000ff;\">struct<\/span> Mult{\n<span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #0000ff;\">const<\/span> <span style=\"color: #2b91af;\">int<\/span> value= Mult&lt;N, M-1&gt;::value + N;\n};\n<span style=\"color: #0000ff;\">template<\/span> &lt;<span style=\"color: #2b91af;\">int<\/span> N&gt;\n<span style=\"color: #0000ff;\">struct<\/span> Mult&lt;N, 1&gt; {\n<span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #0000ff;\">const<\/span> <span style=\"color: #2b91af;\">int<\/span> value= N;\n};\n\n<span style=\"color: #0000ff;\">template<\/span> &lt;<span style=\"color: #2b91af;\">int<\/span> N&gt;\n<span style=\"color: #0000ff;\">struct<\/span> Mult&lt;N, 0&gt; {\n<span style=\"color: #0000ff;\">static<\/span> <span style=\"color: #0000ff;\">const<\/span> <span style=\"color: #2b91af;\">int<\/span> value= 0;\n};\n\nstd::cout &lt;&lt; Mult&lt;3, 2&gt;::value &lt;&lt; std::endl;    <span style=\"color: #008000;\">\/\/ 6<\/span>\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h2>Lazy evaluation<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5159\" style=\"margin: 15px;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikLazyEvaluationEng.png\" alt=\"CharakteristikLazyEvaluationEng\" width=\"472\" height=\"471\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikLazyEvaluationEng.png 472w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikLazyEvaluationEng-300x300.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/02\/CharakteristikLazyEvaluationEng-150x150.png 150w\" sizes=\"auto, (max-width: 472px) 100vw, 472px\" \/><\/p>\n<p>The story about lazy evaluation in C++ is relatively short. That will change in C++20 with the ranges library from Eric Niebler. Lazy evaluation is the default in Haskell. Lazy evaluation means that an expression is only evaluated when needed. This strategy has two benefits.<\/p>\n<ol>\n<li>Lazy evaluation helps you to save time and memory.<\/li>\n<li>You can define algorithms on infinite data structures. Of course, you can only ask for a finite number of values at run time.<\/li>\n<\/ol>\n<p>The following code snippet shows three impressive examples in Haskell:<\/p>\n<p><!-- HTML generated using hilite.me --><\/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\n2\n3\n4\n5\n6\n7\n8<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\">length [2+1, 3*2, 1\/0, 5-4]  <span style=\"color: #008000;\">-- 4<\/span>\n\nsuccessor i<span style=\"color: #0000ff;\">=<\/span> i<span style=\"color: #2b91af;\">:<\/span> (successor (i+1))\ntake 5 ( successor 1 )     <span style=\"color: #008000;\">-- [1,2,3,4,5]<\/span>\n\nodds<span style=\"color: #0000ff;\">=<\/span> takeWhile (&lt; 1000) . filter odd . map (^2)\n[1..]<span style=\"color: #0000ff;\">=<\/span> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ... <span style=\"color: #2b91af;\">Control<\/span>-<span style=\"color: #2b91af;\">C<\/span>  \nodds [1..]                 <span style=\"color: #008000;\">-- [1,9,25, ... , 841,961]  <\/span>\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>I can calculate the length of a list in the first line, including the argument 1\/0.\u00a0 successor in line 3 defines an infinite sequence of integers. But I only request five (<span style=\"font-family: courier new,courier;\">take 5<\/span>) in line 4. Therefore, all is fine. If I want to have all integers, such as in line 7, I must hit Control-C to stop the recursion.\u00a0 I can use the same expression\u00a0 <span style=\"font-family: courier new,courier;\">[1..]<\/span> as an argument for the function <span style=\"font-family: courier new,courier;\">odds.<\/span> Line 6 shows the power off function composition in Haskell. The dot (.) is the symbol for function composition. With a bit of exercise, you can read the function composition in line 6 from right to left: Apply to each argument the square function; let the odd elements pass and continue as long as the resulting numbers are smaller than 1000. You can see the result of the application in the last list.<\/p>\n<p>C++ uses, by default, eager evaluation. This means that contrary to Haskell, expressions are evaluated from the inside to the outside. C++ has short circuit evaluation. So, C++ is a little bit lazy. If the result of a logical expression is given before the whole expression is evaluated, C++ stops to evaluate the expression. Therefore, the following code snippet is valid in C++, although 1\/0 is not defined.<\/p>\n<p><!-- HTML generated using hilite.me --><\/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: #0000ff;\">if<\/span> ( true or (1\/0) ) std<span style=\"color: #0000ff;\">::<\/span>cout &lt;&lt; <span style=\"color: #a31515;\">\"short circuit evaluation\"<\/span> &lt;&lt; std<span style=\"color: #0000ff;\">::<\/span>endl;<\/pre>\n<\/div>\n<h2>What&#8217;s next?<\/h2>\n<p>With the <a href=\"https:\/\/www.modernescpp.com\/index.php\/fold-expressions\">next pos<\/a>t, I step into the future of C++. Fold expressions in C++17 are based on variadic templates and can be used to apply the <a href=\"https:\/\/www.modernescpp.com\/index.php\/higher-order-functions\">fold<\/a> algorithm at compile time.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The remaining three characteristics of functional programming are told quite quickly: Recursion, manipulation of lists, and lazy e Ihop valuation.<\/p>\n","protected":false},"author":21,"featured_media":5156,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[365],"tags":[508],"class_list":["post-5160","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-functional","tag-haskell"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5160","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=5160"}],"version-history":[{"count":2,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5160\/revisions"}],"predecessor-version":[{"id":9777,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5160\/revisions\/9777"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5156"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5160"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5160"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5160"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}