<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joseph Mariadassou on Medium]]></title>
        <description><![CDATA[Stories by Joseph Mariadassou on Medium]]></description>
        <link>https://medium.com/@thesundayprogrammer?source=rss-416d57ec6c81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LjKnnJIUp0NliG7EdhSIjw.jpeg</url>
            <title>Stories by Joseph Mariadassou on Medium</title>
            <link>https://medium.com/@thesundayprogrammer?source=rss-416d57ec6c81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:42:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thesundayprogrammer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[C++ Coroutines Simplified]]></title>
            <link>https://thesundayprogrammer.medium.com/c-coroutines-simplified-05062163fe8a?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/05062163fe8a</guid>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 21:34:53 GMT</pubDate>
            <atom:updated>2026-03-10T21:47:50.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tvt83ebLdXGYMBPn" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This article explains C++ coroutines starting with examples and describing the mechanisms later.</em><br><br><strong>Why yet another introduction to C++ Coroutines</strong><br>Coroutines have been part of C++ since C++20. There are number of tutorial introductions to coroutines, some of which have been listed at the end of the article. While the coroutine concept has been well known the C++ implementation looks rather complicated. It is almost like learning a new natural language. You can start off by learningthe alphabet and then progress to words and grammar and sentences. Or, you can learn a few phrases and then improve your vocabulary and grammar. This article explains C++ coroutines the second way by starting with some examples and then explaining the mechanisms behind it.</p><p>The First Example:</p><pre><br><br> <br>#include &lt;iostream&gt;<br>#include &lt;coroutine&gt;<br>struct MyCoroutine {<br> //elided for later description<br>};<br>MyCoroutine myCoroutineFunction() {<br> std::cout &lt;&lt; “Start of coroutine\n”;<br> co_await std::suspend_always{}; // will pause here<br> std::cout &lt;&lt; “Resume of coroutine\n”;<br>}<br>int main() {<br> auto coro = myCoroutineFunction(); // created suspended<br> coro.resume(); // prints “Start of coroutine”, then suspends at co_await<br> coro.resume(); // prints “Resume of coroutine”<br>}<br> </pre><p>This program (from <a href="https://medium.com/@AlexanderObregon/understanding-c-coroutine-implementation-8e6e5a2c3edd">Obregon</a>) is a simple example of a coroutine. There are a few interesting points that warrant attention. First <em>myCoroutineFunction</em> is declared to return a <em>struct MyCoroutine</em> but there is no return statement. This is because the compiler treats coroutines differently. For a subroutine (aka function) the compiler allocates a stack space that is ‘destroyed’ when the function ends. A coroutine on the other needs to keep the stack frame alive between calls. So this coroutine returns as soon as it is launched without executing the body of the function. The <em>coro.resume()</em> call starts<br>executing the function until it reaches co_await which returns control back to the calling function. The next invocation of <em>coro.resume()</em> invokes the coroutine to continue from where it left earlier. Now how does the compiler know it is a coroutine? A coroutine is one which uses <em>co_await</em>, <em>co_return</em> or <em>co_yield</em> in its body. There are also some restrictions on its<br>return type which we we shall see presently. Notice that we could put <em>co_await</em> inside an infinite loop. But the program will terminate normally as long <em>coro.resume()</em> is called a finite number of times. Consider the value passed to the <em>co_await operator</em>. That value is of <strong><em>awaiter</em></strong> type, also<br> referred to as <strong><em>awaitable</em></strong>. There is a subtle difference which we can overlook for now. There are two built-in structs of <em>awaiter</em> type: <em>suspend_always</em> and <em>suspend_never</em>. The first returns control to the calling function. The latter ignores the <em>co_await </em>and moves on to the next statement in the coroutine.<br><br>Let us now consider how to pass parameters to the function and get values from. For return values, one solution is shared memory<br>as shown in the following changes to code below:</p><pre>MyCoroutine myCoroutineFunction(int init_val, int&amp; return_val) {<br> std::cout &lt;&lt; “Start of coroutine\n”;<br> int k = init_val;<br> for(;;){<br> return_val= k++;<br> co_await std::suspend_always{}; // will pause here<br> std::cout &lt;&lt; “Resume of coroutine\n”;<br> }<br>}<br>int main() {<br> int init = 10;<br> int ret_val;<br> auto coro = myCoroutineFunction(init,ret_val); // created suspended<br> coro.resume(); // prints “Start of coroutine”, <br> // then suspends at co_await<br> std::cout &lt;&lt; retval &lt;&lt; “\n”; // prints &lt;init&gt;<br> coro.resume(); // prints “Resume of coroutine”<br> std::cout &lt;&lt; retval &lt;&lt; “\n”; // prints &lt;init&gt;+1<br>}<br><br></pre><pre>Promise<br>Let us now consider the return type of a coroutine.<br>The return type is any struct that contains a nested definition of <br>promise_type as shown in the code below:<br><br><br>struct MyCoroutine {<br> struct promise_type {<br> MyCoroutine get_return_object() {<br> return MyCoroutine{std::coroutine_handle&lt;promise_type&gt;::from_promise(*this)};<br> }<br> std::suspend_always initial_suspend() noexcept { return {}; } // start suspended<br> std::suspend_always final_suspend() noexcept { return {}; } // keep frame until destroy<br> void unhandled_exception() { std::terminate(); }<br> };<br> std::coroutine_handle&lt;promise_type&gt; h;<br> explicit MyCoroutine(std::coroutine_handle&lt;promise_type&gt; h) : h(h) {}<br> MyCoroutine(MyCoroutine&amp;&amp; other) noexcept : h(other.h) { other.h = {}; }<br> MyCoroutine(const MyCoroutine&amp;) = delete;<br> ~MyCoroutine() { if (h) h.destroy(); }<br> void resume() { if (h &amp;&amp; !h.done()) h.resume(); }<br>};<br></pre><p>This was the struct that was elided earlier. The <em>promise_type</em> requires the following four functions:</p><ol><li><em>get_return_object</em>: described below</li><li><em>initial_suspend</em>: This is the function that gets called when the coroutine call is first made just before the execution of the body of the coroutine, but after the <em>get_return_object</em> is called. In the above code we return <em>suspend_always</em>. Hence control returns to the caller. If we had returned <br> suspend_never execution of the body of the coroutine would continue until the code reaches one of the co_ operators.</li><li><em>final_suspend</em>: This is called if the coroutine completes. In our first example the coroutine terminates and the this function will be called.</li><li><em>unhandled_exception</em>: As the name implies this function is called if the coroutine throws an exception that is not caught.</li></ol><p>Notice that MyCoroutine object is constructed in the call to <em>get_return_object</em>.</p><p><strong>Coroutine Handle</strong><br>Unlike a normal function, the coroutine is expected to retain the stackframe over multiple invocations. Since the stack will be destroyed the stack frame has to be stored in the heap. The compiler makes provisions to store the stackframe on the heap. It provides a pointer like object called the coroutine_handle to the client. This handle is used by the client to resume the coroutine after a <em>co_await</em> or <em>co_yield</em>. When client has no more use for the coroutine instance it frees the resources used by the instance by calling its <em>destroy</em> method as show in the destructor of <em>MyCoroutine</em>. The <em>coroutine_handle</em> is supplied by the C++ runtime in two ways. The <br>first way is through the <em>promise_type</em> as shown in the definition of the <em>promise_type</em> above. An alternate way is in the call to <em>await_suspend</em> in the awaiter object which we shall discuss next.</p><p><strong>Awaiter</strong><br>The awaiter struct implements three functions:</p><ol><li><strong>await_ready</strong>(): The return value is any value that can be converted to bool. It is called as a response to <em>co_await</em>, <em>co_yield</em> or <em>co_return</em>.</li><li><strong>await_suspend</strong>(std::coroutine_handle): This method is called after await_ready returns <em>false</em>. Its return type can be (a) <em>bool</em>, (b)<em>coroutine_handle</em>, or (c ) <em>void</em>. In the first case the coroutine<br> is not suspended if the return value is false. In the second case the function can return any coroutine_handle and that coroutine_handle’s resume() will be resumed. In the last case, the the coroutine is suspended unless coroutine_handle.resume() is called and the coroutine corresponding to the handle is resumed.</li><li><strong>await_resume</strong>(): The return value can be either a void or anything else. <br> If the return value is not void it is treated as the return value of the <em>co_await</em> operator. This function is called just before the coroutine is resumed. An example, adapted from [Obregon], is shown below</li></ol><pre>struct ReturObject {<br> struct promise_type {<br> ReturObject get_return_object() { return {}; }<br><br> std::suspend_never initial_suspend() { return {}; } <br> // Don&#39;t suspend at start<br><br> std::suspend_always final_suspend() noexcept { return {}; } <br> // Suspend at end<br><br> void unhandled_exception() {}<br> void return_void() {} // For coroutines returning void<br> };<br>};</pre><pre>// 2. A simple awaitable to simulate an asynchronous operation (e.g., a delay)<br>struct Awaiter {<br> std::coroutine_handle&lt;&gt; hp_;<br> int val_;<br> bool await_ready() const noexcept { return false; } // Always suspend<br> void await_suspend(std::coroutine_handle&lt;&gt; h) noexcept {<br>  if(hp_);<br>  else hp_ = h;<br> }<br> int await_resume() const noexcept { return val_;}<br>};</pre><pre>// 3. The coroutine function<br>ReturObject counter(Awaiter&amp; a) {<br> for(unsigned int i=0; ; ++i){<br>  int k = co_await a;<br>  std::cout &lt;&lt; “counter: “ &lt;&lt; i+k &lt;&lt; std::endl;<br> }<br>}</pre><pre>int main() {<br> Awaiter a;<br> a.val_=9;<br> counter(a);<br> auto h = a.hp_;<br> for(int i=0; i&lt;10; ++i){<br>  std::cout&lt;&lt; “In main \n”;<br>  h(); //resume coroutine<br>  a.val_++;<br> }<br> h.destroy();<br> return 0;<br>}<br></pre><p><strong>References</strong><br>1. [Obregon] Alexander Obregon, <a href="https://medium.com/@AlexanderObregon/understanding-c-coroutine-implementation-8e6e5a2c3edd">‘Understanding C++ Coroutine Implementation’,</a> Medium, August 18, 2024</p><p>2. [Mazières] David Mazières, ‘<a href="https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html">My tutorial and take on C++20 coroutines</a>’, February 2021,</p><p>3. [Baker] Lewis Baker, ‘Asymetric Transfer’, August 27, 2022, <a href="https://lewissbaker.github.io/">https://lewissbaker.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05062163fe8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large Scale C++: An Executive Summary of Chapter 0]]></title>
            <link>https://thesundayprogrammer.medium.com/large-scale-c-an-executive-summary-of-chapter-0-716cec683a53?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/716cec683a53</guid>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 23:14:26 GMT</pubDate>
            <atom:updated>2026-03-08T13:54:45.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*kBLhIaOZPw71kIn7Uxm9Pg.jpeg" /></figure><p><em>Large Scale C++, meaning over one million LOC at least, requires some discipline to ensure that we get economies of scale. This book by John Lakos addresses some issues in the development and maintenance of large scale C++ source code. Although the ideas presented are worth considering there are few people who are in a position to affect the changes the book advocates.</em></p><p>The book is about organising large volumes of C++ code. The notion of physical design which was first put forth by Lakos in his earlier book is a running theme throughout the first volume. As stated in the book, software design is not independent of the language or tools used to develop the software. Hence this book will not cover how to organize the files for a large website for example.</p><p>The book is split into three volumes:</p><ol><li>Volume I: Process and Architecture</li><li>Volume II: Design and Implementation (Forthcoming)i</li><li>Volume III: Verification and Testing (Forthcoming)</li></ol><p>True to the C/C++ convention the chapters are indexed from zero.</p><h3>Chapter 0: Motivation</h3><p>There are three dimensions to software development: Cost, Time and Functionality/Quality [Functionality and Quality should be two dimensions IMO]. “Quantity changes quality” as Karl Marx stated as the second law of Dialectical Materialism. To enable code reuse we must ensure that code is easily searchable. While good documentation helps, organising the source code helps in reducing dependencies. This improves build and test times.</p><h3>Chapter 1: Compilers, Linkers, and Components</h3><p>Software design depends upon the language and tools that are used to create the software. Hence to design in C++ it is necessary to understand how compilers, linkers and loaders work.</p><h3>Chapter 2: Packaging and Design Rules</h3><p>Usually a component consists of a unique header file and source file combination. Sometimes it may be necessary to break that rule. This chapter discusses the consequences of breaking the rule and when it may be acceptable to do so. Related components are then packaged into a single static library or shared object (in POSIX) or Dynamic Linked Library (in Windows parlance). Dependencies among packages should form a partial order (no cycles). The author claims that packages must be slotted into levels. A package at Level(N) should access directly depend upon only packages at Level(N-1).</p><h3>Chapter 3: Physical Design and Factoring</h3><p>The longest chapter of this volume, the third chapter is essentially where the author makes his case. Most of the chapter is concerned with levelisation: how to organise code such that packages are dependent upon other packages that are just one level below.</p><h3><strong>An Executive Summary of Chapter 0</strong></h3><ul><li>The Goal: Faster, Better, Cheaper!</li></ul><p>There are tree aspects to software engineering: Budget, Schedule and Product. If the product is complex then both budget and time will increase. While one could increase the time to improve product quality and cost, in the commercial world every delay is an opportunity cost. But, every bug is also very expensive to fix after the product is released.</p><ul><li>Application vs. Library Software</li></ul><p>Any organisation developing software applications needs to make modules that are reusable. Otherwise, even in a single application if the application grows to be complex we would have a large amount of code duplication. To achieve good reuse organisations must spend effort to extract reusable modules from existing applications. Every attempt must be made to use existing libraries. Hence the source code must be properly organised. The top-down design methodology will not work well in an organisation that already has a huge code base. To be effective, design should consider existing code base and tools and try to put together applications that are based solely on existing modules. This notion of software tools dictating or at least influencing design is addressed at length in Chapter 2.</p><ul><li>Collaborative vs. Reusable Software</li></ul><p>Often refactoring code within an application makes the code more comprehensible. But breaking up large modules might result in a collection of collaborating components that are not reusable in other applications. This is OK, if the collaborative suite of modules can be used across multiple versions of the application.</p><ul><li>Hierarchically Reusable Software</li></ul><p>Before Object Oriented Programming (OOP) became popular software engineers encouraged the use of layers or rings. Each layer dependent only upon the immediate next layer only. Structured programming mandated keeping data and source code separate. However despite a near reversal of the original practices with OOP, there is a need to layer the software when the source code is large and complex.</p><ul><li>Malleable vs. Stable Software</li></ul><p>Software should be both malleable and stable. Malleable, meaning it can be easily tweaked to address similar problems for which it was first envisaged. ‘Stable’ essentially implies that the software is well understood and tested. Hence any change will require a complete overhaul starting from specification and design to implementation and testing. To overcome this dichotomy OOP recommends the Open-Closed principle; open to extension and closed to change</p><ul><li>The Key Role of Physical Design</li></ul><p>Physical Design:<br> <em>n.</em> The arrangement of source code within files and files within libraries. <br> <em>v.tr.</em> To partition source code among files and libraries<br> Over 60 years ago Peter Drucker claimed that managers spent more time looking for a document than reading it. This is probably true today as well, as despite the fact that computerisation has improved searching, the number of documents is so large that people do spend a lot of time searching. While there are tools that can present source code in ways that are easily searched it is still better to organise the source code such that looking for existing modules and how to use them becomes easy. One such organisational structure is discussed later.</p><ul><li>Physically Uniform Software: The Component</li></ul><p>The need for physical design and heirarchy having been established this chapter deals with how components are organised. <br> A component is defined to be the atomic unit of physical design. In C++ it takes the form of a .h/.cpp pair. Associated with each component is a standalone test driver. Usually there is only one class per component. There are four basic types of classes: <strong>Basic Types</strong> such as Point, DateTime; <strong>Generic Containers</strong> such as Set,List,Vector; <strong>Complex abstractions </strong>such as Graph, Schema; <strong>Facades </strong>such as XmlParser, RegularExpression which puts a simpler face on a collection of other classes. Components are different from classes in that components are physical entities, a collection of files, that can be ported from one platform to another without code change. A platform is a combination of hardware and software used to build the component.</p><ul><li>Quantifying Hierarchical Reuse: An Analogy</li></ul><p>There are many ways to organise folders and files. There is no algorithm that can provide the optimal solution. This is partly because we don’t know which component is more likely to be reused. While we can put a lot of effort in making a component accessible, the fact remains that such effort may be wasted. The subtleties involved will become clearer in later chapters. However two things are important: The software modules must have an acyclic dependency graph and the software must be able to grow while remaining stable as far as existing interfaces are concerned.</p><ul><li>Software Capital</li></ul><p>There is a huge advantage in first-to-market in the software industry. There are so many examples in consumer software. Microsoft understood this better than others. Hence the common wisdom was: Don’t upgrade until Version 3. Hence there is a lot of pressure to get it out rather than get it right. As Fred Brooks pointed out, increasing the number of developers does not always speed up the project, because the more developers there are there is more time spent in communication and decision making. Again a large number of people leads to a lot of internal politics. Unless there is a strong push from those higher-up, developers will rewrite components rather than reuse existing components. Software should be treated as an asset that is depreciated rather than an expense that is consumed. Reusing components will give much credit to the component developer but not much to the user who often has to spend time understanding the code. Getting the balance right between reusing or rewriting is a mixture of hard and soft skills.</p><ul><li>Growing the Investment</li></ul><p>Economies of scale in software development come due to reuse of existing code. If every project is independent of every other project then small organisations can do the job just as well. A piece of software can be considered reusable only if it is actually reused. Both the producer and the consumer must tango. Too often the library writers throw it over the wall, so to speak. The consumer promptly throws it away. But then over-engineering a product to make it reusable is also not desirable. The compromise seems to be to refactor code in the first application before reusing in the second application. Again this is more art than science.</p><ul><li>The Need for Vigilance</li></ul><p>Like anything else as we add more stuff, we get closer to to chaos. The need is thus to ensure that some discipline is maintained. Of course we can either ensure that the discipline is maintained throughout the project or ensure that standards are adhered to when the project reaches completion. This is because a large amount of software is just thrown away because, the requirements have changed or new requirements come up that change the entire architecture or the requirements are reduced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716cec683a53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterative Versions of Recursive Functions in C++]]></title>
            <link>https://thesundayprogrammer.medium.com/iterative-versions-of-recursive-functions-in-c-1deecf2f9d25?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/1deecf2f9d25</guid>
            <category><![CDATA[cps]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 07:30:56 GMT</pubDate>
            <atom:updated>2023-07-04T01:06:51.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vfr_8Ra1aoXzYVYb" /><figcaption>Photo by <a href="https://unsplash.com/@bildflickan?utm_source=medium&amp;utm_medium=referral">Zarah V. Windh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is much more easy to come up of recursive algorithms for many problems. The only catch is that recursion uses stack memory which is in short supply while iterative versions use a list accessed in a last-in-first-out manner. Here we will see three algorithms namely, the factorial, the depth of a binary tree and the generation of all n-choose-k combinations of a set.</p><h3>Factorial</h3><p>The factorial of number can be defined recursively as:</p><pre>f(0) = 1<br>f(n) = n* f(n-1)</pre><p>This allows a direct translation to the following code:</p><pre>int factorial(int n) {<br>  if (n &gt; 1) {<br>    // Recursive case<br>    return n * factorial(n - 1);<br>  } else {<br>    // Base case<br>    return 1;<br>  }<br>}</pre><p>Converting it to an iterative function is pretty simple. However even the recursive function when compiled with GNU C++ compiler produces an iterative code as the following assembler output shows.</p><pre>_Z9factoriali:<br>.LFB0:<br> endbr64<br> movl $1, %eax<br> cmpl $1, %edi<br> jle .L4<br>.L3:<br> movl %edi, %edx<br> subl $1, %edi<br> imull %edx, %eax<br> cmpl $1, %edi<br> jne .L3<br> ret  ;; redundant code<br>.L4:<br> ret</pre><p>Thus there may not be a need to actively convert a recursive function to an iterative function especially if the function is tail recursive. Many languages support tail calls where, if the last statement is a call to another function then there is a jump not a call, thereby preventing the stack from growing. C++ cannot do that, partly because destructors and finalisers are meant to called just before the function returns.</p><h3>Depth of Binary Tree</h3><p>Consider the function to compute the depth of a binary tree. The recursive version is reproduced below:</p><pre>int recursive_depth(Node* root){<br>  if (root ==nullptr) return 0;<br>  else {<br>      int dleft = recursive_depth(root-&gt;left);<br>      int dright = recursive_depth(root-&gt;right);<br>      return 1 + std::max(dleft,dright);<br>  }<br>}</pre><p>The assembler language output as shown below indicates that much like the C++ code the function is called twice recursively.</p><pre>_Z15recursive_depthP4Node:<br>.LFB6:<br> endbr64<br> testq %rdi, %rdi<br> je .L6<br> pushq %rbp<br> pushq %rbx<br> movq %rdi, %rbx<br> subq $8, %rsp<br> movq (%rdi), %rdi<br> call _Z15recursive_depthP4Node<br> movq 8(%rbx), %rdi<br> movl %eax, %ebp<br> call _Z15recursive_depthP4Node<br> leal 1(%rbp), %ecx<br> movl %eax, %edx<br> leal 1(%rax), %eax<br> cmpl %edx, %ebp<br> cmovg %ecx, %eax<br> addq $8, %rsp<br> popq %rbx<br> popq %rbp<br> ret<br>.L6:<br> xorl %eax, %eax<br> ret</pre><p>One way to convert it to an iterative function is to convert it a Continuation Passing Style (CPS). Translating the Ocaml version by <a href="https://stackoverflow.com/questions/9323036/tail-recursive-function-to-find-depth-of-a-tree-in-ocaml">Gasche</a> we get the following C++ code.</p><pre>typedef std::function&lt;int(int)&gt; call_back;<br>int cps_depth( Node* root, call_back cps){<br><br>  if(root==nullptr) return cps(0);<br>  else return cps_depth(root-&gt;left,[&amp;] (int dleft) {<br>                        return cps_depth(root-&gt;right, [&amp;] (int dright){<br>                        return cps(1 + std::max(dleft,dright));<br>                        });});<br>}<br>int depth(Node* root){<br>  return cps_depth(root, [](int k){return k;});<br>}</pre><p>However despite being tail recursive the C++ compiler cannot translate it to an iterative function as the assembled output, not shown, indicates. The way to convert a recursive function to CPS, usually, is to use a CPS function that takes the return value of the recursive function as the input parameter and then to add the rest of the original function as the code for the CPS function. It is important that the recursive function uses the CPS function before returning at every instance.</p><p>Following Gasche, we can now convert the above code to two mutually recursive functions that are actually tail calls.</p><pre>enum class item_type { tree, height};<br>struct item {<br>  item_type type;<br> union { Tree* root; unsigned height; };<br> item(Tree* r):type(item_type::tree)<br>    {root=r;}<br> item(unsigned h):type(item_type::height)<br>    {height=h;}<br>};<br>static int height_aux(Tree *root, stack&lt;item&gt;&amp; items){<br>    if(root)<br>    {<br>      item it(root-&gt;right);<br>      items.push(it);<br>      return height_aux(root-&gt;left,items);<br>    } else {<br>      return eval(items, 0);<br>    }<br>  }<br>  static int eval(stack&lt;items&gt;, unsigned depth){<br>    if(items.empty()){<br>      return depth;<br>    }else{<br> <br>      item cur = items.top();<br>      items.pop();<br>      switch (cur.type)<br>      {<br>        case item_type::tree:<br>          {<br>            item next(depth);<br>            items.push(next);<br>            return height_aux(cur.root, items);<br>          }<br>        case item_type::height:<br>          {<br>            return eval(items,  1 + std::max(depth, cur.height));<br>          }<br>      }<br>    }<br> <br>  }<br>static unsigned height(Tree* root){<br>    stack&lt;item&gt; items;<br>    return height_aux(root,items);<br>}</pre><p>Let’s decode what is happening here. Let’s look at the return call of the CPS version again.</p><pre>return cps_depth(root-&gt;left,[&amp;] (int dleft) {<br>                        return cps_depth(root-&gt;right, [&amp;] (int dright){<br>                        return cps(1 + std::max(dleft,dright));<br>                        });});</pre><p>The second or inner call to cps_depth requires the value of root-&gt;right and nothing else. The subsequent call to cps needs only the value of dleft, which becomes available only when the outer function is called. Hence we need a union that indicates which of the two values is required.</p><p>Combining <em>eval</em> and <em>height_aux</em> into a single iterative function is not too difficult as shown below</p><pre>static int height(Tree *root){<br>  enum class item_type { tree, height};<br>  struct item {<br>    item_type type;<br>    union {<br>      Tree* root;<br>      unsigned height;<br>    };<br>    item(Tree* r):type(item_type::tree)<br>    {root=r;}<br>    item(unsigned h):type(item_type::height)<br>    {height=h;}<br> <br>  };<br>    bool go_on=true;<br>    unsigned depth = 0;<br>    std::stack&lt;item&gt; items;<br>    while (go_on) {<br> <br>      if (root) {<br>        item it(root-&gt;right);<br>        items.push(it);<br>        root = root-&gt;left;<br>      } else {<br>        go_on=false;<br>        depth=0;<br>        while (!items.empty()&amp;&amp; !go_on) {<br>          item cur = items.top();<br>          items.pop();<br>          switch (cur.type) {<br>            case item_type::tree: {<br>                item next(depth);<br>                items.push(next);<br>                root = cur.root;<br>                go_on = true;<br>              }<br>            break;<br>            case item_type::height: {<br>                  depth = 1 + std::max(depth, cur.height);<br>                 }<br>             break;<br>          }<br>        }<br>      }<br>    }<br>    return depth;<br>  }</pre><h3>Generate All Combinations</h3><p>Consider the problem of generating all k-combinations of set containing ’n’ elements.</p><pre>void print(const vector&lt;int&gt;&amp; nums, ostream&amp; fout)<br>{<br>    for (auto&amp; a : nums) { fout &lt;&lt; a &lt;&lt; &#39; &#39;; }<br>    fout &lt;&lt; endl;<br>}<br>void combo(vector&lt;int&gt;&amp; nums, int n, int k, vector&lt;int&gt;&amp; result) <br>{<br>    if ( k == 0 ) {<br>       print(result,cout); <br>    }<br>    else if (n == k){<br>            result.insert(result.end(),nums.begin(),nums.begin()+k);<br>           print(result,cout);<br>            result.erase(result.end()-k,result.end());<br>    } else {<br>            result.push_back(nums[0]);<br>            //include num[0] and reduce n<br>            swap(nums[0],nums[n-1]);<br>            combo(nums,n-1,k-1,result);<br>            result.pop_back();<br>            //exclude old num[0]           <br>            combo(nums,n-1,k,result);<br>            swap(nums[0],nums[n-1]);<br>    }<br>}<br>void doCombo(vector&lt;int&gt;&amp; nums, int n, int k){<br>  vector&lt;int&gt; result;<br>  combo(nums,n,k,result);<br>}</pre><p>Notice that result is empty initially and in the course of the computation, the ‘result’ will be the same at the start and end of the function in all instances of the call. Needless to say, the compiler does not automatically convert it an iterative function. Using the same technique as before let us generate the CPS version is shown below:</p><pre>typedef std::function&lt;void()&gt; callback;<br>void combo_cps(vector&lt;int&gt;&amp; nums, int n, int k,<br>  vector&lt;int&gt;&amp; result, callback cps){<br>    if ( k == 0 ) {<br>        print(result,cout); <br>        cps();<br>    } else if (n == k){<br>        result.insert(result.end(),nums.begin(),nums.begin()+k);<br>        print(result,cout);<br>        result.erase(result.end()-k,result.end());<br>        cps();<br>    } else {<br>        result.push_back(nums[0]);<br>        //include num[0] <br>        swap(nums[0],nums[n-1]);<br>        combo_cps(nums,n-1,k-1,result, <br>                  [&amp;](){<br>                      result.pop_back();<br>                      //exclude old num[0]            <br>                      combo_cps(nums,n-1,k,result, [&amp;]()<br>                                {<br>                                    swap(nums[0],nums[n-1]);<br>                                    cps();<br>                                });<br>                  });<br>    }<br><br>}<br>void combo(vector&lt;int&gt;&amp; nums, int n, int k){<br>   combo_cps(nums,n,k,[](){}):<br>}</pre><p>(On a personal note: I made the rookie mistake of not calling <em>cps</em> before returning and took me a while to fix the issue).</p><p>To convert the above CPS version to an iterative version we need to track two values, n and k and the state which is whether num[0] is included or excluded. The result is shown below:</p><pre>struct iter{<br>  int n;<br>  int k;<br>  enum { include, exclude, none } state;<br>  <br>};<br><br>void combo_iter(vector&lt;int&gt;&amp; nums, int n, int k){<br>    vector&lt;int&gt; result;<br>    vector&lt;iter&gt; items;<br>    iter it{0,0,iter::none};<br>    items.push_back(it);<br>    for(;;){<br>        while(!(k==0 || k==n)){<br>            result.push_back(nums[0]);<br>            swap(nums[0],nums[n-1]);<br>            iter it{n-1,k-1,iter::include};<br>            items.push_back(it);<br>            --n;<br>            --k;<br>        }<br><br>    if ( k == 0 ) {<br>        print(result,cout); <br>    } else if (n == k){<br>        result.insert(result.end(),nums.begin(),nums.begin()+k);<br>        print(result,cout);<br>        result.erase(result.end()-k,result.end());<br>    } <br>        bool go_on = true;<br>        while(go_on){<br>            iter it = items.back();<br>            items.pop_back();<br>            switch (it.state){<br>                case iter::exclude:<br>                     swap(nums[0],nums[n]);<br>                    break;<br>                case iter::include:<br>                    result.pop_back();<br>                    it = iter{it.n,it.k+1,iter::exclude};<br>                    items.emplace_back(it);<br>                    n=it.n;<br>                    k= it.k;<br>                    go_on = false;<br>                    break;<br>                case iter::none:<br>                    return;<br>                    break;<br>            }<br>        }<br>    }<br>}</pre><p>Notice that the structure of the code is almost the same as for the tree-depth problem. To include <em>num</em>[0] we decrease <em>k</em> and add <em>num</em>[0] to the <em>result</em>. To exclude <em>num</em>[0] we revert to the old value of <em>k</em> and pop the top value from the <em>result</em>. Notice that the switch statement is executed only after at least one whole <em>result</em> is computed.</p><p><strong>Footnote:</strong></p><p>Notice that instead of passing vector <em>nums</em> we could use a <em>const_iterator</em> and thereby get rid of all the swaps. In fact if <em>nums</em> is a vector or array we could use a pointer to the first element of the vector.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1deecf2f9d25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Racism: Has the Pendulum Swung Too Far on the Other Side? — Australian Context]]></title>
            <link>https://thesundayprogrammer.medium.com/racism-has-the-pendulum-swung-too-far-on-the-other-side-australian-context-e674cc0ebb5a?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/e674cc0ebb5a</guid>
            <category><![CDATA[australia]]></category>
            <category><![CDATA[aboriginal]]></category>
            <category><![CDATA[racism]]></category>
            <category><![CDATA[the-voice]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 02:31:08 GMT</pubDate>
            <atom:updated>2023-05-25T02:20:14.980Z</atom:updated>
            <content:encoded><![CDATA[<p>Racism: Has the Pendulum Swung Too Far on the Other Side? — Australian Context</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_YRsJn-957Z58VQO" /><figcaption>Photo by <a href="https://unsplash.com/de/@photoholgic?utm_source=medium&amp;utm_medium=referral">Photoholgic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Australia is going to a referendum later this year on what is commonly referred to as The Voice. The referendum is held to amend the constitution to add a clause to the preamble. If passed separate bodies known as the Voice representing (only) the Indigenous people, also known as Aboriginals and Torres Strait Islanders, will advice the government at all levels: local (municipal), state and national. Currently support for this constitutional reform stands at 58% (<a href="https://www.smh.com.au/politics/federal/one-in-10-say-they-re-unlikely-to-vote-in-voice-referendum-rpm-poll-20230417-p5d11c.html">source</a>). It has come down marginally from 64%.</p><p>One thing going for the NO campaign is that very few referendums pass. But they have to address the stigma of being racist. In general those who support the proposal are progressive on the social axis even if they are more right wing on the economic axis. Hence except for the Murdoch press, the rest of the press are by and large, For the proposal even if they feign impartiality, with ABC, the public broadcaster, leading the Yes campaign despite their claims to contrary. Radio National had an interview with Branaby Joyce, a senior federal politician, belonging to the Nationals party on April 18. The character assassination was terrible. “The witness is not on trial, Your Honour.”</p><p>Let’s recall a brief history of what led to this proposal. “It wasn’t until 1984 that Indigenous people were finally treated like other voters and required to enrol and vote at elections.” (<a href="https://www.nma.gov.au/defining-moments/resources/indigenous-australians-right-to-vote">source</a>). In fact they were not counted in the national census. Following a constitutional amendment in 1967, the Indigeneous people were first counted in population census in 1971 (<a href="https://www.nma.gov.au/defining-moments/resources/first-nations-peoples-census">source</a>). Again the land was considered “terra nullius.” In other words the land claimed by white settlers belonged to no one. In 1992 the High Court (the highest constitutional court) overthrew this assumption. So now we have a regime where the Indigenous people are consulted before unclaimed land is appropriated for other purposes.</p><p>Thus the Indigenous people have been handicapped at birth. They are over represented in almost every negative measure such as the proportion of people incarcerated, low life expectancy, school dropouts etc. The government is trying to redress the situation but nothing much is changing. There are many successful indigenous people but much like Afro-Americans they are found mostly in sports and arts including TV presenters. There is no equivalent of Neil de Grasse Tyson in Australia.</p><p>But despite all the programs for the Indigenous people their life is not improving. The claim is that throwing money at the issue does not fix the issue. Hence the Indigenous people must be at the forefront of all the decision making that affects them. Fair enough.</p><p>However having The Voice advise the parliament and the executive would mean that they can deal with any subject. Admittedly their advice can be rejected but their advice must be given due consideration. Imagine a situation where there is a flood in some place. The government decides to build a temporary accommodation in some high ground. For now, the government makes every effort not to encroach on land considered sacred. But the Voice will supersede that. They can force the government to wait until they carry out their own investigation and then give advice. For that matter they can object to defense procurement.</p><p>“…any Voice member that strayed into matters like the Reserve Bank and Defence procurement would be likely [to] face a short tenure.” (<a href="https://www.abc.net.au/news/2023-04-16/voice-constitution-two-words-executive-government-albanese/102217212">source</a>) So now we have to depend on the thoughtfulness of the electors of the Voice to ensure that they don’t stray into such matters. Who are they kidding? George W Bush and John Howard got re-elected after taking their nations to a war in Iraq despite massive protests and the majority of the people being against it at that time. What prevents a bloody minded Indigenous politician stalling much need government action. Very few of Indigenous people will know what is going on and even fewer will care.</p><p>All that The Voice will do is to have yet another level of bureaucracy that a few elite members of the Indigenous community will enjoy. We must reduce references to race in the constitution and not use existing references as an excuse to have even more race based articles in the document.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e674cc0ebb5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Western Media Bias: An Indian Perspective]]></title>
            <link>https://thesundayprogrammer.medium.com/western-media-bias-an-indian-perspective-4376c5718867?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/4376c5718867</guid>
            <category><![CDATA[manufacturing-consent]]></category>
            <category><![CDATA[media-bias]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 19:50:00 GMT</pubDate>
            <atom:updated>2025-07-16T09:48:58.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ViU2GgSOiBNevnsd" /><figcaption>Photo by <a href="https://unsplash.com/@adityn?utm_source=medium&amp;utm_medium=referral">Adityan Ramkumar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The western media has always been biased against India. In the early nineties, Mani Shankar Aiyar wrote an article detailing why no amount of sucking up to the US will help India, because the prime concern of the US is containing Soviet Union and Iran, and Pakistan is strategically located to help the US in the regard. The western media has always deferred to the US government in such foreign policy matters. Sure enough when the geo-political situation changed and the US decided to take India’s help, the news about India became very positive. The latest BBC two part program criticising the Modi government in India is essentially the western media dropping hints to the Modi government that they are not toeing the line with regards to the Ukraine war. I am no fan of Modi but the timing of the program is rather suspicious.</p><p>For a first hand instance regarding the utter bias of the main stream western media, I can cite the Australian Broadcasting Corporation’s Foreign Correspondent’s report on Kashmir in 1995/96.</p><p>The ABC portrayed India as an occupying army that was hell bent on tormenting the local Kashmiris. That there were excesses was not in doubt but to swing the other side and say the Kashmiri insurgents were a bunch of peace loving soldiers fighting for basic human rights is far from the truth. I lived closed to New Delhi when there was an exodus of Hindus from Kashmir coming to Delhi and neighbouring states. The insurgents went to Hindu homes and asked them to vacate their ancestral homes. If not they would be killed. The government could not help because there was a complete breakdown of law and order. Policemen, judges and public prosecutors who tried to arrest such those responsible were either killed themselves or in some cases their family members. The daughter of Mufti Mohammed Sayeed was kidnapped and the insurgents demanded the release of convicted criminals as the ransom. Mufti was then a cabinet minister in the central government and the government agreed. For all their Islamic brotherhood rhetoric the insurgents had no compunction in threatening to take the life of one of their own kin, a young doctor in this case. There were other instances of kidnapping too that the ABC failed to mention. In another “minor” instance a State Bank of India employee was found dead a few months after he started working in Kashmir. There was no official confirmation that he was killed. But the government of India usually downplays such incidents because it will lead to anti-Muslim riots in other parts of India. That attitude partly explains the rise of the Hindu nationalist party which claims that the then Congress government was engaging in politics of appeasement.</p><p>A few years later 9/11 happened. At that time Al Queda claimed innocence. But the western media taking cue from the US, blamed it on Osama bin Laden. Noam Chomsky claims that bin Laden would not have been convicted in any criminal court in the USA given the evidence available at that time. Even now the only evidence we have is, bin Laden gloating over the fall of the twin towers. In all probability the real conspirators behind the scene have not been caught. Bin Laden has been killed but Al Queda can thank the western media for making him a brilliant jihadi martyr in the minds of so many Muslims worldwide.</p><p>On a personal note, this article started as a response to Caitlin Jonhstone’s article: <a href="https://medium.com/@caityjohnstone/us-power-alliance-says-its-coordinating-an-information-war-against-china-3f1b8732b468?source=user_profile---------1----------------------------">US Power Alliance Says It’s Coordinating An “Information War” Against China</a>. My initial thought was, ‘Tell me something I don’t already know Caitlin.’ I guess her main contribution is that they they are not even trying to hide the fact that they are manufacturing consent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4376c5718867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CoPilot does it right for Python but not C++]]></title>
            <link>https://thesundayprogrammer.medium.com/copilot-does-it-right-for-python-but-not-c-bb03bc1df077?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb03bc1df077</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[co-pilot]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 03:41:31 GMT</pubDate>
            <atom:updated>2023-02-08T03:41:31.392Z</atom:updated>
            <content:encoded><![CDATA[<p>CoPilot does it right for Python but not C++</p><p>Here is the problem I wanted CoPilot to solve:</p><blockquote>Represent a positive number as a sum of fibonacci numbers.</blockquote><p>Python Solution</p><pre>def fibsum (n):<br>    &quot;&quot;&quot;<br>    Return a list of fibonacci numbers that sum to n.<br>    &quot;&quot;&quot;<br>    fib = [1, 1]<br>    while fib[-1] &lt; n:<br>        fib.append(fib[-1] + fib[-2])<br>    fib.reverse()<br>    result = []<br>    for f in fib:<br>        if n &gt;= f:<br>            result.append(f)<br>            n -= f<br>    return result</pre><p>The C++ code is obviously wrong:</p><pre>/*<br>Represent a positive number as a sum of fibonacci numbers.<br>*/<br>vector&lt;int&gt; fibSum(int n) {<br>    vector&lt;int&gt; fibs;<br>    int a = 1, b = 1;<br>    while (n &gt; 0) {<br>        if (n &gt;= b) {<br>            fibs.push_back(b);<br>            n -= b;<br>        }<br>        int c = a + b;<br>        a = b;<br>        b = c;<br>    }<br>    return fibs;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb03bc1df077" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CoPilot is No Threat to a Good Programmer]]></title>
            <link>https://thesundayprogrammer.medium.com/copilot-is-no-threat-to-a-good-programmer-5a9d20e224da?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a9d20e224da</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[irr]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 04:26:24 GMT</pubDate>
            <atom:updated>2023-02-07T04:41:14.171Z</atom:updated>
            <content:encoded><![CDATA[<p>CoPilot is No Threat to a Good Programmer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mLaV09rOJeoRhAy7" /><figcaption>Photo by <a href="https://unsplash.com/@johnschno?utm_source=medium&amp;utm_medium=referral">John Schnobrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Prerequisite: Some knowledge of Python and C++</blockquote><p>A lot is being said about ChatGPT. But the older kid around the block is Github CoPilot. I asked CoPilot to compute the internal rate of return using the comment:<br><em>Compute the internal rate of return of a series of cash flows </em><strong><em>(irr)</em></strong></p><p>The last phrase ‘(irr)’ was generated by VSCode with the help of CoPilot (CP), I presume. That by itself was pretty impressive. I got CoPilot to produce C++ and Python code. It generated three different C++ functions on the three days; only one of which was is correct as shown below:</p><pre>/*<br>Compute the net present value of a series of cash flows npv<br>*/<br>double npv(double *cashflows, int n, double r)<br>{<br>    double npv = 0.0;<br>    double r1 = 1.0;<br>    for (int i = 0; i &lt; n; i++)<br>    {<br>        npv += cashflows[i] / r1;<br>        r1 = r1 * (1.0 + r);<br>    }<br>    return npv;<br>}<br>/*<br>Compute the internal rate of return of a series of cash flows  (irr)<br>*/<br>double irr(double *cashflows, int n)<br>{<br>    double x0, x1, f0, f1, df;<br>    int i;<br>    x0 = 0.0;<br>    f0 = 0.0;<br>    for (i = 0; i &lt; n; i++) {<br>        f0 += cashflows[i] ;<br>    }<br>    x1 = 0.1;<br>    f1 = npv(cashflows, n, x1  );<br>    while (fabs(f1) &gt; 1.0e-6)<br>    {<br>        df = (f1 - f0) / (x1 - x0);<br>        x0 = x1;<br>        f0 = f1;<br>        x1 = x0 - f0 / df;<br>        f1 = npv(cashflows, n, x1  );<br>    }<br>    return x1;<br>}</pre><p>I got CoPilot to generate <em>npv </em>and refactored <em>irr </em>to use it. Of the two other wrong codes one of them is obviously wrong. Here is the version CoPilot generated</p><pre>/*<br> Compute the net present value of a series of cash flows<br>*/<br>double npv(std::vector&lt;double&gt;&amp; cashFlows, double discountRate) {<br>    double npv = 0.0;<br>    for (int i = 0; i &lt; cashFlows.size(); i++) {<br>        npv += cashFlows[i] / std::pow(1 + discountRate, i);<br>    }<br>    return npv;<br>}<br>/*<br>Compute the internal rate of return of a series of cash flows  (irr)<br>*/<br>double irr(std::vector&lt;double&gt;&amp; cashFlows) {<br>    double guess = 0.1;<br>    double npv = 0.0;<br>    double epsilon = 0.0000001;<br>    while (true) {<br>        npv = 0.0;<br>        for (int i = 0; i &lt; cashFlows.size(); i++) {<br>            npv += cashFlows[i] / std::pow(1 + guess, i);<br>        }<br>        if (std::abs(npv) &lt; epsilon) {<br>            break;<br>        }<br>        guess += 0.0001;<br>    }<br>    return guess;<br>}</pre><p>Notice th<em>at npv</em> could be optimised to the previous version. At least the function is a starting point in that it can be tweaked to compute a value most of the time. The third version is one I could not make sense of:</p><pre>/*<br>Compute the internal rate of return of a series of cash flows  (irr)<br>*/<br>double irr(const std::vector&lt;double&gt;&amp; cashflows, double guess)<br>{<br>    double x1 = guess;<br>    double x0 = 0.0;<br>    double f1 = 0.0;<br>    double f0 = 0.0;<br>    int max_iter = 100;<br>    int iter = 0;<br>    double eps = 1e-6;<br>    double dx = 1e-6;<br>    double df = 0.0;<br>    double f = 0.0;<br>    double x = 0.0;<br>    int i = 0;<br>    int n = cashflows.size();<br>    while (iter &lt; max_iter)<br>    {<br>        f1 = 0.0;<br>        f0 = 0.0;<br>        for (i = 0; i &lt; n; i++)<br>        {<br>            f1 += cashflows[i] / pow(1.0 + x1, i);<br>            f0 += cashflows[i] / pow(1.0 + x0, i);<br>        }<br>        df = (f1 - f0) / dx;<br>        f = f1 + (x1 - x0) * f1 / df;<br>        x = x1 - f1 / df;<br>        if (fabs(f) &lt; eps)<br>        {<br>            break;<br>        }<br>        x0 = x1;<br>        x1 = x;<br>        iter++;<br>    }<br>    return x;<br>}<br></pre><p>The first Python version was bad in that it usually will not converge:</p><pre>&quot;&quot;&quot;<br> Compute the net present value of a series of cash flows<br> &quot;&quot;&quot;<br>def npv(cashflows, rate):<br>     npv = 0.0<br>     for i in range(len(cashflows)):<br>         npv += cashflows[i]/(1+rate)**i<br>     return npv<br><br>&quot;&quot;&quot;<br>Compute the internal rate of return of a series of cash flows  (irr)<br>&quot;&quot;&quot;<br>def irr(cashflows):<br>    rate = 1.0/8<br>    def redeem(rate):<br>        return npv(cashflows, rate)<br>    redeem_value = redeem(rate)<br>    increment = 1.0/4096.0<br><br>    print(&quot;r=&quot;, rate)<br>    print(&quot;i=&quot;, increment)<br>    while abs(redeem_value) &gt; 0.01:<br>        if redeem_value &lt; 0 :<br>            rate = rate + increment<br>        else:<br>            rate = rate - increment<br>        redeem_value = redeem(rate)<br>        #print(&quot;r=&quot;, rate)<br>    return rate</pre><p>The second version though is a perfect one-liner:</p><pre>def irr(cashflows):<br>    return np.irr(cashflows)</pre><p>I was not aware Numpy had such a built-in function.</p><p>In sum, CoPilot does produce good code sometimes. But it is not reliable</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a9d20e224da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Cloud Computing]]></title>
            <link>https://thesundayprogrammer.medium.com/an-introduction-to-cloud-computing-e832a57db49d?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/e832a57db49d</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 00:51:15 GMT</pubDate>
            <atom:updated>2022-11-15T01:26:54.183Z</atom:updated>
            <content:encoded><![CDATA[<p>An Intelligent User’s Guide to Cloud Computing on Amazon</p><blockquote>Amazon Web Services (AWS) is a cloud computing service provider. They pioneered the use of public cloud in this millennium. Many otherwise savvy computer users are not aware of what it actually does. This blog addresses those users to help them decide if they really need cloud computing by describing some of the services AWS provides.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tX8uEi_s9Hx_MG_Dq9AsHw.png" /></figure><pre><strong>What is Cloud Computing?</strong><br>Consider a computing service such as a web server that is perhaps accessed heavily during business hours and accessed lightly off-business hours. Assigning a computer that can handle the heavy load during the day is wasteful because it is idle at least 100 hours a week. A video streaming service like Netflix is used less during business hours. So we would like to use a system that can increase or decrease the computing power depending upon the usage. This is the service that Cloud Computing provides: a way to increase or decrease the use of computing resources depending upon the need. <br><br><br>The technology behind cloud computing is based on the concept of  a <strong>Virtual Machine</strong> (VM), an idea that can be traced back to the seventies, at least. It is a piece of software that appears like a complete computer from a remote user&#39;s perspective. A physical machine can host more than one VM. For example if there are ten physical machines each hosting ten VMs then from the remote user&#39;s perspective there are one hundred independent computing devices. Amazon pioneered the use of sharing physical machines among disparate customers by assigning every customer their own VM. Two customers could be running VMs on the same hardware blissfully unaware of the existence of each other. <br><br>Each VM is allotted a certain number of CPUs and memory limited by the underlying hardware. When the demand for computing resource increases, the customer can ask for more VMs with the same characteristics as the previous one. This is known as <strong>horizontal scaling</strong>. <strong>Vertical scaling</strong> refers to allocating more resources to the same VM which may mean that the VM may need to be restarted. <br><br>A <strong>private cloud</strong> is a cluster of VMs, often hosted in one or more data centres, that is used exclusively by a single party. A <strong>community cloud</strong> is a cloud that a few organisations share exclusively. For example Amazon runs a cloud service exclusively for US government departments. Amazon also provides private cloud computing services. Their offering is called Outpost. VMware, Microsoft and Ubuntu have similar offerings. The main advantage of a private cloud is that some physical machines can be turned off by moving the few VMs in use to a small number of physical machines.<br><br>That is the history but as is wont with any good technology, cloud computing now has far more use cases. In the rest of the blog I&#39;ll discuss two of the main services that I think can be used by everyone. <em>A good engineer does not ask: Of what use is it? The more pertinent question is: To what use can I put it to?</em> Hope you can come up with uses that the rest of of the world has not thought about before.<br><br><strong>Storage and Computing</strong><br>Computers have always provided facilities for data storage and computing services whether it is a word processor or a spreadsheet. The advantage of the cloud is that you can use small quantities. Let us say you have a collection of pictures or documents. Some have hundreds of gigabytes of data but most of us have much less. But we all land up getting a terabytes of hard disk and we  have to label each external hard disk either by date or by topic. Using online storage we don&#39;t have buy all that hard disk upfront. We can gradually rent more hard disk space. Most of the time we don&#39;t access old files although we would like to retain them should we need them. With online storage, data can be stored in slow devices so that you pay for the access and very little for the storage. The other advantage of online storage is reliability. Most businesses have more than one backup. Online storage providers usually backup data in different physical locations. <br><br>While the need for online storage is thus clear, what is the need for online computing service from the perspective of a small business or a private individual? Interactive applications like a word-processor or spreadsheet is better done on the local machine, although Citrix came up with idea of running MS Office on the server to optimise the number of licenses required. It is not very popular though. However service applications like payroll and inventory tracking are usually back end processes that are run periodically with little human interaction. It requires a detailed cost benefit analysis to decide if cloud computing would be viable in such cases. This is where the idea of server-less computing comes into play as we shall see later.<br><br><br><strong>Storage</strong><br>Most people store data as key-value stores. A file has a unique name for that storage device even if the name can be decomposed to folders and file. A file also has content whether it is text file or a spreadsheet. AWS provides two types of key-value stores. The first is called S3 (short for Simple Storage Service). The second is DynamoDB. S3 is used for storing large files up to a few terabytes (currently 5 terabytes) in size. The key is limited to 1024 (utf-8) characters. It is not possible to change a single byte in either the key or value in a key-value store. You need to update the whole key or value. The other key-value store, DynamoDB is meant for storing a large number of small data. The size of key and value put together is 400KB. However it is extremely fast.It is also quite cheap. </pre><pre>Amazon also provides Relational Databases (RDS) such as Oracle, MSSQL, MySQL or Postgres. These are meant for large database applications that need to handle complex queries. Most small applications though are better off using Dynamo. <br><br><strong>Computing</strong><br>As mentioned earlier cloud computing is used mostly because the demand for computing resources varies. There are two type of computing services, the first is the use of explicit VMs as described earlier. The other is the use of server-less computing where a single function is executed without the customer having to provision a VM. AWS provisions the VM on which the function runs. <br><br>Let us consider the use of a VM. Although it is possible to create a single VM, known as an <strong>EC2</strong> instance, it is better to think of it as creating a node in a network of VMs. This network is known as <strong>Virtual Private Cloud</strong> or VPC. Hence creating a bare EC2 instance essentially means adding a node to the default VPC. But for any practical Internet facing application, Amazon advises to create at least two VPC&#39;s one private and the other public. A public VPC is one that can connect to the internet via an internet gateway. The private VPC is the workhorse that talks to the public VPC. In the simplest instance you would create an EC2 instance with a static IP address that is accessible from anywhere on the Internet. This EC2 instance is usually no more than a request forwarding machine. This is to ensure that all requests are vetted and often reformatted before handing over to the back-end on the private VPC. This is to prevent all kinds of malicious attacks. At worst the front end may go down but all the data in the back-end would be safe.<br><br><strong>Serverless computing</strong> on AWS goes by the name <strong>Lambda</strong>, a term used in Functional programming to indicate a nameless function. In AWS it refers to a code that is not hosted on a customer provisioned VM. The advantage is that subject to limits it scales without the user having to do anything explicit. A Lambda function can be written in Python, Javascript, Java, C#, Go etc. The function can be triggered by an explicit HTTP call. It cannot access resources in a user&#39;s private VPC unless it is bound to a VPC. Doing so would mean it can access S3 and Dynamo without leaving the AWS network. Any single application of a Lambda function is restricted to fifteen minutes. If more time is required then either the solution has to be re-architected or an on-demand EC2 instance needs to be use. <br><br><strong>Summary</strong><br>Cloud computing services on AWS consists of two broad categories: Storage and Computing. Storage services include S3 and DynamoDB. There are two types of computing services: Server-based and server-less. In addition to these AWS also provides other services such as queues, notification services and  services for software development and machine learning.<br>S3 is best service to get started with. A <a href="https://thesundayprogrammer.wordpress.com/2022/03/31/simple-storage-service-a-quick-introduction/">previous article</a> showed how the command line can be used to avail the use of S3. The next article in this series will discuss how to use DynamoDB with S3 to store all your favourite songs along with the relevant blurbs.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e832a57db49d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suicide and the Meaning of Life]]></title>
            <link>https://thesundayprogrammer.medium.com/suicide-and-the-meaning-of-life-a03b794e8d30?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03b794e8d30</guid>
            <category><![CDATA[suicide]]></category>
            <category><![CDATA[religion]]></category>
            <category><![CDATA[tolstoy]]></category>
            <category><![CDATA[exitententialism]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Sat, 09 Apr 2022 01:01:00 GMT</pubDate>
            <atom:updated>2022-04-09T01:01:00.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EpAqcMw4kZs26kO7" /><figcaption>Photo by <a href="https://unsplash.com/@jaffrix?utm_source=medium&amp;utm_medium=referral">Syed Fahim Haider</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>On 21 May 1991, <a href="https://en.wikipedia.org/wiki/Thenmozhi_Rajaratnam">Thenmozhi Rajaratnam</a> detonated an RDX explosive-laden belt tucked below her dress. Rajiv Gandh, the former prime minister of India, his assassin and 14 others were killed in the explosion. Thenmozhi was not motivated by religious belief or the promise of 72 virgins in the after-life. Presumably she believed in a cause higher than her own existence. Why are people willing to die for a cause when they know they are going to be forgotten in the years to come?</p><p>Suicide is an enigma that for most of us is hard to explain. Far many more people aged 15–24 commit suicide than there are people dying of domestic violence in Australia and presumably in the rest of the world. Should we concerned about it? Should we give people the right to commit suicide? After all it’s their own life. The state does not tell me how I must spend my money. Why should the state intervene if I want to take my life? I digress.We would like to think that people who are depressed have a wrong view of life. But there is no reason to think that way. The rest of us may be hallucinating and life with all its disappointments may indeed not be worth living. Let’s hope otherwise.</p><p>“For most of us life is a disappointment. Some can’t cope with it” (Bob Carr). Almost anybody who gives serious thought to the question “What is the purpose of life?” comes to the conclusion that life has no purpose and invents ways of giving meaning to life. Existentialism as a philosophy gained prominence in the 19th century and acquired its name in the 20th century. How do people cope with the existentialist angst? Following Tolstoy I would suggest that there are four mechanisms commonly used to deal with it:Ignorance, Epicureanism, Hope and Religion</p><p>Even when you are fully convinced of the absurdity of life, few actually take their own lives. One reason is fear which is the flip side of hope. Death is a one-way street and even people who claim to talk to people in the other world are not too happy to join them. Cowardice thus helps reduce the incidence of suicide. Attempting suicide and failing is a terrible experience especially if people come to know about it. Here I am not interested in suicide per se but in how it is a response to cope with the absurdity of life.</p><p><em>Consider Ignorance</em>. Some people live in such poor economic situations that they spend all their time making a living. This is true not just in under developed countries but in developed countries as well. The capitalist system forces so called better-off people to put in seventy hours a week and few people have the time to ponder over such issues, to smell the roses so to say. In fact people brag about how hard they work even at the cost of seeing their family or participating in the community. Much like the businessman in Saint-Exupery’s novel <em>The Little Prince</em>, who is too busy counting his money that he no time to say Good-bye.</p><p>The weekend ritual of the football game or some other sport gives us some respite from the emptiness of life. A win by our favourite team or player gives us a vicarious thrill as though we have won the match ourselves. Of course like everything else in life there is more disappointment than joy. But the occasional wins make it worth following the team to the point of spending more than a few days wages, in many cases, to watch your favourite team or player play and hopefully win. It also helps in bonding with like minded people. “WE lost” or “WE won”, referring to “our” team, is a common phrase that seems strange only to a few people like me. Gambling is yet another activity that is usually disappointing but gives occasional joy. The thrill of success makes all the failure worth it. Of course that is true of life in general. Sundays at one time used to be day of worship. Even if most church-goers pay little attention to the readings or the sermon there are a few minutes allocated for introspection.</p><p>The other option is <em>Epicureanism</em>. Books like <em>War and Peace</em> and <em>Pride and Prejudice</em> indicate that back then, as now, rich people flutter from party to party. The rest of the time they talk about what happened at the party. Nowadays, due to much better economic conditions, a much higher proportion of the society live for their weekend at the pub or disco. Another favourite pastime is go on a holiday. You spend every free minute researching or planning your next holiday and bore the hell of everybody around recounting the holiday adventures. They are happy to have fun but they are happier to be seen having fun as Sartre might say.</p><p><em>Hopes</em> and dreams are another way to cope with the absurdity of life. People who have some time but not the economic wherewithal to make merry, live with the hope that their life situation will change, “God wants you to be rich. If you are not rich you are not putting enough effort.” That notion is very popular in the USA and the cause for so much disparity between the rich and poor in that country. The less fortunate see the well off having fun (do they really?) and look through a virtual barbed wire hoping that they will one day be on the other side.</p><p>And <em>Religion. </em>When hope in this life fails people take to hope in a better after-life. Even religions that do not subscribe to an omnipotent god, promise some version of the law of karma. This notion of everlasting life in heaven seems irrational. There is no purpose to life on earth as we know it and everlasting life only makes matters worse. There would be no urgency to do anything. Nothing to look forward to. No desire to leave the world a better place than we found it.</p><blockquote><em>If we had but world enough and time<br>Thy coyness dear lady would be no crime</em></blockquote><p>Well Andrew (Marvel), in heaven the coyness of your mistress would indeed be no crime.</p><p>This is not to say that religion is false. It just means that a lot of people are using religion as a substitute for opium as Karl Marx put it. Religion comes in handy in other ways as well. It helps in a bonding that crosses national and racial boundaries. There is a sense of sense of shared values and beliefs.</p><p>Thenmozhi as discussed above may not have been motivated by a formal religion but still believed that sacrificing her life for Tamil Eelam was a worthy cause no matter how many innocent bystanders had to pay with their own lives. Again, when people register to defend their country they are willing to risk their lives in the hope that should they be killed, their sacrifice will help others leave a better life. It is that attitude that gives meaning to life. Without somebody to believe in you and share the joy of your successes, and split the pain of your failures, life it is true, is without purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03b794e8d30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The First Casualty in War: The Truth]]></title>
            <link>https://thesundayprogrammer.medium.com/the-first-casualty-in-war-the-truth-c7d34b2f8ea8?source=rss-416d57ec6c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7d34b2f8ea8</guid>
            <category><![CDATA[putin-ukraine-invasion]]></category>
            <category><![CDATA[isaac-asimov]]></category>
            <category><![CDATA[free-speech]]></category>
            <category><![CDATA[double-standard]]></category>
            <category><![CDATA[afghanistan]]></category>
            <dc:creator><![CDATA[Joseph Mariadassou]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 03:26:47 GMT</pubDate>
            <atom:updated>2022-03-11T03:26:47.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lGae-kdp7bLiLKK9" /><figcaption>Photo by <a href="https://unsplash.com/@artturijalli?utm_source=medium&amp;utm_medium=referral">Artturi Jalli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In December 1999, a plane from Delhi to Ludhiana in Punjab was hijacked and taken to Kandahar in Afghanistan. A few days later, the then Foreign Minister, Advani flew to Kandahar and swapped a terrorist for the passengers in the plane. The West cared little. They continued to do business with the Taliban or at least tried to, knowing full well that the Taliban was complicit in the hijack.</p><p>Two years later, 9/11 took place. USA demanded that Osama bin Laden be extradited. The Taliban demanded evidence that bin Laden was responsible for the incident. After all Western nations would demand as much even if the person demanded to be extradited is a citizen of the country demanding the extradition. But no, Western governments will not heed such requests. “America is exceptional”</p><p>The western media and indeed many ordinary people in the North Atlantic region are quick to paint Putin as a megalomaniac. True, but USA is a nation of megalomaniacs. It is not just the deep state but the average American thinks USA is exceptional. Hats off to the establishment. They have thoroughly manufactured consent. Except for Noam Chomsky, and a few people like him almost nobody has questioned the invasion of Afghanistan. Chomsky claims that based on the evidence available no court in USA would have convicted bin Laden. For all his criticism of USA and Israel, Chomsky still thinks that America has in it some semblance of decency that would prevent such witch hunting. Wishful thinking!</p><p>“We came, we saw, he died” as Hilary Clinton would say of Col. Ghadaffi, laughing on national TV as she said so. But only Putin is evil! Putin is no Hitler. He knows his limitations and would be happy to settle if Ukraine agreed to be a buffer between Russia and NATO. Instead President Zelenskyy is trying to act like a freedom fighter liberating Ukraine from Russia, no matter how many people in his own country die. And Putin is the megalomaniac!</p><p>The Western governments claim that Russia is about to use chemical weapons. But it is the USA that refused to negotiate the mutual dismantling of chemical weapons. Reagan’s trick of upping the ante until Soviet Union collapsed may not work with Russia.</p><p>Western countries claim to have freedom of speech but they are shutting down dissenting voices. RT and Sputnik have been closed. Stan Grant in Australia could well be a paid puppet of the establishment asking a Russian supporter to leave Q&amp;A. And he was a Russia supporter not a Putin crony as Stan made him out to be.</p><p>The Western media claims that Russian people are suffering. Indeed they are gloating about it. What makes common people enjoy that kind of suffering in other countries and then pity them by contributing to charity is something I’ll leave for Jordan Peterson to explain. Sadism? Voyeurism? Who knows? For now, how bad is it that McDonalds and Gucci have left Russia? (Wish they leave Australia, where I live.) As for Mastercard and VISA, yes people in Russia may not be able to subscribe to New York Times. But payment systems will catch up to fill the void left by Mastercard and VISA. In India Rupay, PayTM, etc. are more or less replacing cash and is used for as little as AU$0.50. You can rest assured that Russia will come up with their own payment systems. In fact in Australia, we had EFTPOS long before VISA and Mastercard became popular. We can still use EFTPOS and ‘BPay’ a system of paying bills is still cheaper and available. The only reason I have a VISA card is because, I use it for international transactions which is so few and far between that the $110 annual fee is just not worth it. Note also that Tiktok would have been nipped in the bud by Facebook were Facebook allowed to operate in China. Not saying Tiktok is better or even good. So American companies leaving Russia may not be a bad thing.</p><p>In this context it is well worth reading Isaac Asimov’s short story ‘Mother Earth.’ The rest of the galaxy decides to ostracise the earth. But despite the initial hardship the people from earth decide to be ostracised rather than suck up to the big bullies in the outer galaxy because the rest of the galaxy still needs the earth. Mother Russia may be thinking likewise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7d34b2f8ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>