    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Template Programming Compile Time Combinations &amp; Sieves</title>
        <link>https://members.accu.org/index.php/articles/2200</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #131 - February 2016</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c358/">o131</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-358/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+358/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Template Programming Compile Time Combinations &amp; Sieves</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 04 February 2016 18:50:45 +00:00 or Thu, 04 February 2016 18:50:45 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Functional style frequently uses sequences. Nick Weatherhead applies these ideas to combinations in C++.</p>
<p><strong>Body:</strong>&nbsp;<p>Previously [<a href="#[Weatherhead15]">Weatherhead15</a>], I discussed the use of C++ templates to compile time program some well-known string katas. Template metaprogramming in this way imposes a functional style with the immutability of variables a key consideration. In this article Iâ€™m applying the same treatment to combinations of k elements and a variation on Eratosthenes sieve. The foundations for each are built as we go along including holding data within lists, adding and removing items from them, implementing queues, defining sequences and operating on them with sets. There is a bit to it so you may wish to skip ahead to a solution and come back to the detail. Either is fine but youâ€™ll probably want to keep Listing 1 to hand for reference.</p>

<h2>Lists</h2>

<p>Without arrays and mutability at our disposal, a structure is required that can represent a list and after each operation produces a new variant. Itâ€™s common for functional languages to have an operation which adds an element to the beginning of a list and is typically known as cons (short for construct). This functional list differs from the imperative viewpoint of linearly linking elements with a head at one end, a body and a tail at the other. Instead it is woven from a compound pair of pairs. Each pair comprises a head plus tail that splits until a null tail terminates a given path. Itâ€™s good to have an appreciation of its recursive nature and the other features it affords see [<a href="#[SICP96]">SICP96</a>]. However, for the most part, this article will attempt to adhere to the metaphor for a single chain.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
  1 #include &lt;iostream&gt;
  2
  3 using namespace std;
  4
  5 struct nop {
  6
  7   static const char delim = '\0';
  8
  9   friend ostream&amp; operator&lt;&lt;( ostream&amp; os
 10   , const nop&amp; ) { return os; }
 11 };
 12
 13 struct nil : nop {
 14
 15   typedef nil type;
 16
 17   template&lt; size_t SIZE = 0 &gt; struct size {
 18
 19     static const size_t value = SIZE;
 20
 21     friend ostream&amp; operator&lt;&lt;( ostream&amp; os
 22     , const size&amp; ) { return os &lt;&lt; SIZE; }
 23   };
 24
 25   template&lt; class RHS &gt;
 26   struct append  : RHS { typedef RHS type; };
 27   template&lt; class RHS &gt;
 28   struct prepend : append&lt; RHS &gt; { };
 29   template&lt; class RHS &gt;
 30   struct uunion  : append&lt; RHS &gt; { };
 31   template&lt; class RHS &gt;
 32   struct except  : nop { typedef nil type; };
 33   template&lt; class RHS &gt;
 34   struct intrsct : except&lt; RHS &gt; { };
 35
 36   template&lt; size_t N, size_t I_SIZE, class O
 37   , size_t O_SIZE = 0 &gt; struct kombine_
 38   : conditional&lt; O_SIZE == N, O, nop &gt;::type
 39   { };
 40 };
 41
 42 template&lt; class HEAD, class TAIL
 43 , char DELIM = ',' &gt; struct list_ {
 44
 45   #define t typename
 46
 47   typedef list_  type; typedef list_  LHS;
 48   typedef HEAD   head; typedef TAIL   tail;
 49
 50   static const char delim = DELIM;
 51
 52   friend ostream&amp; operator&lt;&lt;( ostream&amp; os
 53   , const list_&amp; ) { return os
 54     &lt;&lt; HEAD( ) &lt;&lt; tail::delim &lt;&lt; TAIL( ); }
 55
 56   template&lt; size_t SIZE = 0 &gt; struct size
 57   : tail::template size&lt; SIZE + 1 &gt; { };
 58
 59   template&lt; class RHS &gt; struct append
 60   : list_&lt; LHS, RHS, DELIM &gt; { };
 61   template&lt; class RHS &gt; struct prepend
 62   : list_&lt; RHS, LHS, DELIM &gt; { };
 63
 64   template&lt; class LHS, class RHS &gt;
 65   struct append_
 66   : LHS::type::template append&lt; RHS &gt;  { };
 67   template&lt; class LHS, class RHS &gt;
 68   struct prepend_
 69   : LHS::type::template prepend&lt; RHS &gt; { };
 70   template&lt; class LHS, class RHS &gt;
 71   struct except_
 72   : LHS::type::template except&lt; RHS &gt;  { };
 73   template&lt; class LHS, class RHS &gt;
 74   struct uunion_
 75   : LHS::type::template uunion&lt; RHS &gt;  { };
 76   template&lt; class LHS, class RHS &gt;
 77   struct intrsct_
 78   : LHS::type::template intrsct&lt; RHS &gt; { };
 79
 80   template&lt; class RHS, bool = true &gt;
 81   struct uunion
 82   : conditional&lt; ( LHS::head::value &lt;
 83                    RHS::head::value )
 84     , append_&lt;   LHS::head
 85       , uunion_&lt; LHS::tail,   RHS       &gt; &gt;
 86     , append_&lt; t RHS::head
 87       , uunion_&lt; LHS      , t RHS::tail &gt; &gt;
 88     &gt;::type {
 89       typedef HEAD head; typedef TAIL tail; };
 90
 91   template&lt; bool NA &gt; struct uunion&lt; nil, NA &gt;
 92   : append_&lt; head, tail &gt; { };
 93
 94   template&lt; class RHS, bool = true &gt;
 95   struct intrsct
 96   : conditional&lt; is_same&lt; LHS, RHS &gt;::value
 97     , LHS
 98     , t conditional&lt; ( LHS::head::value ==
 99                        RHS::head::value   )
100       , append_&lt; LHS::head
101         , intrsct_&lt; LHS::tail, t RHS::tail &gt; &gt;
102       , t conditional&lt; ( LHS::head::value &lt;
103                          RHS::head::value  )
104         , intrsct_&lt; LHS::tail,   RHS     &gt;
105         , intrsct_&lt; LHS      , t RHS::tail &gt;
106         &gt;::type
107       &gt;::type
108     &gt;::type {
109       typedef HEAD head; typedef TAIL tail; };
110
111   template&lt; bool NA &gt;
112   struct intrsct&lt; nil, NA &gt; : nil { };
113
114   template&lt; class RHS, bool = true &gt;
115   struct except
116   : conditional&lt; is_same&lt; LHS, RHS &gt;::value
117     , nil
118     ,t conditional&lt; ( LHS::head::value &lt;
119                       RHS::head::value  )
120       , append_&lt; t LHS::head
121         , except_&lt; LHS::tail,   RHS       &gt; &gt;
122       , t conditional&lt; ( LHS::head::value &gt;
123                          RHS::head::value )
124         , except_&lt; LHS      , t RHS::tail &gt;
125         , except_&lt; LHS::tail, t RHS::tail &gt;
126         &gt;::type
127       &gt;::type
128     &gt;::type {
129       typedef HEAD head; typedef TAIL tail; };
130
131   template&lt; bool NA &gt; struct except&lt; nil, NA &gt;
132   : append_&lt; head, tail &gt; { };
133
134   template&lt; size_t N, size_t I_SIZE
135   , class O, size_t O_SIZE &gt; class kkombine_ {
136
137     friend ostream&amp; operator&lt;&lt;( ostream&amp; os
138     , const kkombine_&amp; that ) {
139
140       static const int i_size = I_SIZE - 1;
141
142       return os
143       &lt;&lt; t TAIL::template kombine_&lt; N, i_size
144        , prepend_&lt; HEAD, O &gt;, O_SIZE + 1 &gt;( )
145       &lt;&lt; t TAIL::template kombine_&lt; N, i_size
146        , O                  , O_SIZE     &gt;( );
147   } };
148
149   template&lt; size_t N, size_t I_SIZE, class O
150     = nop, size_t O_SIZE = 0 &gt; struct kombine_
151   : conditional&lt; !O_SIZE &amp;&amp; I_SIZE == N
152     , prepend_&lt; type, nop &gt;
153     , t conditional&lt; O_SIZE == N, O
154       , t conditional&lt; !I_SIZE, nil
155         , kkombine_&lt; N, I_SIZE, O, O_SIZE &gt;
156         &gt;::type
157       &gt;::type
158     &gt;::type { };
159
160   template&lt; size_t N &gt; struct kombine
161   : kombine_&lt; N, size&lt; &gt;::value &gt; { };
162
163   template&lt; size_t N, bool NA = true &gt;
164   struct powerset_ {
165
166     friend ostream&amp; operator&lt;&lt;( ostream&amp; os
167     , const powerset_&amp; that ) { return os
168       &lt;&lt; powerset_&lt; N - 1 &gt;( )
169       &lt;&lt; kombine&lt; N &gt;( ); }
170   };
171
172   template&lt; bool NA &gt;
173   struct powerset_&lt; 0,  NA &gt; : nop { };
174
175   struct powerset
176   : powerset_&lt; size&lt; &gt;::value &gt; { };
177
178   #undef t
179 };
180
181 template&lt; class HEAD, class TAIL
182 , char DELIM = ',' &gt; struct list
183 : list_&lt; HEAD, TAIL, DELIM &gt; { };
184
185 template&lt; class TAIL, char DELIM &gt;
186 struct list_&lt; nop, TAIL, DELIM &gt; : TAIL {
187
188   friend ostream&amp; operator&lt;&lt;(
189     ostream&amp; os, const list_&amp; ) {
190     return os &lt;&lt; ' ' &lt;&lt; TAIL( ); }
191 };
192
193 template&lt; class HEAD, char DELIM &gt;
194 struct list&lt; HEAD, nil, DELIM &gt;
195 : list_&lt; HEAD, nil, DELIM &gt; {
196
197   typedef HEAD type;
198
199   friend ostream&amp; operator&lt;&lt;(
200     ostream&amp; os, const list&amp; ) {
201     return os &lt;&lt; HEAD::value; }
202
203   template&lt; class RHS &gt; struct append
204   : list&lt; HEAD, RHS, DELIM &gt; { };
205   template&lt; class RHS &gt; struct prepend
206   : list&lt; RHS, HEAD, DELIM &gt; { };
207 };
208
209 template&lt; class T, T V, class VS, char DELIM &gt;
210 struct v
211 : list&lt; v&lt; T, V, nil, DELIM &gt;, VS, DELIM &gt; {
212   static const T value = V; };
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>In Listing 1, <code>list_</code> (42â€“179) takes a <code>HEAD</code> element and <code>TAIL</code> elements; an additional parameter <code>DELIM</code> defines the separator used between elements when printing. Appending an underscore to a classâ€™s name is the convention used here to indicate internal usage, hence, <code>list</code> (181â€“183) exposes <code>list_</code>. No-operation <code>nop</code> (5â€“11) simply places a null marker into the output as a guard element. A specialisation of <code>list_</code> (185â€“191) which has <code>nop</code> as its head element is used to indicate that itâ€™s a list of lists and when printed each list can be delimited by another character. Another <code>list</code> (193â€“207) is provided for elements at the end of a list i.e. thatâ€™s <code>TAIL</code> is <code>nil</code> (13â€“40) where some functions are overridden whilst <code>nil</code> implements functions that operate on an empty list. When performingoperations between elements it is convenient to think in terms of what appears on the right and left hand sides, so <code>list_</code> provides some internal functions that take <code>RHS</code> and <code>LHS</code> respectively. A value of type <code>v</code> (209â€“212) is itself a <code>list_</code> with its <code>HEAD</code> being a single value element of the same type. Thus each element can be operated on in the same way.</p>

