<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Erlang - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Erlang - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 06 Jun 2026 11:18:06 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/erlang/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ An Overview of Erlang with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Erlang is a functional programming language developed by Ericsson for use in telecom applications. Because they felt that it’s unacceptable for a telecom system to have any significant downtime, Erlang was built to be (among other things): distribut... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-overview-of-erlang-with-examples/</link>
                <guid isPermaLink="false">66c3447cccd54aa295e92ca2</guid>
                
                    <category>
                        <![CDATA[ Erlang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d15740569d1a4ca35d2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Erlang is a functional programming language developed by Ericsson for use in telecom applications. Because they felt that it’s unacceptable for a telecom system to have any significant downtime, Erlang was built to be (among other things):</p>
<ul>
<li>distributed and fault-tolerant <em>(a piece of failing software or hardware should not bring the system down)</em></li>
<li>concurrent <em>(it can spawn many processes, each executing a small and well-defined piece of work, and isolated from one another but able to communicate via messaging)</em></li>
<li>hot-swappable <em>(code can be swapped into the system while it’s running, leading to high availability and minimal system downtime)</em></li>
</ul>
<h3 id="heading-syntax"><strong>Syntax</strong></h3>
<p>Erlang makes heavy use of <strong>recursion</strong>. Since data is immutable in Erlang, the use of <code>while</code> and <code>for</code> loops (where a variable needs to keep changing its value) is not allowed.</p>
<p>Here’s an example of recursion, showing how a function repeatedly strips the first letter from the front of a name and prints it, only stopping when the last letter has been encountered.</p>
<pre><code class="lang-erlang"><span class="hljs-keyword">-module</span><span class="hljs-params">(name)</span>.

<span class="hljs-keyword">-export</span><span class="hljs-params">([print_name/<span class="hljs-number">1</span>])</span>.

<span class="hljs-function"><span class="hljs-title">print_name</span><span class="hljs-params">([RemainingLetter | []])</span> -&gt;</span>
  io:format(<span class="hljs-string">"~c~n"</span>, [RemainingLetter]);
<span class="hljs-function"><span class="hljs-title">print_name</span><span class="hljs-params">([FirstLetter | RestOfName])</span> -&gt;</span>
  io:format(<span class="hljs-string">"~c~n"</span>, [FirstLetter]),
  print_name(RestOfName).
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">&gt; name:print_name("Mike").
M
i
k
e
ok
</code></pre>
<p>There is also a heavy emphasis on <strong>pattern-matching</strong>, which frequently eliminates the need for an <code>if</code> structure or <code>case</code> statement. In the following example, there are two matches for specific names, followed by a catch-all for any other names.</p>
<pre><code class="lang-erlang"><span class="hljs-keyword">-module</span><span class="hljs-params">(greeting)</span>.

<span class="hljs-keyword">-export</span><span class="hljs-params">([say_hello/<span class="hljs-number">1</span>])</span>.

<span class="hljs-function"><span class="hljs-title">say_hello</span><span class="hljs-params">(<span class="hljs-string">"Mary"</span>)</span> -&gt;</span>
  <span class="hljs-string">"Welcome back Mary!"</span>;
<span class="hljs-function"><span class="hljs-title">say_hello</span><span class="hljs-params">(<span class="hljs-string">"Tom"</span>)</span> -&gt;</span>
  <span class="hljs-string">"Howdy Tom."</span>;
<span class="hljs-function"><span class="hljs-title">say_hello</span><span class="hljs-params">(Name)</span> -&gt;</span>
  <span class="hljs-string">"Hello "</span> ++ Name ++ <span class="hljs-string">"."</span>.
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">&gt; greeting:say_hello("Mary").
"Welcome back Mary!"
&gt; greeting:say_hello("Tom").
"Howdy Tom."
&gt; greeting:say_hello("Beth").
"Hello Beth."
</code></pre>
<h2 id="heading-erlang-term-storage"><strong>Erlang Term Storage</strong></h2>
<p>Erlang Term Storage, normally abbreviated as ETS, is an in-memory database built into OTP. It’s accessible within Elixir, and is a powerful alternative to solutions like Redis when your application runs on a single node.</p>
<h2 id="heading-quick-start"><strong>Quick Start</strong></h2>
<p>To create an ETS table you first need to initialize a table <code>tableName = :ets.new(:table_otp_name, [])</code>, once you have initialized a table you can: insert data, lookup values, delete data, and more.</p>
<h3 id="heading-ets-demo-in-iex"><strong>ETS Demo in IEX</strong></h3>
<pre><code class="lang-elixir">iex(<span class="hljs-number">1</span>)&gt; myETSTable = <span class="hljs-symbol">:ets</span>.new(<span class="hljs-symbol">:my_ets_table</span>, [])
<span class="hljs-comment">#Reference&lt;0.1520230345.550371329.65846&gt;</span>
iex(<span class="hljs-number">2</span>)&gt; <span class="hljs-symbol">:ets</span>.insert(myETSTable, {<span class="hljs-string">"favoriteWebSite"</span>, <span class="hljs-string">"freeCodeCamp"</span>})
<span class="hljs-keyword">true</span>
iex(<span class="hljs-number">3</span>)&gt; <span class="hljs-symbol">:ets</span>.insert(myETSTable, {<span class="hljs-string">"favoriteProgrammingLanguage"</span>, <span class="hljs-string">"Elixir"</span>})
<span class="hljs-keyword">true</span>
iex(<span class="hljs-number">4</span>)&gt; <span class="hljs-symbol">:ets</span>.i(myETSTable)
&lt;<span class="hljs-number">1</span>   &gt; {&lt;&lt;<span class="hljs-string">"favoriteProgrammingLanguage"</span>&gt;&gt;,&lt;&lt;<span class="hljs-string">"Elixir"</span>&gt;&gt;}
&lt;<span class="hljs-number">2</span>   &gt; {&lt;&lt;<span class="hljs-string">"favoriteWebSite"</span>&gt;&gt;,&lt;&lt;<span class="hljs-string">"freeCodeCamp"</span>&gt;&gt;}
EOT  (q)uit (p)Digits (k)ill /Regexp --&gt;
</code></pre>
<h2 id="heading-persistence"><strong>Persistence</strong></h2>
<p>ETS Tables are not persistent and are destroyed once the process which owns it terminates. If you would like to store data persistently a traditional database and/or file-based storage is recommended.</p>
<h2 id="heading-use-cases"><strong>Use cases</strong></h2>
<p>ETS Tables are commonly used for caching data in the application, for example account data fetched from a database may be stored in an ETS Table to reduce the amount of queries to the database. Another use case is for rate limiting use of features in a web application - ETS’s fast read and write speed make it great for this. ETS Tables are a powerful tool for developing highly concurrent web applications at the lowest possible hardware cost.</p>
<h3 id="heading-try-it-out"><strong>Try it out</strong></h3>
<p>There are websites where you can try running Erlang commands without having to install anything locally, like these:</p>
<ul>
<li><a target="_blank" href="http://www.tryerlang.org/">Give it a try! (a hands-on tutorial)</a></li>
<li><a target="_blank" href="https://www.tutorialspoint.com/compile_erlang_online.php">TutorialsPoint CodingGround</a></li>
</ul>
<p>If you’d like to install it on your (or a virtual) machine, you can find installation files at <a target="_blank" href="https://www.erlang.org/downloads">Erlang.org</a> or on <a target="_blank" href="https://www.erlang-solutions.com/resources/download.html">Erlang Solutions</a>.</p>
<h4 id="heading-more-information"><strong>More Information:</strong></h4>
<ul>
<li><a target="_blank" href="https://www.erlang.org/about">About Erlang</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Erlang_(programming_language)">Erlang (programming language)</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to build a distributed Game of Life in Elixir ]]>
                </title>
                <description>
                    <![CDATA[ By Artur Trzop I wrote my first game in Elixir. It is a popular thing — Conway’s Game of Life — but it gets quite interesting when you solve it in a functional language, especially when you can see how the actor model works and how actors are distrib... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-distributed-game-of-life-in-elixir-9152588100cd/</link>
                <guid isPermaLink="false">66c34f6939769b84d9fe96de</guid>
                
                    <category>
                        <![CDATA[ Elixir ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Erlang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 17 Jan 2019 17:14:44 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*AfpCKR3o8T1Ie-Eq.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Artur Trzop</p>
<p>I wrote my first game in Elixir. It is a popular thing — Conway’s Game of Life — but it gets quite interesting when you solve it in a functional language, especially when you can see <a target="_blank" href="https://en.wikipedia.org/wiki/Actor_model">how the actor model works</a> and how actors are distributed across servers in the network.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3Snl82uCosun4TAqGggHfSKVUng0YPUzFheF" alt="Image" width="400" height="274" loading="lazy">
<em>Game of Life</em></p>
<p><strong>In this blog post I am going to show:</strong></p>
<ul>
<li>how to write rules for the game of life with tests in Elixir,</li>
<li>parallel tasks across lightweight processes (actors) in order to utilize all CPU cores,</li>
<li>how to distribute work across nodes so the game can be executed by many servers in the cluster,</li>
<li>how to use GenServer behaviour, TaskSupervisor and Agents in Elixir.</li>
</ul>
<p>This project and the full <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life">source code can be found here</a>.</p>
<h3 id="heading-demo">Demo</h3>
<p>Let’s start with watching quick demo of how the game works.</p>
<p><a target="_blank" href="https://asciinema.org/a/44233"><strong>GameOfLife</strong></a><br><a target="_blank" href="https://asciinema.org/a/44233">_Recorded by ArturT_asciinema.org</a></p>
<p>As you can see, node1 represents running game and board on the screen. The second node was also started and connected to the first one. From the second node, we added new cells to the board. Both nodes are responsible for processing the game, but only the first node is a primary with information about the current state of the game. We can connect more nodes to the cluster so game processing can happen on all of the nodes. You are going to learn in this article how to make it happen.</p>
<h3 id="heading-game-of-life-rules">Game of Life rules</h3>
<p>If you already know about <a target="_blank" href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">the game of life problem</a> just jump to <a target="_blank" href="https://beyondscheme.com/2016/distributed-game-of-life-in-elixir#create-new-application-in-elixir">the next header</a>. If not, in this section you can learn the basic concept.</p>
<p>The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:</p>
<ul>
<li>Any live cell with fewer than two live neighbours dies as if caused by under-population.</li>
<li>Any live cell with two or three live neighbours lives on to the next generation.</li>
<li>Any live cell with more than three live neighbours dies, as if by over-population.</li>
<li>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</li>
</ul>
<p>The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed — births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations.</p>
<h3 id="heading-create-new-application-in-elixir">Create new application in Elixir</h3>
<p>First things first, so we are going to create a new Elixir OTP application with supervision tree. We will use supervisor for our game server, you will learn more about it a bit later.</p>
<pre><code>$ mix <span class="hljs-keyword">new</span> --sup game_of_life
</code></pre><p>A <code>--sup</code> option is given to generate an OTP application skeleton including a supervision tree. Normally an app is generated without a supervisor and without the app callback.</p>
<p>In <code>lib/game_of_life.ex</code> file you will find an example of how to add child worker to supervisor.</p>
<pre><code># lib/game_of_life.exdefmodule GameOfLife <span class="hljs-keyword">do</span>  use Application  # See http:<span class="hljs-comment">//elixir-lang.org/docs/stable/elixir/Application.html  # for more information on OTP Applications  def start(_type, _args) do    import Supervisor.Spec, warn: false    children = [      # Define workers and child supervisors to be supervised      # worker(GameOfLife.Worker, [arg1, arg2, arg3]),    ]    # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html    # for other strategies and supported options    opts = [strategy: :one_for_one, name: GameOfLife.Supervisor]    Supervisor.start_link(children, opts)  endend</span>
</code></pre><h3 id="heading-represent-the-board-in-game-of-life">Represent the board in Game of Life</h3>
<p>We need to represent the alive cells on the board in our game. A single cell can be a tuple <code>{x, y}</code> with coordinates in the 2-dimensional board.</p>
<p>All alive cells on the board will be on the list <code>alive_cells</code>.</p>
<pre><code>alive_cells = [{<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">-1</span>,<span class="hljs-number">-2</span>}]
</code></pre><p>Here is an example of how this board with alive cells looks like:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/j2utgQIL1-t1HTIR9smp5jEtsfDIbsOkS1ZE" alt="Image" width="600" height="450" loading="lazy">
<em>Board with alive cells</em></p>
<p>and here are proper x &amp; y coordinates:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/FNNnkZazIb8gyyR0vg5F9R4kiXVKAUXDUx9D" alt="Image" width="600" height="450" loading="lazy">
<em>Coordinates of alive cells</em></p>
<p>Now when we have the idea of how we are going to store our alive cells we can jump to write some code.</p>
<h3 id="heading-game-of-life-rules-with-tests">Game of Life rules with tests</h3>
<p>We can create <code>GameOfLife.Cell</code> module with function <code>keep_alive?/2</code> responsible for determining if a particular alive cell <code>{x, y}</code> should be still alive on the next generation or not.</p>
<p>Here is the function with expected arguments:</p>
<pre><code># lib/game_of_life/cell.exdefmodule GameOfLife.Cell <span class="hljs-keyword">do</span>  def keep_alive?(alive_cells, {x, y} = _alive_cell) <span class="hljs-keyword">do</span>    # TODO  endend
</code></pre><p>Let’s write some tests to cover the first of the requirements of the Game of Life:</p>
<blockquote>
<p>Any live cell with fewer than two live neighbours dies, as if caused by under-population.</p>
</blockquote>
<p>We wrote tests to ensure <code>GameOfLife.Cell.keep_alive?/2</code> function returns false in a case when the alive cell has no neighbours or has just one.</p>
<pre><code># test/game_of_life/cell_test.exsdefmodule GameOfLife.CellTest <span class="hljs-keyword">do</span>  use ExUnit.Case, <span class="hljs-attr">async</span>: <span class="hljs-literal">true</span>  test <span class="hljs-string">"alive cell with no neighbours dies"</span> <span class="hljs-keyword">do</span>    alive_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}    alive_cells = [alive_cell]    refute GameOfLife.Cell.keep_alive?(alive_cells, alive_cell)  end  test <span class="hljs-string">"alive cell with 1 neighbour dies"</span> <span class="hljs-keyword">do</span>    alive_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}    alive_cells = [alive_cell, {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}]    refute GameOfLife.Cell.keep_alive?(alive_cells, alive_cell)  endend
</code></pre><p><code>GameOfLife.Cell.keep_alive?/2</code> function needs to return false just to pass our tests so let’s add more tests to cover other requirements.</p>
<blockquote>
<p>Any live cell with more than three live neighbours dies, as if by over-population.</p>
</blockquote>
<pre><code># test/game_of_life/cell_test.exstest <span class="hljs-string">"alive cell with more than 3 neighbours dies"</span> <span class="hljs-keyword">do</span>  alive_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}  alive_cells = [alive_cell, {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  refute GameOfLife.Cell.keep_alive?(alive_cells, alive_cell)end
</code></pre><blockquote>
<p><em>Any live cell with two or three live neighbours lives on to the next generation.</em></p>
</blockquote>
<pre><code># test/game_of_life/cell_test.exstest <span class="hljs-string">"alive cell with 2 neighbours lives"</span> <span class="hljs-keyword">do</span>  alive_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}  alive_cells = [alive_cell, {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}]  assert GameOfLife.Cell.keep_alive?(alive_cells, alive_cell)endtest <span class="hljs-string">"alive cell with 3 neighbours lives"</span> <span class="hljs-keyword">do</span>  alive_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}  alive_cells = [alive_cell, {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  assert GameOfLife.Cell.keep_alive?(alive_cells, alive_cell)end
</code></pre><p>Now, we can implement our <code>GameOfLife.Cell.keep_alive?/2</code> function.</p>
<pre><code># lib/game_of_life/cell.exdefmodule GameOfLife.Cell <span class="hljs-keyword">do</span>  def keep_alive?(alive_cells, {x, y} = _alive_cell) <span class="hljs-keyword">do</span>    <span class="hljs-keyword">case</span> count_neighbours(alive_cells, x, y, <span class="hljs-number">0</span>) <span class="hljs-keyword">do</span>      <span class="hljs-number">2</span> -&amp;gt; <span class="hljs-literal">true</span>      <span class="hljs-number">3</span> -&gt; <span class="hljs-literal">true</span>      _ -&gt; <span class="hljs-literal">false</span>    end  end  defp count_neighbours([head_cell | tail_cells], x, y, count) <span class="hljs-keyword">do</span>    increment = <span class="hljs-keyword">case</span> head_cell <span class="hljs-keyword">do</span>      {hx, hy} when hx == x - <span class="hljs-number">1</span> and hy == y - <span class="hljs-number">1</span> -&gt; <span class="hljs-number">1</span>      {hx, hy} when hx == x     and hy == y - <span class="hljs-number">1</span> -&gt; <span class="hljs-number">1</span>      {hx, hy} when hx == x + <span class="hljs-number">1</span> and hy == y - <span class="hljs-number">1</span> -&gt; <span class="hljs-number">1</span>      {hx, hy} when hx == x - <span class="hljs-number">1</span> and hy == y     -&amp;gt; <span class="hljs-number">1</span>      {hx, hy} when hx == x + <span class="hljs-number">1</span> and hy == y     -&gt;; <span class="hljs-number">1</span>      {hx, hy} when hx == x - <span class="hljs-number">1</span> and hy == y + <span class="hljs-number">1</span> -&gt;; <span class="hljs-number">1</span>      {hx, hy} when hx == x     and hy == y + <span class="hljs-number">1</span> -&amp;gt; <span class="hljs-number">1</span>      {hx, hy} when hx == x + <span class="hljs-number">1</span> and hy == y + <span class="hljs-number">1</span> -&gt; <span class="hljs-number">1</span>      _not_neighbour -&gt; <span class="hljs-number">0</span>    end    count_neighbours(tail_cells, x, y, count + increment)  end  defp count_neighbours([], _x, _y, count), <span class="hljs-attr">do</span>: countend
</code></pre><p>As you can see, we implemented the private function <code>count_neighbours/4</code> responsible for counting neighbours. It will be helpful to meet the next rule.</p>
<p>There is one more requirement we forgot about:</p>
<blockquote>
<p>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</p>
</blockquote>
<p>We are going to write a new function <code>GameOfLife.Cell.become_alive?/2</code> expecting the coordinates of the dead cell and returning if the dead cell should become alive or not.</p>
<pre><code># lib/game_of_life/cell.exdefmodule GameOfLife.Cell <span class="hljs-keyword">do</span>  def become_alive?(alive_cells, {x, y} = _dead_cell) <span class="hljs-keyword">do</span>    <span class="hljs-number">3</span> == count_neighbours(alive_cells, x, y, <span class="hljs-number">0</span>)  endend
</code></pre><p>And here is the test for that:</p>
<pre><code># test/game_of_life/cell_test.exstest <span class="hljs-string">"dead cell with three live neighbours becomes a live cell"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  dead_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}  assert GameOfLife.Cell.become_alive?(alive_cells, dead_cell)endtest <span class="hljs-string">"dead cell with two live neighbours stays dead"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}]  dead_cell = {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}  refute GameOfLife.Cell.become_alive?(alive_cells, dead_cell)end
</code></pre><p>There is one more thing which might be helpful for us. We have the list of alive cells but we don’t know much about the dead cells. The number of dead cells is infinite so we need to cut down the number of dead cells for which we want to check if they should become alive. The simple way would be to check only dead cells with alive neighbours. Hence the <code>GameOfLife.Cell.dead_neighbours/1</code>function.</p>
<p>Let’s write some tests first:</p>
<pre><code># test/game_of_life/cell_test.exstest <span class="hljs-string">"find dead cells (neighbours of alive cell)"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}]  dead_neighbours = GameOfLife.Cell.dead_neighbours(alive_cells) |&amp;gt; Enum.sort  expected_dead_neighbours = [    {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>},    {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>},    {<span class="hljs-number">0</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}  ] |&gt;; Enum.sort  assert dead_neighbours == expected_dead_neighboursendtest <span class="hljs-string">"find dead cells (neighbours of alive cells)"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  dead_neighbours = GameOfLife.Cell.dead_neighbours(alive_cells) |&amp;gt; Enum.sort  expected_dead_neighbours = [    {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">3</span>, <span class="hljs-number">0</span>},    {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">3</span>, <span class="hljs-number">1</span>},    {<span class="hljs-number">0</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">3</span>, <span class="hljs-number">2</span>}  ] |&gt; Enum.sort  assert dead_neighbours == expected_dead_neighboursend
</code></pre><p>and here is the implemented function:</p>
<pre><code># lib/game_of_life/cell.exdef dead_neighbours(alive_cells) <span class="hljs-keyword">do</span>  neighbours = neighbours(alive_cells, [])  (neighbours |&amp;gt; Enum.uniq) -- alive_cellsenddefp neighbours([{x, y} | cells], neighbours) <span class="hljs-keyword">do</span>  neighbours(cells, neighbours ++ [    {x - <span class="hljs-number">1</span>, y - <span class="hljs-number">1</span>}, {x    , y - <span class="hljs-number">1</span>}, {x + <span class="hljs-number">1</span>, y - <span class="hljs-number">1</span>},    {x - <span class="hljs-number">1</span>, y    }, {x + <span class="hljs-number">1</span>, y    },    {x - <span class="hljs-number">1</span>, y + <span class="hljs-number">1</span>}, {x    , y + <span class="hljs-number">1</span>}, {x + <span class="hljs-number">1</span>, y + <span class="hljs-number">1</span>}  ])enddefp neighbours([], neighbours), <span class="hljs-attr">do</span>: neighbours
</code></pre><p>Basically, these are all rules implemented in the single module <code>GameOfLife.Cell</code>. You can see the whole <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life/blob/master/lib/game_of_life/cell.ex">module file</a> with <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life/blob/master/test/game_of_life/cell_test.exs">tests on GitHub</a>.</p>
<h3 id="heading-the-architecture-of-distributed-game-of-life">The architecture of distributed Game of Life</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/BIrpLZBjGimv4-HlBQQt9UslBgNwam3Pr0bC" alt="Image" width="600" height="450" loading="lazy">
<em>The architecture of distributed Game of Life in Elixir</em></p>
<p>Our main supervisor is <code>GameOfLife.Supervisor</code> which I mentioned at the beginning of the article. Below you can see how we defined its children like <code>Task.Supervisor</code>, workers for <code>BoardServer</code> and <code>GamePrinter</code>.</p>
<pre><code># lib/game_of_life.exdefmodule GameOfLife <span class="hljs-keyword">do</span>  use Application  # See http:<span class="hljs-comment">//elixir-lang.org/docs/stable/elixir/Application.html  # for more information on OTP Applications  def start(_type, _args) do    import Supervisor.Spec, warn: false    init_alive_cells = []    children = [      # Define workers and child supervisors to be supervised      # worker(GameOfLife.Worker, [arg1, arg2, arg3]),      supervisor(Task.Supervisor, [[name: GameOfLife.TaskSupervisor]]),      worker(GameOfLife.BoardServer, [init_alive_cells]),      # We will uncomment this line later      # worker(GameOfLife.GamePrinter, []),    ]    # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html    # for other strategies and supported options    opts = [strategy: :one_for_one, name: GameOfLife.Supervisor]    Supervisor.start_link(children, opts)  endend</span>
</code></pre><p>Let me describe what each component on the image is responsible for.</p>
<p><code>Task.Supervisor</code> is an Elixir module defining a new supervisor which can be used to dynamically supervise tasks. We are going to use it to spin off tasks like determining if the particular cell should live or die. Those tasks can be run across nodes connected into the cluster.</p>
<p>In the above code, we gave the name <code>GameOfLife.TaskSupervisor</code> for our supervisor. We will use this name to tell the <code>Task.Supervisor.async</code> function which Task Supervisor should handle our task. You can read more about <a target="_blank" href="http://elixir-lang.org/docs/stable/elixir/Task.Supervisor.html">Task.Supervisor here</a>.</p>
<p><code>GameOfLife.BoardServer</code> is our module implemented as <a target="_blank" href="http://elixir-lang.org/docs/stable/elixir/GenServer.html">GenServer behaviour</a>. It is responsible for holding the state of the game. By that I mean it keeps the list of alive cells on the board along with generation counter and TRef. TRef is a timer reference returned by the <a target="_blank" href="http://erlang.org/doc/man/timer.html">Erlang timer module</a> and the <a target="_blank" href="http://erlang.org/doc/man/timer.html#apply_interval-4">apply_interval</a> function.</p>
<p>We want to start the game and generate a new list of alive cells for the next generation with a specified time interval. With each new generation, we will update the generation counter. The other interesting thing is that <code>GameOfLife.BoardServer</code> is running only on a single node. Once another node is connected to the cluster where is already running <code>GameOfLife.BoardServer</code> then <code>GameOfLife.BoardServer</code> won’t be started just like that on the newly connected node.</p>
<p>Instead on the new node <code>GameOfLife.BoardServer</code> will keep the only reference to the PID of the process existing on the first node. We want to have the single source of truth about the state of our game in one primary <code>GameOfLife.BoardServer</code> process existing on the first node started in the cluster.</p>
<p><code>GameOfLife.GamePrinter</code> is a simple module using <a target="_blank" href="http://elixir-lang.org/docs/stable/elixir/Agent.html">Agent</a> in order to keep TRef (time reference) so we can print the board to STDOUT with the specified interval. We will use <a target="_blank" href="http://erlang.org/doc/man/timer.html#apply_interval-4">Erlang timer module</a> to print the board on the screen every second.</p>
<p>You may wonder what’s the difference between GenServer and Agent.</p>
<p>A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously, and so on. The advantage of using a generic server process (GenServer) is that it will have a standard set of interface functions and include functionality for tracing and error reporting. It also fits into a supervision tree as this is what we did in the <code>GameOfLife</code> module.</p>
<p>On the other hand, Agent is a much simpler solution than GenServer. Agents are a simple abstraction around state. Often in Elixir there is a need to share or store state that must be accessed from different processes or by the same process at different points in time. The Agent module provides a basic server implementation that allows state to be retrieved and updated via a simple API. This is what we are going to do in <code>GameOfLife.GamePrinter</code> as we only need to keep time reference to our timer interval.</p>
<h3 id="heading-create-node-manager-for-task-supervisor">Create node manager for task supervisor</h3>
<p>Let’s start with something simple just to see if we can distribute work across nodes in the cluster. We assume each new process created by task supervisor will be assigned randomly to one of the connected nodes. Each node should be equally overloaded with the assumption that each task is pretty similar and all nodes are machines with the same configuration and overload.</p>
<pre><code># lib/game_of_life/node_manager.exdefmodule GameOfLife.NodeManager <span class="hljs-keyword">do</span>  def all_nodes <span class="hljs-keyword">do</span>    [Node.self | Node.list]  end  def random_node <span class="hljs-keyword">do</span>    all_nodes |&amp;gt; Enum.random  endend
</code></pre><p>Our node manager has <code>random_node/0</code> function which returns the name of a random node connected to the cluster. Basically, that’s it. A simple solution should be enough for now.</p>
<h3 id="heading-create-board-helper-functions">Create board helper functions</h3>
<p>We need some helper functions for operations we can do on the board like adding and removing cells. Let’s start with tests for the module <code>GameOfLife.Board</code> and function <code>add_cells/2</code>.</p>
<pre><code># test/game_of_life/board_test.exsdefmodule GameOfLife.BoardTest <span class="hljs-keyword">do</span>  use ExUnit.Case, <span class="hljs-attr">async</span>: <span class="hljs-literal">true</span>  test <span class="hljs-string">"add new cells to alive cells without duplicates"</span> <span class="hljs-keyword">do</span>    alive_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}]    new_cells = [{<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}]    actual_alive_cells = GameOfLife.Board.add_cells(alive_cells, new_cells)                          |&amp;gt; Enum.sort    expected_alive_cells = [{<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}]    assert actual_alive_cells == expected_alive_cells  endend
</code></pre><p>We need to ensure we won’t allow adding the same cell twice to the board so we test that there are no duplicates. Here is the implementation for <code>add_cells/2</code> function:</p>
<pre><code># lib/game_of_life/board.exdefmodule GameOfLife.Board <span class="hljs-keyword">do</span>  def add_cells(alive_cells, new_cells) <span class="hljs-keyword">do</span>    alive_cells ++ new_cells    |&amp;gt; Enum.uniq  endend
</code></pre><p>Another thing is removing cells from the list of alive cells:</p>
<pre><code># test/game_of_life/board_test.exstest <span class="hljs-string">"remove cells which must be killed from alive cells"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">4</span>, <span class="hljs-number">-2</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  kill_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>}]  actual_alive_cells = GameOfLife.Board.remove_cells(alive_cells, kill_cells)  expected_alive_cells = [{<span class="hljs-number">4</span>, <span class="hljs-number">-2</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  assert actual_alive_cells == expected_alive_cellsend
</code></pre><p>Implementation is super simple:</p>
<pre><code># lib/game_of_life/board.exdef remove_cells(alive_cells, kill_cells) <span class="hljs-keyword">do</span>  alive_cells -- kill_cellsend
</code></pre><p>Let’s create something more advanced. We should determine which cells should still live in the next generation after the tick. Here is a test for the <code>GameOfLife.Board.keep_alive_tick/1</code> function:</p>
<pre><code># test/game_of_life/board_test.exstest <span class="hljs-string">"alive cell with 2 neighbours lives on to the next generation"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>}]  expected_alive_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}]  assert GameOfLife.Board.keep_alive_tick(alive_cells) == expected_alive_cellsend
</code></pre><p>The function <code>keep_alive_tick</code> does a few things like creating a new task with <code>Task.Supervisor</code> for each alive cell. Tasks will be created across available nodes in the cluster. We calculate if alive cells should stay alive or be removed. The <code>keep_alive_or_nilify/2</code> function returns if the cell should live or <code>nil</code> otherwise.</p>
<p>We wait with <code>Task.await/1</code> until all tasks across all nodes finished their work. Tasks are working in parallel but we need to wait for results from each task. We remove from the list the <code>nil</code> values so at the end we end up with only alive cells for the next generation.</p>
<pre><code># lib/game_of_life/board.ex@doc <span class="hljs-string">"Returns cells that should still live on the next generation"</span>def keep_alive_tick(alive_cells) <span class="hljs-keyword">do</span>  alive_cells  |&amp;gt; Enum.map(&amp;(Task.Supervisor.async(                {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                GameOfLife.Board, :keep_alive_or_nilify, [alive_cells, &amp;<span class="hljs-number">1</span>])))  |&gt;; Enum.map(&amp;Task.await/<span class="hljs-number">1</span>)  |&gt; remove_nil_cellsenddef keep_alive_or_nilify(alive_cells, cell) <span class="hljs-keyword">do</span>  <span class="hljs-keyword">if</span> GameOfLife.Cell.keep_alive?(alive_cells, cell), <span class="hljs-attr">do</span>: cell, <span class="hljs-attr">else</span>: nilenddefp remove_nil_cells(cells) <span class="hljs-keyword">do</span>  cells  |&gt; Enum.filter(fn cell -&amp;gt; cell != nil end)end
</code></pre><p>There is one more case we should handle which is a situation when dead cells should become alive. <code>GameOfLife.Board.become_alive_tick/1</code> function will be responsible for that.</p>
<pre><code># test/game_of_life/board_test.exstest <span class="hljs-string">"dead cell with three live neighbours becomes a live cell"</span> <span class="hljs-keyword">do</span>  alive_cells = [{<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}]  born_cells = GameOfLife.Board.become_alive_tick(alive_cells)  expected_born_cells = [{<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>}, {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">1</span>}]  assert born_cells == expected_born_cellsend
</code></pre><p>This is how our function looks like:</p>
<pre><code># lib/game_of_life/board.ex@doc <span class="hljs-string">"Returns new born cells on the next generation"</span>def become_alive_tick(alive_cells) <span class="hljs-keyword">do</span>  GameOfLife.Cell.dead_neighbours(alive_cells)  |&amp;gt; Enum.map(&amp;(Task.Supervisor.async(                {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                GameOfLife.Board, :become_alive_or_nilify, [alive_cells, &amp;<span class="hljs-number">1</span>])))  |&gt;; Enum.map(&amp;Task.await/<span class="hljs-number">1</span>)  |&gt; remove_nil_cellsenddef become_alive_or_nilify(alive_cells, dead_cell) <span class="hljs-keyword">do</span>  <span class="hljs-keyword">if</span> GameOfLife.Cell.become_alive?(alive_cells, dead_cell), <span class="hljs-attr">do</span>: dead_cell, <span class="hljs-attr">else</span>: nilend
</code></pre><p>It works similarly to <code>GameOfLife.Board.keep_alive_tick/1</code>. First, we are looking for the dead neighbours of alive cells. Then for each dead cell we create a new process across the nodes in the cluster to determine if the dead cell should become alive in the next generation.</p>
<p>You can see the full source code of <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life/blob/master/lib/game_of_life/board.ex">GameOfLife.Board module</a> and <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life/blob/master/test/game_of_life/board_test.exs">tests on github</a>.</p>
<h3 id="heading-create-boardserver">Create BoardServer</h3>
<p>Let’s create <code>GameOfLife.BoardServer</code> generic server behaviour. We define a public interface for the server.</p>
<pre><code># lib/game_of_life/board_server.exdefmodule GameOfLife.BoardServer <span class="hljs-keyword">do</span>  use GenServer  <span class="hljs-built_in">require</span> Logger  @name {:<span class="hljs-built_in">global</span>, __MODULE__}  @game_speed <span class="hljs-number">1000</span> # miliseconds  # Client  def start_link(alive_cells) <span class="hljs-keyword">do</span>    <span class="hljs-keyword">case</span> GenServer.start_link(__MODULE__, {alive_cells, nil, <span class="hljs-number">0</span>}, <span class="hljs-attr">name</span>: @name) <span class="hljs-keyword">do</span>      {:ok, pid} -&amp;gt;        Logger.info <span class="hljs-string">"Started #{__MODULE__} master"</span>        {:ok, pid}      {:error, {:already_started, pid}} -&gt;        Logger.info <span class="hljs-string">"Started #{__MODULE__} slave"</span>        {:ok, pid}    end  end  def alive_cells <span class="hljs-keyword">do</span>    GenServer.call(@name, :alive_cells)  end  def generation_counter <span class="hljs-keyword">do</span>    GenServer.call(@name, :generation_counter)  end  def state <span class="hljs-keyword">do</span>    GenServer.call(@name, :state)  end  @doc <span class="hljs-string">""</span><span class="hljs-string">"  Clears board and adds only new cells.  Generation counter is reset.  "</span><span class="hljs-string">""</span>  def set_alive_cells(cells) <span class="hljs-keyword">do</span>    GenServer.call(@name, {:set_alive_cells, cells})  end  def add_cells(cells) <span class="hljs-keyword">do</span>    GenServer.call(@name, {:add_cells, cells})  end  def tick <span class="hljs-keyword">do</span>    GenServer.cast(@name, :tick)  end  def start_game(speed \\ @game_speed) <span class="hljs-keyword">do</span>    GenServer.call(@name, {:start_game, speed})  end  def stop_game <span class="hljs-keyword">do</span>    GenServer.call(@name, :stop_game)  end  def change_speed(speed) <span class="hljs-keyword">do</span>    stop_game    start_game(speed)  endend
</code></pre><p>As you can see, we use <code>GenServer</code> behaviour in our module. The module requires also Logger as we would like to print some info to the STDOUT.</p>
<p>In the <code>start_link/1</code> function we start a new <code>GenServer</code>. When our generic server starts, it is as a first process in the cluster. Then it becomes the primary process. In the case when there is already a running process with a globally registered name <code>{:global,__MODULE__}</code>, we log info that our process will be a replica process with a reference to the existing PID on another node in the cluster.</p>
<p>We store the global name for our server in the attribute <code>@name</code>. We use another attribute <code>@game_speed</code> for default game speed which is 1000 milliseconds.</p>
<p>In our public interface, we have the <code>alive_cells/1</code> function which returns the list of alive cells. Basically, it is the current state of the game (alive cells on the board). This function calls <code>GenServer</code> with the registered <code>@name</code> and requests <code>:alive_cells</code>. We need to implement the <code>handle_call/3</code> function for this type of request (<code>:alive_cells</code>).</p>
<p>There is another public function <code>generation_counter/1</code> which returns how many generations were already processed by the board server.</p>
<p>The <code>state/1</code> function returns state that is held by our generic server. The state is represented as the tuple with 3 values like alive cells, TRef (time reference - we want to regenerate board every second) and generation counter. TRef is a very internal thing for the board server so we won’t return this to the outside world. That’s why we will return just alive cells and the generation counter. You will see it later in the implementation for <code>handle_call(:state, _from, state)</code>.</p>
<p>You can use the <code>set_alive_cells/1</code> function in the case when you want to override the current list of alive cells with a new list.</p>
<p>The <code>add_cells/1</code> function will be very useful as we want to be able to add new cells or figures to the board. For instance, we may want to add a blinker pattern to the existing game. You will learn more about patterns later.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SGbjJ1XyyVP1F7u7KDrJ2mT74d6J3KBxuhw1" alt="Image" width="82" height="82" loading="lazy">
<em>blinker pattern</em></p>
<p>We can manually force the game to calculate the next generation of cells with the <code>tick/1</code> function.</p>
<p>The <code>start_game/1</code> function is responsible for starting a new timer which calls every second a <code>tick/1</code> function. Thanks to that our game will update the list of alive cells within a specified interval which is <code>@game_speed</code>.</p>
<p>The last 2 functions are <code>stop_game/1</code> and <code>change_speed/1</code> which just restart the game and start a new one with the provided speed.</p>
<p>Now you can see how the above functions are working. They are calling server callbacks.</p>
<pre><code># lib/game_of_life/board_server.exdefmodule GameOfLife.BoardServer <span class="hljs-keyword">do</span>  use GenServer  # ...  # Server (callbacks)  def handle_call(:alive_cells, _from, {alive_cells, _tref, _generation_counter} = state) <span class="hljs-keyword">do</span>    {:reply, alive_cells, state}  end  def handle_call(:generation_counter, _from, {_alive_cells, _tref, generation_counter} = state) <span class="hljs-keyword">do</span>    {:reply, generation_counter, state}  end  def handle_call(:state, _from, {alive_cells, _tref, generation_counter} = state) <span class="hljs-keyword">do</span>    {:reply, {alive_cells, generation_counter}, state}  end  def handle_call({:set_alive_cells, cells}, _from, {_alive_cells, tref, _generation_counter}) <span class="hljs-keyword">do</span>    {:reply, cells, {cells, tref, <span class="hljs-number">0</span>}}  end  def handle_call({:add_cells, cells}, _from, {alive_cells, tref, generation_counter}) <span class="hljs-keyword">do</span>    alive_cells = GameOfLife.Board.add_cells(alive_cells, cells)    {:reply, alive_cells, {alive_cells, tref, generation_counter}}  end  def handle_call({:start_game, speed}, _from, {alive_cells, nil = _tref, generation_counter}) <span class="hljs-keyword">do</span>    {:ok, tref} = :timer.apply_interval(speed, __MODULE__, :tick, [])    {:reply, :game_started, {alive_cells, tref, generation_counter}}  end  def handle_call({:start_game, _speed}, _from, {_alive_cells, _tref, _generation_counter} = state) <span class="hljs-keyword">do</span>    {:reply, :game_already_running, state}  end  def handle_call(:stop_game, _from, {_alive_cells, nil = _tref, _generation_counter} = state) <span class="hljs-keyword">do</span>    {:reply, :game_not_running, state}  end  def handle_call(:stop_game, _from, {alive_cells, tref, generation_counter}) <span class="hljs-keyword">do</span>    {:ok, :cancel} = :timer.cancel(tref)    {:reply, :game_stoped, {alive_cells, nil, generation_counter}}  end  def handle_cast(:tick, {alive_cells, tref, generation_counter}) <span class="hljs-keyword">do</span>    keep_alive_task = Task.Supervisor.async(                      {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                      GameOfLife.Board, :keep_alive_tick, [alive_cells])    become_alive_task = Task.Supervisor.async(                        {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                        GameOfLife.Board, :become_alive_tick, [alive_cells])    keep_alive_cells = Task.await(keep_alive_task)    born_cells = Task.await(become_alive_task)    alive_cells = keep_alive_cells ++ born_cells    {:noreply, {alive_cells, tref, generation_counter + <span class="hljs-number">1</span>}}  endend
</code></pre><p>Oh, we forgot about tests. In this case, we can use <a target="_blank" href="http://elixir-lang.org/docs/stable/ex_unit/ExUnit.DocTest.html">DocTest</a>. It allows us to generate tests from the code examples existing in a module/function/macro’s documentation.</p>
<p>Our test file is super short:</p>
<pre><code># test/game_of_life/board_server_test.exsdefmodule GameOfLife.BoardServerTest <span class="hljs-keyword">do</span>  use ExUnit.Case  doctest GameOfLife.BoardServerend
</code></pre><p>Let’s add <code>@moduledoc</code> to <code>GameOfLife.BoardServer</code>.</p>
<pre><code># lib/game_of_life/board_server.exdefmodule GameOfLife.BoardServer <span class="hljs-keyword">do</span>  use GenServer  <span class="hljs-built_in">require</span> Logger  @moduledoc <span class="hljs-string">""</span><span class="hljs-string">"  ## Example      iex&gt; GameOfLife.BoardServer.start_game      :game_started      iex&gt; GameOfLife.BoardServer.start_game      :game_already_running      iex&gt; GameOfLife.BoardServer.stop_game      :game_stoped      iex&gt; GameOfLife.BoardServer.stop_game      :game_not_running      iex&gt; GameOfLife.BoardServer.change_speed(500)      :game_started      iex&gt; GameOfLife.BoardServer.stop_game      :game_stoped      iex&gt; GameOfLife.BoardServer.set_alive_cells([{0, 0}])      [{0, 0}]      iex&gt; GameOfLife.BoardServer.alive_cells      [{0, 0}]      iex&gt; GameOfLife.BoardServer.add_cells([{0, 1}])      [{0, 0}, {0, 1}]      iex&gt; GameOfLife.BoardServer.alive_cells      [{0, 0}, {0, 1}]      iex&gt; GameOfLife.BoardServer.state      {[{0, 0}, {0, 1}], 0}      iex&gt; GameOfLife.BoardServer.generation_counter      0      iex&gt; GameOfLife.BoardServer.tick      :ok      iex&gt; GameOfLife.BoardServer.generation_counter      1      iex&gt; GameOfLife.BoardServer.state      {[], 1}  "</span><span class="hljs-string">""</span>end
</code></pre><p>As you can see we have grouped 3 examples in the <code>@moduledoc</code> attribute and they are separated by a new line. When you run tests you will see 3 separate tests.</p>
<pre><code>$ mix test test/game_of_life/board_server_test.exsCompiled lib/game_of_life/board_server.ex20:<span class="hljs-number">54</span>:<span class="hljs-number">30.637</span> [info]  Started Elixir.GameOfLife.BoardServer master...Finished <span class="hljs-keyword">in</span> <span class="hljs-number">0.1</span> seconds (<span class="hljs-number">0.1</span>s on load, <span class="hljs-number">0.00</span>s on tests)<span class="hljs-number">3</span> tests, <span class="hljs-number">0</span> failuresRandomized <span class="hljs-keyword">with</span> seed <span class="hljs-number">791637</span>
</code></pre><p>In <code>GameOfLife.BoardServer</code> you probably noticed 2 interesting things. First is <code>GameOfLife.Board</code> which is called in:</p>
<pre><code># lib/game_of_life/board_server.exdef handle_call({:add_cells, cells}, _from, {alive_cells, tref, generation_counter}) <span class="hljs-keyword">do</span>  alive_cells = GameOfLife.Board.add_cells(alive_cells, cells)  {:reply, alive_cells, {alive_cells, tref, generation_counter}}end
</code></pre><p>As you saw before we added some useful functions to <code>GameOfLife.Board</code> module which helps us to do operations on the list of alive cells.</p>
<p>Another interesting thing is how we use <code>Task.Supervisor</code> in:</p>
<pre><code># lib/game_of_life/board_server.exdef handle_cast(:tick, {alive_cells, tref, generation_counter}) <span class="hljs-keyword">do</span>    keep_alive_task = Task.Supervisor.async(                      {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                      GameOfLife.Board, :keep_alive_tick, [alive_cells])    become_alive_task = Task.Supervisor.async(                        {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                        GameOfLife.Board, :become_alive_tick, [alive_cells])    keep_alive_cells = Task.await(keep_alive_task)    born_cells = Task.await(become_alive_task)    alive_cells = keep_alive_cells ++ born_cells    {:noreply, {alive_cells, tref, generation_counter + <span class="hljs-number">1</span>}}  end
</code></pre><p>What we are doing here is spinning off a new async process to run the <code>GameOfLife.keep_alive_tick/1</code> function with the argument <code>alive_cells</code>.</p>
<pre><code># lib/game_of_life/board_server.exkeep_alive_task = Task.Supervisor.async(                  {GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node},                  GameOfLife.Board, :keep_alive_tick, [alive_cells])
</code></pre><p>The tuple <code>{GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node}</code> tells <code>Task.Supervisor</code> that we want to use task supervisor with the name <code>GameOfLife.TaskSupervisor</code> and we want to run the process on the node returned by the <code>GameOfLife.NodeManager.random_node</code> function.</p>
<h3 id="heading-create-game-printer-and-console-presenter">Create game printer and console presenter</h3>
<p><code>GameOfLife.GamePrinter</code> module is running as a worker under the supervision of the <code>GameOfLife</code> supervisor. <code>GameOfLife.GamePrinter</code> is using <code>Agent</code> to store <code>TRef</code> for timer reference as we want to print the board to the STDOUT with the specified interval.</p>
<p>You have already seen the example of using <code>Agent</code> so this shouldn’t be new for you. Basically, we wrote the public interface to start and stop printing the board to the screen. For tests we used <a target="_blank" href="http://elixir-lang.org/docs/stable/ex_unit/ExUnit.DocTest.html">DocTest</a>.</p>
<pre><code># lib/game_of_life/game_printer.exdefmodule GameOfLife.GamePrinter <span class="hljs-keyword">do</span>  @moduledoc <span class="hljs-string">""</span><span class="hljs-string">"  ## Example      iex&gt; GameOfLife.GamePrinter.start_printing_board      :printing_started      iex&gt; GameOfLife.GamePrinter.start_printing_board      :already_printing      iex&gt; GameOfLife.GamePrinter.stop_printing_board      :printing_stopped      iex&gt; GameOfLife.GamePrinter.stop_printing_board      :already_stopped  "</span><span class="hljs-string">""</span>  @print_speed <span class="hljs-number">1000</span>  def start_link <span class="hljs-keyword">do</span>    Agent.start_link(fn -&gt; nil end, <span class="hljs-attr">name</span>: __MODULE__)  end  def start_printing_board <span class="hljs-keyword">do</span>    Agent.get_and_update(__MODULE__, __MODULE__, :do_start_printing_board, [])  end  def do_start_printing_board(nil = _tref) <span class="hljs-keyword">do</span>    {:ok, tref} = :timer.apply_interval(@print_speed, __MODULE__, :print_board, [])    {:printing_started, tref}  end  def do_start_printing_board(tref), <span class="hljs-attr">do</span>: {:already_printing, tref}  def print_board <span class="hljs-keyword">do</span>    {alive_cells, generation_counter} = GameOfLife.BoardServer.state    alive_counter = alive_cells |&gt; Enum.count    GameOfLife.Presenters.Console.print(alive_cells, generation_counter, alive_counter)  end  def stop_printing_board <span class="hljs-keyword">do</span>    Agent.get_and_update(__MODULE__, __MODULE__, :do_stop_printing_board, [])  end  def do_stop_printing_board(nil = _tref), <span class="hljs-attr">do</span>: {:already_stopped, nil}  def do_stop_printing_board(tref) <span class="hljs-keyword">do</span>    {:ok, :cancel} = :timer.cancel(tref)    {:printing_stopped, nil}  endend
</code></pre><p><code>GameOfLife.Presenters.Console</code> is responsible for printing the board nicely with X &amp; Y axes, the number of alive cells, and the generation counter. Let’s start with tests. We are going to capture STDOUT and compare if data printed to the screen are looking as we expect.</p>
<pre><code># test/game_of_life/presenters/console_test.exsdefmodule GameOfLife.Presenters.ConsoleTest <span class="hljs-keyword">do</span>  use ExUnit.Case  # allows to capture stuff sent to stdout  <span class="hljs-keyword">import</span> ExUnit.CaptureIO  test <span class="hljs-string">"print cells on the console output"</span> <span class="hljs-keyword">do</span>    cell_outside_of_board = {<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>}    cells = [{<span class="hljs-number">0</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">2</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">0</span>, <span class="hljs-number">2</span>}, cell_outside_of_board]    result = capture_io fn -&amp;gt;      GameOfLife.Presenters.Console.print(cells, <span class="hljs-number">123</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>)    end    assert result == (    <span class="hljs-string">"    2| O,,\n"</span> &lt;&gt;    <span class="hljs-string">"    1| ,O,\n"</span> &lt;&gt;    <span class="hljs-string">"    0| OOO\n"</span> &lt;&gt;    <span class="hljs-string">"     | _ _ \n"</span> &lt;;&amp;gt;    <span class="hljs-string">"    /  0    \n"</span> &amp;lt;&gt;    <span class="hljs-string">"Generation: 123\n"</span> &amp;lt;&amp;gt;    <span class="hljs-string">"Alive cells: 6\n"</span>    )  endend
</code></pre><p>Here is the implementation of our print function:</p>
<pre><code># lib/game_of_life/presenters/<span class="hljs-built_in">console</span>.exdefmodule GameOfLife.Presenters.Console <span class="hljs-keyword">do</span>  @doc <span class="hljs-string">""</span><span class="hljs-string">"  Print cells to the console output.  Board is visible only for specified size for x and y.  Start x and y are in top left corner of the board.  `x_padding` Must be a prime number. Every x divided by the prime number  will be visible on x axis.  `y_padding` Any number. Padding for numbers on y axis.  "</span><span class="hljs-string">""</span>  def print(cells, generation_counter, alive_counter, start_x \\ <span class="hljs-number">-10</span>, start_y \\ <span class="hljs-number">15</span>, x_size \\ <span class="hljs-number">60</span>,            y_size \\ <span class="hljs-number">20</span>, x_padding \\ <span class="hljs-number">5</span>, y_padding \\ <span class="hljs-number">5</span>) <span class="hljs-keyword">do</span>    end_x = start_x + x_size    end_y = start_y - y_size    x_range = start_x..end_x    y_range = start_y..end_y    <span class="hljs-keyword">for</span> y &amp;lt;- y_range, x &lt;- x_range <span class="hljs-keyword">do</span>      # draw y axis      <span class="hljs-keyword">if</span> x == start_x <span class="hljs-keyword">do</span>        (y        |&gt;; Integer.to_string        |&gt; <span class="hljs-built_in">String</span>.rjust(y_padding)) &lt;&amp;gt; <span class="hljs-string">"| "</span>        |&amp;gt; IO.write      end      IO.write(<span class="hljs-keyword">if</span> Enum.member?(cells, {x, y}), <span class="hljs-attr">do</span>: <span class="hljs-string">"O"</span>, <span class="hljs-attr">else</span>: <span class="hljs-string">","</span>)      <span class="hljs-keyword">if</span> x == end_x, <span class="hljs-attr">do</span>: IO.puts <span class="hljs-string">""</span>    end    # draw x axis    IO.write <span class="hljs-built_in">String</span>.rjust(<span class="hljs-string">"| "</span>, y_padding + <span class="hljs-number">2</span>)    x_length = (round((end_x-start_x)/<span class="hljs-number">2</span>))    <span class="hljs-keyword">for</span> x &amp;lt;- <span class="hljs-number">0.</span>.x_length, <span class="hljs-attr">do</span>: IO.write <span class="hljs-string">"_ "</span>    IO.puts <span class="hljs-string">""</span>    IO.write <span class="hljs-built_in">String</span>.rjust(<span class="hljs-string">"/  "</span>, y_padding + <span class="hljs-number">2</span>)    <span class="hljs-keyword">for</span> x &lt;- x_range <span class="hljs-keyword">do</span>      <span class="hljs-keyword">if</span> rem(x, x_padding) == <span class="hljs-number">0</span> <span class="hljs-keyword">do</span>        x        |&amp;gt; Integer.to_string        |&gt; <span class="hljs-built_in">String</span>.ljust(x_padding)        |&amp;gt; IO.write      end    end    IO.puts <span class="hljs-string">""</span>    IO.puts <span class="hljs-string">"Generation: #{generation_counter}"</span>    IO.puts <span class="hljs-string">"Alive cells: #{alive_counter}"</span>  endend
</code></pre><p>The board with the bigger visible part looks like this:</p>
<pre><code>   <span class="hljs-number">15</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">14</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">13</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">12</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">11</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">10</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">9</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">8</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">7</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">6</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">5</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">4</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">3</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">2</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">1</span>| ,,,,,,,,,,OO,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,    <span class="hljs-number">0</span>| ,,,,,,,,,,OO,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">-1</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">-2</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">-3</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">-4</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   <span class="hljs-number">-5</span>| ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,     | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _    /  <span class="hljs-number">-10</span>  <span class="hljs-number">-5</span>   <span class="hljs-number">0</span>    <span class="hljs-number">5</span>    <span class="hljs-number">10</span>   <span class="hljs-number">15</span>   <span class="hljs-number">20</span>   <span class="hljs-number">25</span>   <span class="hljs-number">30</span>   <span class="hljs-number">35</span>   <span class="hljs-number">40</span>   <span class="hljs-number">45</span>   <span class="hljs-number">50</span>Generation: <span class="hljs-number">18</span>Alive cells: <span class="hljs-number">4</span>
</code></pre><p>Last step is to uncomment the <code>GameOfLife.GamePrinter</code> worker in:</p>
<pre><code># lib/game_of_life.exdefmodule GameOfLife <span class="hljs-keyword">do</span>  use Application  # See http:<span class="hljs-comment">//elixir-lang.org/docs/stable/elixir/Application.html  # for more information on OTP Applications  def start(_type, _args) do    import Supervisor.Spec, warn: false    init_alive_cells = []    children = [      # Define workers and child supervisors to be supervised      # worker(GameOfLife.Worker, [arg1, arg2, arg3]),      supervisor(Task.Supervisor, [[name: GameOfLife.TaskSupervisor]]),      worker(GameOfLife.BoardServer, [init_alive_cells]),      # This line is uncommented now      worker(GameOfLife.GamePrinter, []),    ]    # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html    # for other strategies and supported options    opts = [strategy: :one_for_one, name: GameOfLife.Supervisor]    Supervisor.start_link(children, opts)  endend</span>
</code></pre><h3 id="heading-add-figure-patterns-and-place-them-on-the-board">Add figure patterns and place them on the board</h3>
<p>To play our game of life, it would be great to have an easy way to add figures to the board. There are many commonly known patterns like still lifes, oscillators, and spaceships. You can <a target="_blank" href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Examples_of_patterns">learn more about them here</a>.</p>
<p>One interesting pattern is the gun. The Gosper Glider Gun is a very popular pattern. Here it is how it looks:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/wxl-EjJX2Bn1aQ82Mp6p0hhFLMUnSjwpMyHy" alt="Image" width="610" height="178" loading="lazy">
<em>Gosper Glider Gun</em></p>
<p>When you run game the pattern behaves as you see. The gun is shooting.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ROo3D4AEbeI2atC5gYBi3Snfk1-TiAsDmMdk" alt="Image" width="250" height="180" loading="lazy">
<em>Gosper Glider Gun pattern live cycle</em></p>
<p>Let’s write this pattern down. Imagine you want to put the pattern in a rectangle. Left bottom corner of the rectangle is at <code>{0,0}</code> position.</p>
<pre><code># lib/game_of_life/patterns/guns.exdefmodule GameOfLife.Patterns.Guns <span class="hljs-keyword">do</span>  @moduledoc <span class="hljs-string">""</span><span class="hljs-string">"  https://en.wikipedia.org/wiki/Gun_(cellular_automaton)  "</span><span class="hljs-string">""</span>  @doc <span class="hljs-string">""</span><span class="hljs-string">"  https://en.wikipedia.org/wiki/File:Game_of_life_glider_gun.svg  "</span><span class="hljs-string">""</span>  def gosper_glider <span class="hljs-keyword">do</span>    [      {<span class="hljs-number">24</span>, <span class="hljs-number">8</span>},      {<span class="hljs-number">22</span>, <span class="hljs-number">7</span>}, {<span class="hljs-number">24</span>, <span class="hljs-number">7</span>},      {<span class="hljs-number">12</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">13</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">20</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">21</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">34</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">35</span>, <span class="hljs-number">6</span>},      {<span class="hljs-number">11</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">15</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">20</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">21</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">34</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">35</span>, <span class="hljs-number">5</span>},      {<span class="hljs-number">0</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">10</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">16</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">20</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">21</span>, <span class="hljs-number">4</span>},      {<span class="hljs-number">0</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">10</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">14</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">16</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">17</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">22</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">24</span>, <span class="hljs-number">3</span>},      {<span class="hljs-number">10</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">16</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">24</span>, <span class="hljs-number">2</span>},      {<span class="hljs-number">11</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">15</span>, <span class="hljs-number">1</span>},      {<span class="hljs-number">12</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">13</span>, <span class="hljs-number">0</span>},    ]  endend
</code></pre><p>It would be also useful if we could place the pattern on the board in the position specified by us. Let’s write a pattern converter.</p>
<pre><code># lib/game_of_life/pattern_converter.exdefmodule GameOfLife.PatternConverter <span class="hljs-keyword">do</span>  @doc <span class="hljs-string">""</span><span class="hljs-string">"  ## Example      iex&gt; GameOfLife.PatternConverter.transit([{0, 0}, {1, 3}], -1, 2)      [{-1, 2}, {0, 5}]  "</span><span class="hljs-string">""</span>  def transit([{x, y} | cells], x_padding, y_padding) <span class="hljs-keyword">do</span>    [{x + x_padding, y + y_padding} | transit(cells, x_padding, y_padding)]  end  def transit([], _x_padding, _y_padding), <span class="hljs-attr">do</span>: []end
</code></pre><p>This is the way you can add the Gosper glider pattern to the board with the specified position.</p>
<pre><code>GameOfLife.Patterns.Guns.gosper_glider|&amp;gt; GameOfLife.PatternConverter.transit(<span class="hljs-number">-2</span>, <span class="hljs-number">-3</span>)|&gt; GameOfLife.BoardServer.add_cells
</code></pre><p>You can find <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life/tree/master/lib/game_of_life/patterns">more patterns in modules here</a>.</p>
<h3 id="heading-run-game-across-multiple-nodes">Run game across multiple nodes</h3>
<p>Now it is time to run our game. The full <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life">source code can be found here</a>.</p>
<p>Let’s run the first node where the <code>GameOfLife.BoardServer</code> will be running.</p>
<pre><code>$ iex --sname node1 -S mixErlang/OTP <span class="hljs-number">18</span> [erts<span class="hljs-number">-7.3</span>] [source] [<span class="hljs-number">64</span>-bit] [smp:<span class="hljs-number">4</span>:<span class="hljs-number">4</span>] [<span class="hljs-keyword">async</span>-threads:<span class="hljs-number">10</span>] [hipe] [kernel-poll:<span class="hljs-literal">false</span>] [dtrace]Interactive Elixir (<span class="hljs-number">1.2</span><span class="hljs-number">.4</span>) - press Ctrl+C to exit (type h() ENTER <span class="hljs-keyword">for</span> help)<span class="hljs-number">16</span>:<span class="hljs-number">54</span>:<span class="hljs-number">08.554</span> [info]  Started Elixir.GameOfLife.BoardServer masteriex(node1@Artur)<span class="hljs-number">1</span>&gt; GameOfLife.BoardServer.start_game:game_startediex(node1@Artur)<span class="hljs-number">2</span>&gt; GameOfLife.GamePrinter.start_printing_board:printing_started
</code></pre><p>In another terminal window, you can start the second node. We will connect it with the first node.</p>
<pre><code>$ iex --sname node2 -S mixErlang/OTP <span class="hljs-number">18</span> [erts<span class="hljs-number">-7.3</span>] [source] [<span class="hljs-number">64</span>-bit] [smp:<span class="hljs-number">4</span>:<span class="hljs-number">4</span>] [<span class="hljs-keyword">async</span>-threads:<span class="hljs-number">10</span>] [hipe] [kernel-poll:<span class="hljs-literal">false</span>] [dtrace]Interactive Elixir (<span class="hljs-number">1.2</span><span class="hljs-number">.4</span>) - press Ctrl+C to exit (type h() ENTER <span class="hljs-keyword">for</span> help)<span class="hljs-number">16</span>:<span class="hljs-number">55</span>:<span class="hljs-number">17.395</span> [info]  Started Elixir.GameOfLife.BoardServer masteriex(node2@Artur)<span class="hljs-number">1</span>&gt; Node.connect :node1@Arturtrue16:<span class="hljs-number">55</span>:<span class="hljs-number">17.691</span> [info]  Started Elixir.GameOfLife.BoardServer slaveiex(node2@Artur)<span class="hljs-number">2</span>&gt; Node.list[:node1@Artur]iex(node2@Artur)<span class="hljs-number">3</span>&gt; Node.self:node2@Arturiex(node2@Artur)<span class="hljs-number">4</span>&gt; GameOfLife.Patterns.Guns.gosper_glider |&gt; GameOfLife.BoardServer.add_cells[{<span class="hljs-number">24</span>, <span class="hljs-number">8</span>}, {<span class="hljs-number">22</span>, <span class="hljs-number">7</span>}, {<span class="hljs-number">24</span>, <span class="hljs-number">7</span>}, {<span class="hljs-number">12</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">13</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">20</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">21</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">34</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">35</span>, <span class="hljs-number">6</span>}, {<span class="hljs-number">11</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">15</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">20</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">21</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">34</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">35</span>, <span class="hljs-number">5</span>}, {<span class="hljs-number">0</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">10</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">16</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">20</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">21</span>, <span class="hljs-number">4</span>}, {<span class="hljs-number">0</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">10</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">14</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">16</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">17</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">22</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">24</span>, <span class="hljs-number">3</span>}, {<span class="hljs-number">10</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">16</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">24</span>, <span class="hljs-number">2</span>}, {<span class="hljs-number">11</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">15</span>, <span class="hljs-number">1</span>}, {<span class="hljs-number">12</span>, <span class="hljs-number">0</span>}, {<span class="hljs-number">13</span>, <span class="hljs-number">0</span>}]
</code></pre><p>Both nodes are executing a calculation to determine a new state for living cells. You can run the game also across different servers in the network like this:</p>
<pre><code># start node1$ iex --name node1@<span class="hljs-number">192.168</span><span class="hljs-number">.0</span><span class="hljs-number">.101</span> --cookie <span class="hljs-string">"token_for_cluster"</span> -S mix# start node2 on another server$ iex --name node2@<span class="hljs-number">192.168</span><span class="hljs-number">.0</span><span class="hljs-number">.102</span> --cookie <span class="hljs-string">"token_for_cluster"</span> -S mixiex&gt; Node.connect :<span class="hljs-string">"node1@192.168.0.101"</span><span class="hljs-literal">true</span>
</code></pre><p>You already saw how the game works in the demo at the beginning of the article. You can try it on your own machine, just clone the <a target="_blank" href="https://github.com/BeyondScheme/elixir-game_of_life">repository</a>.</p>
<h3 id="heading-summary">Summary</h3>
<p>Finally, we managed to get to the end. It was a pretty long road but we have a working game, distributed across nodes. We learned how to write GenServer, use Agents, split processes across nodes with TaskSupervisor and connect nodes into the cluster. You also saw examples of tests in Elixir and how to use DocTest.</p>
<p>Hope you found something interesting in the article. Please share your thoughts in the comments.</p>
<p>Nowadays I work on CI parallelisation problem to run tests fast on CI servers. I built <a target="_blank" href="https://knapsackpro.com?utm_source=medium&amp;utm_medium=blog&amp;utm_campaign=game_of_life_elixir&amp;utm_content=knapsackpro"><strong>Knapsack Pro which splits your Ruby and JavaScript tests on parallel CI nodes to save time on testing</strong></a>. You can check one of my articles about <a target="_blank" href="https://medium.com/@arturtrzop/cypress-e2e-tests-split-with-ci-parallelisation-and-auto-balancing-ci-nodes-time-8c6c8b0a37f1">Cypress in JavaScript test suite parallelisation</a> or <a target="_blank" href="https://medium.com/datadriveninvestor/heroku-ci-parallel-test-runs-done-with-optimal-test-suite-split-how-to-run-parallel-dynos-79903d9a0ec6">Heroku CI parallelisation</a>. Let me know how slow or fast your tests are in your Elixir projects — just leave a comment. :) I’d like to add support for CI parallelisation testing into Elixir as well.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A functional approach to mergesort algorithm ]]>
                </title>
                <description>
                    <![CDATA[ By Joe Chasinga Algorithms are often difficult for people to understand. I believe that this is because they are most often programmed or explained in a language that encourages thinking in procedures or instructions which are not intuitive. Very oft... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-functional-approach-to-merge-sort-and-algorithms-in-general-bbc12457eeb0/</link>
                <guid isPermaLink="false">66c342914f7405e6476b0155</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Erlang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 11 May 2018 00:04:59 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*1AHesZT5E0EAaT7feMhbaQ.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Joe Chasinga</p>
<p>Algorithms are often difficult for people to understand. I believe that this is because they are most often programmed or explained in a language that encourages thinking in procedures or instructions which are not intuitive.</p>
<p>Very often the meat of an algorithm (how you solve a particular problem logically without computer coding) looks very simple and understandable when described graphically. Surprisingly, however, it often does not translate well into code written in languages like Python, Java, or C++. Therefore it becomes much more difficult to understand.</p>
<p><strong>In other words, the algorithmic concept doesn’t map directly to how the code should be written and read</strong>.</p>
<h3 id="heading-why-are-algorithms-so-difficult-to-code">Why are algorithms so difficult to code?</h3>
<p>Well, we could blame it on the inner workings of early electro-mechanic computers. The early inventors of some of the most used programming languages today could never get rid of those features. Or perhaps they couldn’t help leaving their fingerprints on their inventions. Once you understand computers that well, there’s no undoing that.</p>
<p>To make matters worse, on top of already micro-managing languages, somebody had to invent an API for better micro-management. They called it object-oriented programming (OOP), and added the concept of classes to programming — but I think modules and functions could handle the same things just fine, thank you very much.</p>
<p>C++ didn’t make C any better, but it did pave a way by inspiring more descendants of OOP. And all together, all these things make abstract algorithmic thinking hard for the aforementioned reasons.</p>
<h3 id="heading-the-case-study-merge-sort">The case study: merge sort</h3>
<p>For our discussion, we will use a merge sort algorithm as a specimen. Take a look at the diagram below. If you can count and put together jigsaw puzzles, then you can probably understand how it works in a few minutes.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZcTwK7oDpCLBjTjYrP-3ZlnUCSWe7EkYj7Zb" alt="Image" width="300" height="180" loading="lazy">
_By Swfung8 — Own work, CC BY-SA 3.0, [https://commons.wikimedia.org/w/index.php?curid=14961648](https://commons.wikimedia.org/w/index.php?curid=14961648" rel="noopener" target="<em>blank" title=")</em></p>
<p>The key steps of producing a merge sort are few and simple. In fact, I can explain it using my daughter’s number blocks (helpful to follow these by going back to the animated diagram for reference):</p>
<ul>
<li>First, we need to keep subdividing a list of numbers (or letters, or any type of sortable values) by half until we end up with many single-element lists. A list with one element is technically sorted. This is called trivially sorted.</li>
<li>Then, we create a new empty list in which we could start re-arranging the elements and putting them one by one according to which one is less/smaller than the other.</li>
<li>Then we need to “merge” each pair of lists back together, effectively reversing the subdivision steps. But this time, at every step of the way, we have to make sure that the smaller element in the pair in question is being put into the empty list first.</li>
</ul>
<p>For the sake of the argument, we will try to map out the above processes by making each one a subroutine (function in normal speak). The meatiest part of this algorithm is the merging, so let’s start with that first.</p>
<pre><code class="lang-ps">def merge(a, b):
    out = <span class="hljs-function">[]</span>

    <span class="hljs-keyword">while</span> (len(a) &gt; <span class="hljs-number">0</span> and len(b) &gt; <span class="hljs-number">0</span>): 
        <span class="hljs-keyword">if</span> (a[<span class="hljs-number">0</span>] &lt;= b[<span class="hljs-number">0</span>]):
            out.append(a[<span class="hljs-number">0</span>])
            <span class="hljs-built_in">del</span> a[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">else</span>:
            out.append(b[<span class="hljs-number">0</span>])
            <span class="hljs-built_in">del</span> b<span class="hljs-function">[<span class="hljs-number">0</span>]</span>

    <span class="hljs-keyword">while</span> (len(a) &gt; <span class="hljs-number">0</span>):
        out.append(a[<span class="hljs-number">0</span>])
        <span class="hljs-built_in">del</span> a<span class="hljs-function">[<span class="hljs-number">0</span>]</span>
    <span class="hljs-keyword">while</span> (len(b) &gt; <span class="hljs-number">0</span>):
        out.append(b[<span class="hljs-number">0</span>])
        <span class="hljs-built_in">del</span> b[<span class="hljs-number">0</span>]

    <span class="hljs-keyword">return</span> out
</code></pre>
<p>Go on and spend some time looking it over. You might notice that with imperative Python code, it is designed to be spoken out and then understood. It is very understandable in English, but not in logic.</p>
<h4 id="heading-our-first-attempt">Our first attempt</h4>
<p>Here is one attempt (that you could possibly use in a whiteboarding session):</p>
<p>To merge list <code>a</code> and <code>b</code>, we’ll have to first create an empty list named <code>out</code> for clarity (because in Python we can’t be sure it will really be “out” in the end). Then, as long as (or while) both lists are not empty, we’ll keep putting the head of both lists to a fight-off. Whichever is less than or equal to the opponent wins and gets to enter <code>out</code> first. The loser will have to stay and wait there for the new contestant down the line. The rematches continue on until the first <code>while</code> loop breaks.</p>
<p>Now, at some point either <code>a</code> or <code>b</code> will be empty, leaving the other with one or more elements hanging. Without any contestants left in the other list, the two <code>while</code> loops make sure to fast track those poor elements into <code>out</code> so both list are exhausted. Then, when that’s all done, we return <code>out</code>.</p>
<p>And this is the test cases for merge:</p>
<pre><code class="lang-py"><span class="hljs-keyword">assert</span>(merge([<span class="hljs-number">1</span>], [<span class="hljs-number">2</span>]) == [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>])
<span class="hljs-keyword">assert</span>(merge([<span class="hljs-number">2</span>], [<span class="hljs-number">1</span>]) == [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>])
<span class="hljs-keyword">assert</span>(merge([<span class="hljs-number">4</span>, <span class="hljs-number">1</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>]) == [<span class="hljs-number">3</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>])
</code></pre>
<p>I hope at this point it is clear to you why we end up with the result in the last case. If it isn’t, try drawing on a whiteboard or a piece of paper and simulating the explanation.</p>
<h4 id="heading-divide-and-conquer">Divide and Conquer</h4>
<p>Now we will carry on with the subdivision part. This process is also known as partitioning or, in somewhat grander language, <a target="_blank" href="https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm">Divide and Conquer</a> (by the way, <a target="_blank" href="https://en.wikipedia.org/wiki/Divide_and_rule">the definition in politics is equally interesting</a>).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/7r1BOCtjx7Z261gFldhvdk6sxqLYy0xGpe57" alt="Image" width="416" height="396" loading="lazy">
<em>Gold Medallion of Philip II of Macedonia who is said to have coined the maxim divide et impera (divide and conquer). Bibliothèque nationale de France, Paris</em></p>
<p>Basically, if anything is hard to conquer or understand, you should break it down until it becomes smaller and more easily understood. Do that until the parts are unbreakable and repeat the process with the rest.</p>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">half</span>(<span class="hljs-params">arr</span>):</span>
    mid = len(arr) / <span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> arr[:mid], arr[mid:]
</code></pre>
<p>What the <code>half</code> routine does is find the middle index, slice the input list into roughly equal sublists, and return both as a pair. It only needs to do this once, since the parent function will eventually call it recursively.</p>
<p>Since we have the pieces, now we just need to put them together into a coherent scheme. This is where the water gets murky, because recursions are involved.</p>
<p>Before going into more code, let me explain why recursions and imperative programming languages like Python do not fit together so well. I won’t go into the topic of optimization, because that does not concern today’s discussion and is not as interesting.</p>
<p>One distinct irony here is that, even in a language with iterative looping like Python, it still cannot entirely avoid recursion (it might get away without recursion, but I’m sure that would make it even more bizarre). Recursion is a territory where iterative constructs, such as for and while loops, become utterly useless.</p>
<p>Moreover, recursion is not natural in Python. It does not feel natural and transparent, but rather feels quite half-baked the way its lambda is. An attempt at voicing over recursions in Python would be like, “then we do this recursively and just pray it all works out and hits the base case in the end so it doesn’t spiral into the infinite darkness of stack overflow.” Wow, right?</p>
<p>So here is the <code>mergesort</code> function:</p>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mergesort</span>(<span class="hljs-params">arr</span>):</span>

    <span class="hljs-keyword">if</span> (len(arr) &lt;= <span class="hljs-number">1</span>):
        <span class="hljs-keyword">return</span> arr

    left, right = half(arr)
    L = mergesort(left)
    R = mergesort(right)

    <span class="hljs-keyword">return</span> merge(L, R)
</code></pre>
<p>Apparently, this is really clean and easy to read. But it isn’t clear what happens after the call to <code>half</code> , at least semantically. Because of this “non-nativity” to recursion, recursive calls are very opaque and obstructive to educational endeavors.</p>
<p>The only way to visualize this mergesort process is probably to track the changes in the sublists in every step:</p>
<pre><code>input: [<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>]
A alias <span class="hljs-keyword">for</span> mergesort / half
B alias <span class="hljs-keyword">for</span> merge

## subdividing by half ...

                 A([<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>])
              A([<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>])    A([<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>])
          A([<span class="hljs-number">0</span>])  A([<span class="hljs-number">3</span>, <span class="hljs-number">1</span>])  A([<span class="hljs-number">3</span>, <span class="hljs-number">2</span>])   A([<span class="hljs-number">6</span>, <span class="hljs-number">5</span>])
    A([]) A([<span class="hljs-number">0</span>]) A([<span class="hljs-number">3</span>])  A([<span class="hljs-number">1</span>]) A([<span class="hljs-number">3</span>]) A([<span class="hljs-number">2</span>]) A([<span class="hljs-number">6</span>]) A([<span class="hljs-number">5</span>]) 

## base <span class="hljs-keyword">case</span> reached, start merging ...

       B([], [<span class="hljs-number">0</span>]) B([<span class="hljs-number">3</span>], [<span class="hljs-number">1</span>]) B([<span class="hljs-number">3</span>], [<span class="hljs-number">2</span>]) B([<span class="hljs-number">6</span>], [<span class="hljs-number">5</span>])
          B([<span class="hljs-number">0</span>], [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>])         B([<span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>])
                B([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>])
                 B([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>])

<span class="hljs-attr">output</span>: [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
</code></pre><p>On an asymptotic side note, dividing and conquering almost always incurs a logarithmic runtime. When you keep dividing a collection into <code>N</code> sub-collections, whether it contains 10 or 100,000,000 items, the number of steps taken in the latter case increases at the rate of log base <code>N</code>.</p>
<p>For instance, it takes about 3 steps to keep dividing 10 by 2 until it gets as close to 1 as it can (or exactly 3 steps to reach 1 in integer division). But it takes only about 26 steps to do the same and divide 100,000,000 by 2 until you reach 1. This fact can be expressed as follows:</p>
<pre><code><span class="hljs-number">2</span>^<span class="hljs-number">3.321928</span> = <span class="hljs-number">10</span>
<span class="hljs-number">2</span>^<span class="hljs-number">6.643856</span> = <span class="hljs-number">100</span>

...

<span class="hljs-number">2</span>^<span class="hljs-number">26.575425</span> = <span class="hljs-number">100000000</span>

or 

log base <span class="hljs-number">2</span> <span class="hljs-keyword">of</span> <span class="hljs-number">100000000</span> = <span class="hljs-number">26.575425</span>
</code></pre><p>The takeaway here is that we had to visualize the recursive processes in order to understand the inner workings of the algorithm — even though it looked so trivial in the animated diagram.</p>
<p><strong>Why is there a divide between the conceptual processes of the algorithm itself and the code that instructs the computer to compute such processes?</strong></p>
<p>It’s because in a way, by using imperative languages, we are in fact still mentally enslaved by the machines.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/NEuX4NWEDEEpa2TikKqjT2ABx5kj8tPZk8A5" alt="Image" width="800" height="417" loading="lazy">
<em>Not quite like this, but you get the point.</em></p>
<h3 id="heading-diving-deeper-into-the-code">Diving deeper into the code</h3>
<blockquote>
<p>“There’s a difference between knowing the path and walking the path.”<br>― <a target="_blank" href="https://www.goodreads.com/author/show/7392901.Morpheus_The_Matrix">Morpheus, The Matrix</a></p>
</blockquote>
<p>Programming is hard, we all know that. And understanding programming in a really deep way is even harder on your soul (and your career). But I would argue that, like Morpheus said, sometimes walking the path is all that matters. Being able to see clearly is one of most rewarding things in programming.</p>
<p>In functional programming, the programmer (you) gets the front seat in seeing how data change recursively. This means that you have the ability to decide how the data of a certain form should be transformed to the data of another based on the snapshot of how it looks. This isn’t unlike how we have visualized the mergesort process. Let me give you a preview.</p>
<p>Let’s say you want to create a base case in Python. In it, you want to return the list in question when it has only one element, and an empty list when there’s two elements. So you’d need to write something like this:</p>
<pre><code class="lang-py"><span class="hljs-keyword">if</span> (len(arr) == <span class="hljs-number">1</span>):
    <span class="hljs-keyword">return</span> arr
<span class="hljs-keyword">elif</span> (len(arr) == <span class="hljs-number">2</span>):
    <span class="hljs-keyword">return</span> []
</code></pre>
<p>Or to make this worse but more interesting, you could try to access the first element by index 0 and the second element by index 1 and get ready to handle <code>IndexError</code> exception.</p>
<p>In a functional language like Erlang — which is what I’ll be using in this article for its dynamic type system like Python — you more or less would do something like this:</p>
<pre><code><span class="hljs-keyword">case</span> Arr <span class="hljs-keyword">of</span>
  [_] -&gt; Arr;
  [_,_] -&gt; []
end.
</code></pre><p>This gives you a clearer view of the state of the data. Once it’s trained enough, it requires much less cognitive power to read and comprehend what the code does than <code>len(arr)</code> . Just keep in mind: a programmer who doesn’t speak English might ask, “what is len?” Then you get distracted by the literal meaning of the function instead of the value of that expression.</p>
<p>However, this comes with a price: you don’t have the luxury of a looping construct. A language like Erlang is recursion-native. Almost every meaningful Erlang program will make use of rigorous recursive function calls. And that’s why it is mapped more closely to the algorithmic concepts which usually consist of recursion.</p>
<p>Let’s try to retrace our steps in producing mergesort, but this time in Erlang, starting with the <code>merge</code> function.</p>
<pre><code>merge([], [], Acc) -&gt; Acc;
merge([], [H | T], Acc) -&gt; [H | merge([], T, Acc)];
merge([H | T], [], Acc) -&gt; [H | merge(T, [], Acc)];
merge([Ha | Ta], [Hb | Tb], Acc) -&gt;
  <span class="hljs-keyword">case</span> Ha =&lt; Hb <span class="hljs-keyword">of</span>
    <span class="hljs-literal">true</span>  -&gt; [Ha | merge(Ta, [Hb | Tb], Acc)];
    <span class="hljs-literal">false</span> -&gt; [Hb | merge([Ha | Ta], Tb, Acc)]
  end.
</code></pre><p>What an abomination! Definitely not an improvement in terms of readability, you think. Yes, Erlang admittedly won’t win any prizes for beautiful language. In fact, many functional languages can look like gibberish to the untrained eyes.</p>
<p>But let’s give it a chance. We will go through each step like we did before, and perhaps in the end some of us will see the light. But before we go on, for those of you who are not familiar with Erlang, these are some points worth noting:</p>
<ul>
<li>Each block of <code>merge</code> is considered a function clause of the same function. They are separated by <code>;</code>. When an expression ends in Erlang, it ends with a period (<code>.</code>). It’s a convention to separate a function into several clauses for different cases. For instance, <code>merge([], [], Acc) -&gt; A</code>cc; clause maps the case where the first two arguments are empty lists to the value of the last argument.</li>
<li>Arity plays an important role in Erlang. Two functions with the same name and arity are considered the same function. Otherwise, they aren’t. For example, <code>merge/1</code> and <code>merge/3</code> (how functions and their arity are addressed in Erlang) are two different functions.</li>
<li>Erlang uses rigorous <a target="_blank" href="https://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a> (This is used in many other functional languages, but especially in Erlang). Since values in pure functional languages are immutable, it is safe to bind variables in a similar shape of data to the existing one with a matched shape. Here is a trivial example:</li>
</ul>
<pre><code>{X, Y} = {<span class="hljs-number">0.5</span>, <span class="hljs-number">0.13</span>}.
X.  %% <span class="hljs-number">0.5</span>
Y.  %% <span class="hljs-number">0.13</span>

[A, B, C | _] = [alice, jane, bob, kent, ollie].
[A, B, C].  %% [alice, jane, bob]
</code></pre><ul>
<li>Note that we will seldom talk about returning values when we work with Erlang functions, because they don’t really “return” anything per se. It maps an input value to a new value. This isn’t the same as outputting or returning it from the function. The function application itself <strong>is</strong> the value. For instance, if <code>Add(N1, N2) -&gt; N1+</code>N2<code>., Add(1,</code> 2) is 3. There’s no way for it to return anything other than 3, hence we can say it is 3. This is why you could easily <code>do add_one = add</code>(1) and th<code>en add_one</code>(2) is <code>3, add_one</code>(5) is 6, and so on.</li>
</ul>
<p>For those who are interested, see <a target="_blank" href="https://stackoverflow.com/questions/210835/what-is-referential-transparency">referential transparency</a>. To make this point clearer and risking redundancy, here is something to think about:</p>
<blockquote>
<p>when <code>f(x)</code> is a function with one arity, and the mapping is <code>f(x) -&gt;</code>; x , then it's conclusive th<code>at f(1) -</code>&amp;g<code>t; 1, f(2</code>) <code>-&gt; 2, f(3.1416)</code> -&gt; <code>3.1416, and f("fo</code>o") -&gt; "foo".  </p>
<p>This may look like a no-brainer, but in an impure function there's no such guaranteed mapping:  </p>
<p><code>a = 1</code><br><code>def add_to_a(b):</code><br> <code>return b + a</code>  </p>
<p>Now <code>a</code> might as well be anything before <code>add_to_a</code> gets called. Thus in Python, you could write a pure version of the above as:  </p>
<p><code>def add(a, b):</code><br> <code>return a + b</code><br>or <code>lambda a, b: a + b</code> .</p>
</blockquote>
<p>Now it’s time to bumble into the unknown.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Vg7C4II-2IY3Jx58NEN-nzHtSmVS9FwmWk6L" alt="Image" width="511" height="424" loading="lazy">
<em>That’s what Frank O. Gehry said.</em></p>
<h4 id="heading-forging-ahead-with-erlang">Forging ahead with Erlang</h4>
<pre><code>merge([], [], Acc) -&gt; Acc;
</code></pre><p>The first clause of the <code>merge/3</code> function means that when the first two arguments are empty lists, map the entire expression to (or “return”) the third argument <code>Acc</code>.</p>
<p>Interestingly, in a pure function, there’s no way of retaining and mutating state outside of itself. We can only work with what we have received as inputs into the function, transform it, then feed the new state into another function’s argument (most often this is another recursive call to itself).</p>
<p>Here, <code>Acc</code> stands for accumulator, which you can think of as a state container. In the case of <code>merge/3</code>, <code>Acc</code> is a list that starts empty. But as the recursive calls get on, it accumulates values from the first two lists using the logic we program (which we will talk about next).</p>
<p>This process of exhausting a value to build up another value is collectively known as reduction. Therefore, in this case it we can conclude that since the first two lists are exhausted (empty), <code>Acc</code> must be ripe for pick up.</p>
<pre><code>merge([], [H | T], Acc) -&gt; [H | merge([], T, Acc)];
</code></pre><p>The second clause matches the case when the first list is already empty, but there’s still at least one more element in the second list. <code>[H | T]</code> means a list has a head element <code>H</code> which <a target="_blank" href="https://en.wikipedia.org/wiki/Cons#Lists">cons onto another list</a> <code>T</code>. In Erlang, a list is a linked list, and the head has a pointer to the rest of the list. So a list of <code>[1, 2, 3, 4]</code> can be thought of as:</p>
<pre><code>%% match A, B, C, and D to <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, and <span class="hljs-number">4</span>, respectively

[A | [B | [C | [D | []]]]] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>].
</code></pre><p>In this case, as you can see in the conning example, <code>T</code> can just be an empty tail list. So in this second case, we map it to a value of a new list in which the <code>H</code> element of the second list is conned onto the recursive result of calling <code>merge/3</code> when <code>T</code> is the second argument.</p>
<pre><code>merge([H | T], [], Acc) -&gt; [H | merge(T, [], Acc)];
</code></pre><p>The third case is just a flip side of the second case. It matches the case when the first list is not empty, but the second is. This clause maps to a value in a similar pattern, except it calls <code>merge/3</code> with the tail of the first list as the first argument and keeps the second list empty.</p>
<pre><code>merge([Ha | Ta], [Hb | Tb], Acc) -&gt;
  <span class="hljs-keyword">case</span> Ha =&lt; Hb <span class="hljs-keyword">of</span>
    <span class="hljs-literal">true</span>  -&gt; [Ha | merge(Ta, [Hb | Tb], Acc)];
    <span class="hljs-literal">false</span> -&gt; [Hb | merge([Ha | Ta], Tb, Acc)]
  end.
</code></pre><p>Let’s begin with the meat of <code>merge/3</code> first. This clause matches the case when the first and second arguments are non-empty lists. In this case, we enter a <code>case … of</code> clause (equivalent to switch case in other languages) to test if the head element of the first list (<code>Ha</code>) is less than or equal to the head element of the second list (<code>Hb</code>).</p>
<p>If that is true, we con <code>Ha</code> onto the resulting list of the next recursive call to merge with the tail list of the previous first list (<code>Ta</code>) as the new first argument. We keep the second and third arguments the same.</p>
<p>These clauses constitute to a single function, <code>merge/3</code>. You can imagine that it could have been a single function clause. We could use complex case … of and/or if conditional plus pattern-matching to weed out each case and map it to the right result. That would have made it more chaotic, when you can easily read each case the function is matching quite nicely on separate lines.</p>
<p>However, things got a little hairy for the subdividing operation, which needs two functions: <code>half/1</code> and <code>half/3</code>.</p>
<pre><code>half([]) -&gt; {[], []};
half([X]) -&gt; {[X], []};
half([X,Y]) -&gt; {[X], [Y]};
half(L) -&gt;
  Len = length(L),
  half(L, {<span class="hljs-number">0</span>, Len}, {[], []}).

half([], _, {Acc1, Acc2}) -&gt;
  {<span class="hljs-attr">lists</span>:reverse(Acc1), <span class="hljs-attr">lists</span>:reverse(Acc2)};
half([X], _, {Acc1, Acc2}) -&gt;
  {<span class="hljs-attr">lists</span>:reverse(Acc1), <span class="hljs-attr">lists</span>:reverse([X | Acc2])};
half([H|T], {Cnt, Len}, {Acc1, Acc2}) -&gt;
  <span class="hljs-keyword">case</span> Cnt &gt;= (Len div <span class="hljs-number">2</span>) <span class="hljs-keyword">of</span>
      <span class="hljs-literal">true</span> -&gt; half(T, {Cnt + <span class="hljs-number">1</span>, Len}, {Acc1, [H|Acc2]});
      <span class="hljs-literal">false</span> -&gt; half(T, {Cnt + <span class="hljs-number">1</span>, Len}, {[H|Acc1], Acc2})
  end.
</code></pre><p>This is where you’ll miss Python and its destructive nature. In a pure functional language, lists are linked lists. When you work with them, there’s no looking back. There’s no logic that says “I want to divide a list in half, so I’m going to get the middle index, and slice it into two <em>left</em> and <em>right</em> portions.”</p>
<p>If your mind is set in working with linked lists, you’re more along the lines of “I can only go forward through the list, working with a few elements at a time. I need to create two empty lists and keep count of how many items I’ve retrieve from the source list and put into the first one so I know when it’s time to switch to another bucket. All the aforementioned needs to be passed in as arguments in the recursive calls.” Whew!</p>
<p>In other words, cutting a list in half can be compared to chopping a block of cheese with a knife in the middle of it. On the other hand, a functional comparison for doing so is like pouring coffee into two cups equally — you just need to know when it’s time to stop pouring into the first one and move on to the second one.</p>
<p>The <code>half/1</code> function, although it isn’t really necessary, is there for convenience.</p>
<pre><code>half([]) -&gt; {[], []};
half([X]) -&gt; {[X], []};
half([X,Y]) -&gt; {[X], [Y]};
half(L) -&gt;
  Len = length(L),
  half(L, {<span class="hljs-number">0</span>, Len}, {[], []}).
</code></pre><p>By now, you should get the sense of what each Erlang function clause is doing. The new bracket pairs here represent tuples in Erlang. Yes, we are returning a left and right value pair, like in the Python version. The <code>half/1</code> function is here to handle simple, explicit base cases which don’t warrant the worthiness of passing in other arguments.</p>
<p>However, take note of the last case when the argument has a list with more than two elements. (Note: those with less than or equal to two elements are already handled by the first three clauses.) It simply computes the following:</p>
<ul>
<li>the length of the list <code>L</code> and calls <code>half/3</code> with <code>L</code> as the first argument</li>
<li>a pair of counter variables and list’s length, which will be used to signal the switching from list one to list two</li>
<li>and of course, a pair of empty lists to fill the elements from <code>L</code> in.</li>
</ul>
<pre><code>half([], _, {Acc1, Acc2}) -&gt;
  {<span class="hljs-attr">lists</span>:reverse(Acc1), <span class="hljs-attr">lists</span>:reverse(Acc2)};
</code></pre><p><code>half/3</code> looks like a mess, but only to the untrained eyes. The first clause matches a pattern when the source list is drained. In this case, the second pair of counter and length won’t matter since it’s already the end. We simply know that <code>Acc1</code> and <code>Acc2</code> are ripe for yielding. But wait, what’s with the reversing of both?</p>
<p>Appending an element to a linked list is a very slow operation. It runs O(N) times for every append, because it needs to create a new list, copy the existing one onto it, and create a pointer to the new element and assign it to the last element. It’s like redoing the whole list. Couple this with recursions and you are bound for disaster.</p>
<p>The only good way to add something to a linked list is to prepend it at the head. Then all it needs to do is create a memory for that new value and give it a reference to the head of the linked list. A simple O(1) operation. So even though we could concatenate lists using <code>++</code> like <code>[1, 2, 3] ++ [4]</code>, we rarely want to do it this way, especially with recursions.</p>
<p>The technique here is to reverse the source list first, then con an element onto it like <code>[4 | [3, 2, 1]]</code> , and reverse them again to get the right result. This may sound terrible, but reversing a list and reversing it back is an O(2N) operation, which is O(N). But in between, conning elements onto the list takes only O(1), so it basically costs no extra runtime.</p>
<pre><code>half([H|T], {Cnt, Len}, {Acc1, Acc2}) -&gt;
  <span class="hljs-keyword">case</span> Cnt &gt;= (Len div <span class="hljs-number">2</span>) <span class="hljs-keyword">of</span>
      <span class="hljs-literal">true</span> -&gt; half(T, {Cnt + <span class="hljs-number">1</span>, Len}, {Acc1, [H|Acc2]});
      <span class="hljs-literal">false</span> -&gt; half(T, {Cnt + <span class="hljs-number">1</span>, Len}, {[H|Acc1], Acc2})
  end.
</code></pre><p>Getting back to <code>half/3</code>. The second clause, the meat of the function, does exactly the same thing as the coffee pouring metaphor we visited earlier. Since the source list is still “emitting” data, we want to keep track of the time we have been pouring values from it into the first coffee cup <code>Acc1</code>.</p>
<p>Remember that in <code>half/1</code>’s last clause, we calculated the length of the original list? That is the Len variable here, and it stays the same throughout all the calls. It’s there so that we can compare <code>Cnt</code> counter to it divided by 2 to see if we have come to the middle of the source list and should switch to filling up <code>Acc2</code> . That is where the <code>case … of</code> comes in.</p>
<p>Now, let’s put them all together in <code>mergesort/1</code> . This should be as simple as the Python version, and can be easily compared.</p>
<pre><code>mergesort([A]) -&gt; [A];
mergesort([A, B]) -&gt;
  <span class="hljs-keyword">case</span> A =&lt; B <span class="hljs-keyword">of</span>
      <span class="hljs-literal">true</span> -&gt; [A,B];
      <span class="hljs-literal">false</span> -&gt; [B,A]
  end;
mergesort(L) -&gt;
  {Left, Right} = half(L),
  merge(mergesort(Left), mergesort(Right), []).
</code></pre><h4 id="heading-thats-it">That’s it!</h4>
<p>At this point, either you think this is a novel and useful way of thinking about a problem, or you find it just plain confusing. But I hope you got something out of this programming approach that helps shine new light on how we can think about algorithms.</p>
<h4 id="heading-update"><strong>Update</strong></h4>
<p>The Python implementation of <code>merge</code> function isn’t efficient because in each <code>while</code> loop the first element in the list is removed. Although this is a common pattern in functional languages like Erlang, in Python it is very costly to remove or insert an element anywhere other than the last position because unlike a list in Erlang which is a linked list which is very efficient to remove or add element at the head of the list, Python list behaves like an array which has to reposition all other elements when one is removed or added, incurring a O(n) runtime.</p>
<p>The better way is to sacrifice little space to define a counter variable for each list which can be incremented and used to access the current element of the source list without the need to remove the top-most element at all.</p>
<pre><code>def merge(a, b):
    out = []

    ai = <span class="hljs-number">0</span>
    bi = <span class="hljs-number">0</span>

    <span class="hljs-keyword">while</span> (ai &lt;= len(a) - <span class="hljs-number">1</span> and bi &lt;= len(b) - <span class="hljs-number">1</span>): 
        <span class="hljs-keyword">if</span> (a[ai] &lt;= b[bi]):
            out.append(a[ai])
            ai += <span class="hljs-number">1</span>
        <span class="hljs-attr">else</span>:
            out.append(b[bi])            
            bi += <span class="hljs-number">1</span>

    <span class="hljs-keyword">while</span> (ai &lt;= len(a) - <span class="hljs-number">1</span>):
        out.append(a[ai])
        ai += <span class="hljs-number">1</span>

    <span class="hljs-keyword">while</span> (bi &lt;= len(b) - <span class="hljs-number">1</span>):
        out.append(b[bi])
        bi += <span class="hljs-number">1</span>

    <span class="hljs-keyword">return</span> out
</code></pre> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Elixir: A Big-Picture Programming Language ]]>
                </title>
                <description>
                    <![CDATA[ By CityBase Elixir makes programmers better at their work, and it makes their work better About a year ago, I decided to pursue the chance to work with Elixir full time as lead engineer at CityBase. Since I began using the programming language in 201... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/elixir-a-big-picture-programming-language-755dcef2fa6a/</link>
                <guid isPermaLink="false">66c349b54f7405e6476b019f</guid>
                
                    <category>
                        <![CDATA[ Elixir ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Erlang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 22 Jan 2018 16:40:02 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*tLIXa6jWWjxfB-6AYjm2Hg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By CityBase</p>
<h4 id="heading-elixir-makes-programmers-better-at-their-work-and-it-makes-their-work-better">Elixir makes programmers better at their work, and it makes their work better</h4>
<p>About a year ago, I decided to pursue the chance to work with Elixir full time as lead engineer at CityBase. Since I began using the programming language in 2014, my goal has been to use, grow, and learn more from Elixir.</p>
<p>CityBase attracted me for other reasons, too. I’ve always been curious about making complex systems work better. With government technology, we have the challenge to make some of the most complex systems work more effectively for people on a massive scale, to massive impact.</p>
<p>These objectives — growing Elixir and coding for large-scale impact — are in my opinion the same. I really believe that today, reliability, concurrency, and fault tolerance are foundational qualities that most applications should be built on. Elixir can help with that based on a battle-proven list of applications and concepts.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/UtGCPFkJSMeNlcix48URAs-F-7-YIhJyx8mf" alt="Image" width="800" height="599" loading="lazy">
_(Photo: [Unsplash](https://unsplash.com/photos/w7ZyuGYNpRQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;Kevin, &lt;a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title="))</em></p>
<h3 id="heading-a-new-language-with-tested-roots">A New Language with Tested Roots</h3>
<p>Elixir is a new language created in 2011. It’s built with the principles of Erlang, a system developed in 1986 for the telecom industry. Erlang is the reason your phone is never temporarily shut down for maintenance. It’s responsible for hardware flexibility and scalability, so you can replace a phone and have your account work the same, and add new phone lines without affecting performance.</p>
<p>Even though Elixir is relatively young, it relies on Erlang’s proven virtual machine (VM), called BEAM, and its principles of high availability, adaptability, and scalability. These features are exceptionally important in govtech applications, where the fundamental services delivered by technology must be available to everyone.</p>
<h3 id="heading-the-programmers-programing-language">The Programmer’s Programing Language</h3>
<p>Engineers like me are excited to work with Elixir because it helps us be better at our jobs. To code with Elixir, developers need to be in tune with overall business objectives, and code with the future flexibility in mind.</p>
<p>It includes tools that encourage programmers to plan around what can go wrong, and focus on getting as close as possible to the ideal outcome for the end user.</p>
<p><strong>Having programmers who understand the desired big-picture outcomes can be a game changer.</strong></p>
<p>If you ask someone to write code that performs a certain function, they’ll write that code. But if you ask them to write code that leads to an experience or solves a problem, they may think of a solution you never considered — and foresee problems you didn’t know existed.</p>
<p>Elixir encourages this kind of big-picture thinking in its DNA. A shared characteristic of Elixir and Erlang is that they are holistic programming languages. You could easily use Elixir to develop just one service, but it is optimized for developing large systems of many services.</p>
<h3 id="heading-a-language-thats-fault-tolerant">A Language That’s Fault-Tolerant</h3>
<p>Like death and taxes, another certainty in life is that things will go wrong.</p>
<p>Elixir has native fault tolerance for the two major types of programming errors.</p>
<h4 id="heading-error-type-1"><strong>Error Type 1</strong></h4>
<p>The rarest issues are usually discovered in production and are by definition harder to test for. For instance, connectivity (when a service goes down or is taking longer than expected) between a third-party service or a system resource, such as a database.</p>
<p>To be fault-tolerant to these issues, your system must always be available to customers by using at least two servers. This is to address hardware issues, network problems, or other errors that live outside your program.</p>
<p>Elixir runs on Erlang’s BEAM VM, which is configured as a mini OS on top of the server OS. The VM is responsible for the communication between servers and nodes. A node will be notified when another node is down, and the system will act in response.</p>
<h4 id="heading-error-type-2"><strong>Error Type 2</strong></h4>
<p>Issues associated with data are easier to test and can be reproduced locally. For example, if a function that does any math calculation receives a string instead of a number, that function will fail.</p>
<p>For a program to be fault-tolerant here, your system must be able to “heal” itself during errors stemming from logic bugs, wrong input data, and other internal failures.</p>
<p>As Elixir is a compiled language, any mistakes in the code prevent the application from starting. This ensures that running applications at least have a valid starting state.</p>
<p>For this to work smoothly, the Erlang VM uses something called the supervision principle, which goes like this:</p>
<ul>
<li>Processes are structured based on the idea that there are both “worker” and “supervisor” modules built into a given program.</li>
<li>Workers perform computations, and supervisors monitor workers.</li>
<li>If something goes wrong, a supervisor can restart a worker to its initial valid state.</li>
</ul>
<p>The supervision principle is associated with process isolation, when one module can run in one isolated process. This ensures that errors in one module will not affect other parts of the application, and you can restart that module in isolation as well.</p>
<h3 id="heading-a-language-thats-modular-and-built-to-scale">A Language That’s Modular and Built to Scale</h3>
<p>Elixir is a modular language, meaning that you can modify self-contained parts without worrying about impacting other, unrelated parts. Microservices function concurrently. These code-based actions all play roles in the greater program you’ve created, but tasks are distributed so that they are not dependent on one another to work. This reinforces the benefits of failing fast — you take one faulty player out, and the game still continues.</p>
<p>This also becomes crucial as a codebase grows: in non-modular systems, it’s not always clear when one part impacts others — or which other parts it might impact. This means that even the smallest change requires that you test everything to ensure that the change didn’t break anything. This makes for a daunting amount of work, which means projects move slowly and require lots of people.</p>
<p>It also means that training new developers is difficult and time-consuming, as they must familiarize themselves with a complex code legacy in order to effectively expand it.</p>
<p>With Elixir, <strong>developers focus on the future, and ensure they’re coding for new or evolving goals</strong>, rather than a previous vision that’s baked into overly complex code.</p>
<p>Beyond its modularity, Elixir is also highly scalable. The language enables you to start building an application running only one or two servers and to add more as needed. Together, the servers function as part of a cluster in a distributed system to achieve high availability and scalability.</p>
<p>Within that cluster, servers communicate using an Erlang-based protocol, rather than having to implement or use any application protocol like HTTP, and pick a data serialization/deserialization option like JSON or Protocol Buffers. That means you don’t need to implement anything to pass data between services in different servers/nodes. This is huge in terms of complexity of logic for communication.</p>
<h3 id="heading-a-language-that-has-no-niche">A Language That Has No Niche</h3>
<p>Obviously, I’m a fan of Elixir. It’s got a lot going for it, from its proven infrastructure to its scalability. But maybe the coolest thing about this language is that it’s industry agnostic. Already, it’s been adopted by a range of companies, for a variety of purposes: WhatsApp, Bleacher Report, Netflix, Pinterest, Postmates, and a handful of .gov sites all use Elixir or Erlang.</p>
<p>This is a plus for several reasons: first, it means that the language is likely to continue to grow in popularity as companies recognize the benefits it can offer. That, in turn, means that developers will continue to learn it, which means there’s not likely to be a shortage of developers who know Elixir. Companies of all sizes should be able to find developers at all levels to work with Elixir.</p>
<p>Given the power this language has to improve user experience, minimize downtime, and make life easier for dev teams, these are indicators everyone should be cheering — especially those of us in engineering and programming fields.</p>
<p>For those of us in govtech, Elixir is especially promising, as it embodies the kind of resilience and long-term focus essential to making governments function better for everyone.</p>
<p>• • •</p>
<p>By <a target="_blank" href="http://pedroassumpcao.ghost.io/">Pedro Assumpcao</a>, Lead Software Engineer at CityBase</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Long Should I Make My API Key? ]]>
                </title>
                <description>
                    <![CDATA[ By Sam Corcos Calculating collision probabilities of hashed values Say you built an API that generates public keys, and these keys all need to be unique and hard to guess. The most common way to do this is to use a hash function to generate a random... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-long-should-i-make-my-api-key-833ebf2dc26f/</link>
                <guid isPermaLink="false">66c34e7130aba6677fb9f9ff</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Elixir ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Erlang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 20 Aug 2016 11:04:45 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*BbHKX6Db55smgYEUJj-qZg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sam Corcos</p>
<h4 id="heading-calculating-collision-probabilities-of-hashed-values">Calculating collision probabilities of hashed values</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*BbHKX6Db55smgYEUJj-qZg.png" alt="Image" width="800" height="442" loading="lazy"></p>
<p>Say you built an API that generates public keys, and these keys all need to be unique and hard to guess. The most common way to do this is to use a hash function to generate a random series of numbers and letters. A typical hash looks something like the text below.</p>
<blockquote>
<p><em>AFGG2piXh0ht6dmXUxqv4nA1PU120r0yMAQhuc13i8</em></p>
</blockquote>
<p>A question that often comes up is, “How long does my hash need to be in order to ensure uniqueness?” Most people assume this is a difficult calculation. So they default to some very large number, like a 50-digit hash. The equation to approximate collision probability is actually quite simple.</p>
<h3 id="heading-how-do-i-calculate">How do I calculate?</h3>
<p>Let’s assume you’re using a good cryptographic algorithm (i.e. <a target="_blank" href="https://medium.com/@betable/tifu-by-using-math-random-f1c308c4fd9d#.1ypwox7l4">not JavaScript’s Math.random</a>). Every language has a decent crypto package for generating random hashes. With Phoenix, you can use the Erlang <strong>:crypto</strong> package.</p>
<p>There are only two pieces of information you need to do the calculation:</p>
<ol>
<li>How many possible unique hash values can you create with the given inputs? We’ll assign this to the variable <em>N.</em></li>
<li>How many values could you possibly need to generate in the lifetime of your project? We’ll assign this to the variable <em>k.</em></li>
</ol>
<p>To calculate the first value, add up all the possible characters that can go into your hash. Raise it to the power of the length of your hash.</p>
<p>So for example, if your hash value contains numbers, lowercase, and uppercase letters, that adds up to 62 total characters (10 + 26 + 26) that we can use. If we are generating a hash of only 3 characters in length, then:</p>
<p><em>N</em> = 62³ = <strong>238,328</strong> possible values</p>
<p>To calculate the second value, you need to think about what your app does and make some reasonable assumptions.</p>
<p>Let’s say your app is generating a hash to assign to each of your customers. Let’s also say that your app is very niche. The absolute-best case scenario, your app will have 1000 customers over its lifetime. Then, for safety’s sake, we’ll multiply that by 10. We assume that you may need to generate 10,000 values over the course of your app’s life.</p>
<p><em>k</em> = <strong>10,000</strong> upper bound for possible values that need to be created</p>
<p>So now we need to calculate. There are many algorithms we can use. We’ll use one of the <a target="_blank" href="https://en.wikipedia.org/wiki/Birthday_problem#Approximations">simple approximations</a>, where <em>e</em> is the mathematical constant (the base of the natural log), and <em>k</em> and <em>N</em> are the same values as above.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*jET4z0dP--QnXA3AjpvEKA.png" alt="Image" width="360" height="142" loading="lazy"></p>
<p>The base equation gives us the probability that all values are unique. Then we subtract that result from 1 to get the odds that you have a collision. If you don’t feel like writing your own equation, I’ve provided one below written in JavaScript.</p>
<p>So in the example above, <strong>calculate(N, k)</strong> yields a probability of <strong>approximately 100%</strong> that you will have a collision. So for that use case, you should use a hash of more than 3 characters in length.</p>
<p>Now, if we were to take that same example but change the length of our hash from 3 to 5, we would get an <em>N</em> that is <em>much</em> larger (exponentials are good like that).</p>
<p><em>N</em> = 62⁵ = ~<strong>900,000,000</strong></p>
<p>Assuming the same value <em>k</em>, our new probability of a collision is down to only <strong>5.4%</strong>. What if we bumped that from 5 characters to 10?</p>
<p><em>N</em> = 62¹⁰ = <strong>~800,000,000,000,000,000</strong></p>
<p>Yes, that’s ~800 quintillion unique hashes. Which bring your odds of a collision down to 0.000000000062%. This is about a <strong>1-in-50-billion chance</strong> that you have a conflict. And that’s with a hash of 10 digits — something like: BwQ1W6soXk.</p>
<p>For another example, let’s say you’re a data processing company that deals with lots of transactions. We’ll say you deal with 1 million processes per second and you need to generate a hash for each of them. Let’s also say that you think this company could run for the next 100 years.</p>
<p>_k = ~_3,000,000,000,000,000</p>
<p>That comes out to about <strong>3 quadrillion</strong> hashes that you need made that all need to be unique. That’s a lot of data! But even with this extremely large number to work with, you only need a <strong>21-digit</strong> hash to ensure a <strong>1-in-10-million chance</strong> of collision over the lifetime of the project.</p>
<p>So the next time you’re worried about the length of your hash in ensuring uniqueness, know that you don’t need one as long as you think you do. Plus, you can do the calculation yourself without much effort.</p>
<p><em>Sam Corcos is the lead developer and co-founder of <a target="_blank" href="http://sightlinemaps.com">Sightline Maps</a>, the most intuitive platform for 3D printing topographical maps, as well as <a target="_blank" href="http://learnphoenix.io">LearnPhoenix.io</a>, an intermediate-advanced tutorial site for building scalable production apps with Phoenix and React.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