<h2>Queues</h2>

<p>Imperative lists and vectors describe consecutive elements, as does the functional list, and all can be used as the underlying structure of a queue. Removing the <code>HEAD</code> of a <code>list_</code> requires a simple reference to the <code>TAIL</code> elements. To <code>prepend</code> (28â€“29, 61â€“62, 205â€“206) elements another <code>list_</code> is created with the new content in the <code>HEAD</code> and the existing content in the <code>TAIL</code>; <code>append</code> (28â€“29, 59â€“60, 203â€“204) just reverses the concatenation of the <code>HEAD</code> and <code>TAIL</code>. There are also implementations of these that take explicit left and right hand side arguments â€“ see <code>append_</code> (65â€“66) and <code>prepend_</code> (67â€“78).</p>

<h2>Size</h2>

<p>Functional programs donâ€™t have loop constructs so rely on recursion to perform inductive operations. Templates donâ€™t optimise tail recursive calls so each grows the stack, hence compilers place a limit on its depth (note that despite this if an expression is sufficiently long itâ€™s still feasible to exhaust the memory). A classic way to observe this is to use a size function <code>size&lt; &gt;</code> (17â€“23, 56â€“57) that iterates over a list to obtain a count. Whatâ€™s not always clear is that functors used as default template parameter arguments can be evaluated independently of the template to which theyâ€™re applied. Take <code>list_&lt;HEAD, TAIL&gt;::kombine_&lt;N, I_SIZE, O = nop, O_SIZE = 0&gt;</code> (149â€“158), if the input size <code>I_SIZE</code> is defaulted to <code>size&lt;&gt;</code> one might expect it to be calculated, as per a regular function, on invocation. However, as <code>size&lt;&gt;</code>â€™s template parameters are not dependent on <code>kombine_</code>â€™s the compiler instantiates it whenever <code>list_</code> is called. This is okay for k-combinations but would unintentionally execute for primes too. To prevent this the default is wrapped by <code>kombine&lt;N&gt;</code> (160â€“161). Alternatively how about having a size attribute i.e. <code>size = 1</code> for single elements and <code>size = HEAD::size + TAIL::size</code> as they are combined? This is fine when the <code>HEAD</code> and <code>TAIL</code> are lists. However, they are also used for list expressions; size isnâ€™t intrinsic to these and their resultant type is unknown until fully evaluated.</p>

<h2>Combinations</h2>

<p>The brief is to find all the unique combinations of <em>k</em> elements from a set of distinct values. For the purpose of this discussion each element has its own letter and the input set is in alphabetical order.</p>

<p>In Figure 1 (<em>k</em>-combinations) the input elements are treated as a queue; at each step the last item is removed from the top of the queue and either placed at the bottom of the output queue when branching right or dropped when going left. If the output reaches the desired length before the input queue is exhausted then it forms a terminal node and branching ceases. Further, if the input is of the required length and the output queue is empty then the input can be directly substituted for the output without further branching.</p>

<p><img src="http://accu.org/content/images/journals/ol131/Weatherhead/Weatherhead-01.png" /></p>

<p>Here <em>k</em>-combinations (Listing 2) are represented with consecutive characters, specified by <code>c</code> and <code>cs</code>. As previously mentioned <code>list_&lt;HEAD, TAIL&gt;::kombine&lt;N&gt;</code> (160â€“161) wraps the initial call <code>list_&lt;HEAD, TAIL&gt;::kombine_&lt;N, size&lt; &gt;, nop, 0&gt;</code>. This takes parameters for the desired combination length, the size of the input list which when first called is the size of the initial list, the output list and its size which are initially empty. The underlying definition <code>list_&lt;HEAD, TAIL&gt;::kombine_&lt;N, I_SIZE, O, O_SIZE&gt;</code> (149â€“158) makes several checks. The first sees if the output can be directly substituted with the input. Otherwise a check is made to see if the output list has reached the desired length. If neither of these are satisfied <code>list_&lt;HEAD, TAIL &gt;::kkombine_&lt;N, I_SIZE, O, O_SIZE&gt;</code> (134â€“147) is called to branch left and right. If the end of the input list is reached i.e. <code>nil::kombine_&lt;N, size&lt;&gt;, nop, 0&gt;</code> (36â€“39) branching ceases with or without the output having reached the specified length. The <code>powerset</code> (175â€“176) is implemented as all the combinations of <em>k</em> for 0 to <em>n</em> elements.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
â€¦
template&lt; char C, class CS = nil
, char DELIM = '\0' &gt; struct c
: v&lt; char, C, CS, DELIM &gt;            { };
template&lt; char C, char... CS &gt;
struct cs      : c&lt; C, cs&lt; CS... &gt; &gt; { };
template&lt; char C &gt;
struct cs&lt; C &gt; : c&lt; C &gt;              { };

int main( ) {

  /* kombine('abcd', 2)=' ab ac ad bc bd cd'  *
   * powerset('abcd')=' a b c d ab ac ad bc   *
   * bd cd abc abd acd bcd abcd'              */
  cout
   &lt;&lt; &quot;\nkombine('abcd', 2)='&quot;
   &lt;&lt; cs&lt;'a','b','c','d'&gt;::kombine&lt;2&gt;( )&lt;&lt; &quot;'&quot;
   &lt;&lt; &quot;\npowerset('abcd')='&quot;
   &lt;&lt; cs&lt;'a','b','c','d'&gt;::powerset( ) &lt;&lt; &quot;'&quot;;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>It can be seen from the enumeration of elements that the permutations, whilst not strictly necessary, are in lexicographic order. Another way of representing combinations is in binary whereby each bit set maps to a corresponding value to print. Investigation of this is left as an additional exercise.</p>

<h2>Member template specialisation</h2>

<p>You may have noticed that there are a number of member template functors that take an additional, seemingly redundant, parameter; in each case these have a specialisation. For example the power set is all the subsets of an input set including itself and the empty set. In the general case this is lists between the length of the input list <code>powerset_&lt;N&gt;</code> to <code>powerset_&lt;1&gt;</code> (163â€“170). A specialisation <code>powerset_&lt;0&gt;</code> (172â€“173) terminates the set with an empty list. Nested classes are dependent on their enclosing template types, hence if explicitly specialised the enclosing classes need to be too. A work-around to this restriction is to provide partial specialisations by adding a dummy parameter.</p>

<h2>Sequences</h2>

<p>Lists can be long; however, if the content is not arbitrarily distributed then it can be described as a function rather than with individual elements. Evaluating the function and generating the list can then be deferred until first use. This is the case for sieving ranges of numbers with set intervals.</p>

<p>In Listing 3 (Sequences &amp; Sets) a cons of integers <code>i</code> is defined for use as a sequence <code>seq</code>. The common case produces all integers in ascending order between a low <code>LO</code> and high <code>HI</code> value. The interval <code>I</code> can be altered to increase the step size. Reversing direction by beginning at a high value, ending with a low value and specifying a negative increment will produce a sequence in descending order. At each step the current value is appended to the list and, whilst within bounds, the next step is defined as a sequence of itself with an incremented starting range.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
â€¦
template&lt; int I, class IS = nil
, char DELIM = ',' &gt; struct i
: v&lt; int, I, IS, DELIM &gt;             { };
template&lt; int I, int... IS &gt;
struct is      : i&lt; I, is&lt; IS... &gt; &gt; { };
template&lt; int I &gt;
struct is&lt; I &gt; : i&lt; I &gt;              { };

template&lt; int LO, int HI, int I = 1
, char DELIM = ',' &gt; struct seq
: conditional&lt;
  ( I &gt; 0 ? LO + I &lt;= HI : LO &gt;= HI - I )
  , i&lt; LO, seq&lt; LO + I, HI, I, DELIM &gt; &gt;
  , i&lt; LO &gt; &gt;::type { };

int main( ) {

  /* seq(-3, 3, 2).uunion(seq(-2, 2, 2))= *
   *     -3,-2,-1,0,1,2,3                 *
   * seq(-3, 3).intrsct(seq(-2, 2, 2))=   *
   *     -2,0,2                           *
   * seq(-3, 3).except(seq(-2, 2, 2))=    *
   *     -3,-1,1,3                        */
  cout
  &lt;&lt; &quot;\nseq(-3, 3, 2).uunion(seq(-2, 2, 2))=&quot;
  &lt;&lt; seq&lt;-3, 3, 2&gt;::uunion&lt; seq&lt;-2, 2, 2&gt;&gt;( )
  &lt;&lt; &quot;\nseq(-3, 3).intrsct(seq(-2, 2, 2))=&quot;
  &lt;&lt; seq&lt;-3, 3&gt;::intrsct&lt;seq&lt; -2, 2, 2&gt;&gt;( )
  &lt;&lt; &quot;\nseq(-3, 3).except(seq(-2, 2, 2))=&quot;
  &lt;&lt; seq&lt;-3, 3&gt;::except&lt;seq&lt;-2, 2, 2&gt;&gt;( );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<h2>Sets</h2>

<p>In addition to sequences some set theory is required to sieve. Union, intersection and difference of ascending ordered sets are provided (a description of each follows) although not all will be required. When combining operations itâ€™s feasible that earlier operations result in an empty list, hence the member templates for sets (30â€“34) in <code>nil</code>.</p>

<h3>Union</h3>

<p>The general case <code>list&lt;HEAD, TAIL&gt;::uunion&lt;RHS&gt;</code> (80â€“89) determines which <code>HEAD</code>, the <code>LHS</code> or <code>RHS</code>, is less than the other. Whichever is chosen becomes the <code>HEAD</code> of a new list with the rest being the union of its <code>TAIL</code> with the other list. The union of a list with an empty list is the list itself (91â€“92). As it isnâ€™t fully defined at the point of parsing its creation is delayed with a concatenation operation i.e. <code>append_&lt;HEAD, TAIL&gt;</code>.</p>

<h3>Intersection</h3>

<p>The general case <code>list&lt;HEAD, TAIL&gt;::intrsct&lt;R&gt;</code> (94â€“109) determines whether the <code>LHS</code> and <code>RHS</code>â€™s <code>HEAD</code>s are of equal value; if they are one becomes the <code>HEAD</code> of the resulting list with the rest comprising the intersection of the respective listâ€™s <code>TAIL</code>s. Otherwise, the <code>HEAD</code> with least value is discarded and the intersection between the remaining elements is performed. Intersection with an empty list (111â€“112) is, of course, <code>nil</code>.</p>

<h3>Set difference</h3>

<p>Known here as <code>list&lt;HEAD, TAIL&gt;::except&lt;R&gt;</code> (114â€“129) it is the equivalent of minus where any elements in the <code>LHS</code> that also appear in the <code>RHS</code> are removed. If both the <code>LHS</code> and <code>RHS</code> are identical then they cancel one another out resulting in the empty list <code>nil</code>; otherwise, the <code>HEAD</code> of each is compared. If the <code>LHS</code> is less than the <code>RHS</code> then it becomes the <code>HEAD</code> of a new list with the rest being the set difference between its <code>TAIL</code> and the <code>RHS</code>â€™s. If itâ€™s greater the <code>RHS</code>â€™s <code>HEAD</code> is removed and if equal both <code>HEAD</code>s are removed with the set difference calculated between the remaining elements. If the <code>RHS</code> is an empty list then there is nothing to minus (131â€“132); as with union the list isnâ€™t fully defined at the point of parsing so a concatenation operation i.e. <code>append_&lt;HEAD, TAIL&gt;</code> delays its creation.</p>

<h2>Sieves</h2>

<p>Eratosthenes proposed a simple way for finding primes up to a specified integer using the efficient principal of sieving. There are other well-known variations such as Eulerâ€™s sieve. The basic mechanism removes multiples of each integer between 2 and <em>n</em> thereby leaving only those that are divisible by one and themselves. There are some quick ways to refine this algorithm which also reduce recursive calls. All even numbers with the exception of 2 can be removed from the initial range; that is all multiples seeded from an even index and every other value from those with an odd. Further, as in table 1, higher order progressions have some values that overlap with lower ones. Thus sequences can begin at the square of their seed. Similarly it is unnecessary to go beyond an index that is âˆš<em>n</em> as if <em>n</em> is not prime it must have a divisor less than or equal to âˆš<em>n</em> [<a href="#[SICP96]">SICP96</a>]. Table 1 shows the arithmetic progressions required to sieve integers between 2 and 100. </p>

<table class="sidebartable">
	<tr>
		<td>
			<table class="journaltable">
				<tr>
					<th>Index (Odd N)</th>
					<th>Interval (N + N)</th>
					<th>Begin (N x N)</th>
					<th colspan="5">Arithmetic Progression</th>
				</tr>
				<tr>
					<td>3</td>
					<td>6</td>
					<td>9</td>
					<td>9</td>
					<td>15</td>
					<td>21</td>
					<td>27</td>
					<td>...99</td>
				</tr>
				<tr>
					<td>5</td>
					<td>10</td>
					<td>25</td>
					<td style="background-color:lightgray">...15</td>
					<td>25</td>
					<td>35</td>
					<td>45</td>
					<td>...95</td>
				</tr>
				<tr>
					<td>7</td>
					<td>14</td>
					<td>49</td>
					<td style="background-color:lightgray">...21</td>
					<td style="background-color:lightgray">35</td>
					<td>49</td>
					<td>63</td>
					<td>...98</td>
				</tr>
				<tr>
					<td>9</td>
					<td>18</td>
					<td>81</td>
					<td style="background-color:lightgray">...27</td>
					<td style="background-color:lightgray">45</td>
					<td style="background-color:lightgray">63</td>
					<td>81</td>
					<td>99</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td class="title">Table 1</td>
	</tr>
</table>

<p>A common solution is to have an array of elements indexed from 1 to <em>n</em>, marking 1 for removal, then generating multiples from 2 to the square root of <em>n</em>, beginning each sequence with the square of its index and marking these for removal too, and finally printing all unmarked values. Instead the algorithm can be conceived in terms of operations on ordered sets.</p>

<p>In Listing 4 (Eratosthenes Sieve) the template parameter <code>HI</code> is the limit value, <code>N</code> is the current sieving multiple beginning at 3 and incrementing by 2 for odd intervals. <code>O</code> is the output list which will be successively sieved; it begins as a list of a fixed value of 2 followed by the sequence of odd numbers up to and including the limit value. Whilst the square of the multiple i.e. <code>LO = N * N</code> is less than or equal to the <code>HI</code> boundary every other odd multiple <code>N + N</code> is sieved from the output list.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
â€¦
template&lt; int HI, int N = 3
, class O = i&lt; 2, seq&lt; 3, HI, 2 &gt; &gt;
, int LO = N * N &gt; struct primes
: conditional&lt; LO &lt;= HI
  , primes&lt; HI, N + 2
    , typename O::type::template except&lt;
      seq&lt; LO, HI, N + N &gt; &gt; &gt;
  , O &gt;::type { };

int main( ) {

  /* primes(350)=2,3,5,7,11,13,17,19,23,29,31 *
   * ,37,41,43,47,53,59,61,67,71,73,79,83,89  *
   * ,97,101,103,107,109,113,127,131,137,139  *
   * ,149,151,157,163,167,173,179,181,191,193 *
   * ,197,199,211,223,227,229,233,239,241,251 *
   * ,257,263,269,271,277,281,283,293,307,311 *
   * ,313,317,331,337,347,349                 */
  cout &lt;&lt; &quot;\nprimes(350)=&quot; &lt;&lt; primes&lt;350&gt;( );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<h2>Summary</h2>

<p>In [<a href="#[Weatherhead15]">Weatherhead15</a>] I covered ASCII to integer conversion, roman numerals and palindromes. Each used a variant of the list construct to represent strings. Here it was used to generate combinations with a queue and to sieve sequences by applying set operations. Representative of the way runtime classes are developed the data and methods were encapsulated for reuse. Further ways to experiment with this include implementing other sieves and adding functions to filter and sort.</p>

<h2>Note</h2>

<p>All the code in this article compiles with GCC 4.9.2 and Clang 3.5.2 using <em>-std=c++11</em>. However, your mileage may vary with other compilers. Also whilst a null character should not be displayed in a terminal, some platforms show them as a space.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[SICP96]"></a>[SICP96] Harold Abelson and Gerald Jay Sussman with Julie Sussman. <em>Structure and Interpretation of Computer Programs Second Edition</em> pp.53â€“54, 116, 139â€“145, The MIT Press, 1996.</p>

<p class="bibliomixed"><a id="[Weatherhead15]"></a>[Weatherhead15] Nick Weatherhead. Template Programming Compile Time String Functions, <em>Overload</em> 128, August 2015.</p>

<h2>Further reading</h2>

<p class="bibliomixed">Chris Oldwood. List incomprehension, <em>CVu</em> Volume 26 Issue 2 pp.7â€“8, May 2014.</p>

<p class="bibliomixed">Stuart Golodetz. Functional Programming Using C++ Templates (Part 1), <em>Overload</em> 81, October 2007.</p>

<h2>Acknowledgements</h2>

<p>Iâ€™d like to thank the <em>Overload</em> review team for providing their feedback which enabled me to elevate the content presented in this article.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
