<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sasha Fonseca on Medium]]></title>
        <description><![CDATA[Stories by Sasha Fonseca on Medium]]></description>
        <link>https://medium.com/@sashaafm?source=rss-f0be80d0ec3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JN8vEw4xBu9rycth.png</url>
            <title>Stories by Sasha Fonseca on Medium</title>
            <link>https://medium.com/@sashaafm?source=rss-f0be80d0ec3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:27:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sashaafm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Developing an Algorithm and Data Structures collection in Elixir Part II — Binary Search Tree]]></title>
            <link>https://medium.com/@sashaafm/developing-an-algorithm-and-data-structures-collection-in-elixir-part-ii-binary-search-tree-8c18e2294dee?source=rss-f0be80d0ec3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c18e2294dee</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Sasha Fonseca]]></dc:creator>
            <pubDate>Sat, 20 Feb 2016 17:52:45 GMT</pubDate>
            <atom:updated>2016-02-20T17:52:45.173Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>In the first part I presented my project Exads (Elixir Algorithms and Data Structures) with my goal of building the largest and most complete algorithms and abstract data structures collection for Elixir. In the last post I talked about my implementation of the <a href="https://medium.com/@sashaafm/developing-an-algorithm-and-data-structures-collection-in-elixir-593ce7e140e9#.4b1d50bgl">Priority Queue</a>. Like in the previous part, I’ll gladly take contributions to my project in any form (issues, pull requests to implement another algorithms or ADS, test suites, ideas).</p><p>Now in this second part I’ll describe my experience developing the Binary Search Tree abstract data structure.</p><h4>Specification</h4><p>A Binary Search Tree is a data structure made of nodes and where each one these nodes has a <strong><em>value</em></strong><em> </em>and is linked to another two nodes named <strong><em>left</em></strong><em> </em>and <strong><em>right</em></strong> (and linked by its parent node, of course). Unlike in the regular Binary Tree, this tree has defined rules to about its nodes way of being stored. Given a node <em>x</em> and its successor node <em>y, </em>then<em> y </em>will be on the left side if <em>y &lt; x</em> or on the right side otherwise.<em> </em>In <em>Introduction to Algorithms (3rd Edition 2010)</em>, by <em>T. Cormen</em> <em>et al. </em>(aka the Algorithms Bible) has the following quote about Binary Search Tree (BST):</p><blockquote>The search tree data structure supports many dynamic-set operations, including<br>SEARCH, MINIMUM, MAXIMUM, PREDECESSOR, SUCCESSOR, INSERT, and<br>DELETE.</blockquote><p>I’ll skip their description since their name is quite self explanatory.</p><h4>Implementation</h4><p>The first decision to make when implementing these kind of ADS is what other data structure will be used to hold the data and to represent the ADS itself. In this particular case, my first instinct was to either use Tuple or Map. Although both would serve my needs quite well, maps in Elixir are much powerful than Tuple, having many more operations available. However, Elixir has the Map and the Struct, which can be seen as a named module (due to a special <strong><em>__using__ </em></strong>macro that receives the module’s name and uses it as the struct’s). Initially, I implemented every operation using the struct, which seemed a good idea at the time, but I soon started running into a infuriating problem. As I stated, structs take their module’s name as their own. This means that they can end up with pretty long names and chain of maps, which although Elixir offers a short-cut to reference the module’s name (typing <strong><em>__MODULE__</em></strong>, also a special macro) when developing, it does not present any kind of abbreviation when outputting results, which will lead to some serious headache and confusion when trying to read the results and debug the code. For this reason, the following implementation is presented with maps.</p><p>Pattern matching and expressiveness come into play onde again, when declaring the maps used as having the value of <strong><em>:leaf </em></strong>when they are “empty”, <em>i.e.</em> they are null. Inserting elements can be done in a quite straightforward manner, not different from other functional languages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d490d3d0a70743d50dd7f5bd628a23f1/href">https://medium.com/media/d490d3d0a70743d50dd7f5bd628a23f1/href</a></iframe><p>Combined with the <em>new/1 </em>function (to build a new BST), <em>insert/1 </em>takes a three keyed map, one for the node’s value and another two for the left and right nodes, which will themselves be another three keyed maps (and therefore also BST’s) and takes a value. This value is compared against the current node’s value and its insertion into the left or right sub-tree is done recursively, according to the BST’s sorting rule.</p><p>Deletion in BST’s is not exactly trivial. I had to refresh my memory on BST’s for this one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0cfe663779398929d1962699de18fe6/href">https://medium.com/media/f0cfe663779398929d1962699de18fe6/href</a></iframe><p>I’ll leave this <a href="http://pages.cs.wisc.edu/~vernon/cs367/notes/9.BST.html">link</a> for anyone who wants to fully understand the requirements to properly delete a node in a BST, but the underlying problem revolves around not wanting to leave “gaps” or “holes” in the tree. Therefore, these gaps must be covered linking the remaining sub-tree to the deleted node’s parent. Although this may be a larger snippet of code, Elixir is quite expressive and lets it be readable and succinct.</p><p>Elixir also has many different constructs for control flow and conditions. Besides the more common <em>if </em>and <em>cond do</em> (similar to a <em>switch</em> construct), the language also provides <em>unless </em>(has the same function as <em>if </em>but offers a different interpretation), <em>case do</em>, which is great for pattern matching and since version 1.2, the <em>with </em>special form is also present.</p><p>For the SEARCH operation I implemented the two more common forms of BST searching algorithms, <strong>Depth-First Search</strong> (all three order variants) and <strong>Breadth-First Search</strong>. Elixir provided me with a fun implementation of these:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655080bbf29c53b2e5d06e1ed7b663b4/href">https://medium.com/media/655080bbf29c53b2e5d06e1ed7b663b4/href</a></iframe><p>This operation takes the tree to search and an <em>atom </em>named <em>order</em> to input the desired order. Using one of the conditional constructs, I implemented all the three variants (pre-order, in-order and post-order) inside the same helper function. However, another way to achieve the same result would be pattern matching different function based on the received order. Elixir does not take any kind of performance hit with either of these approaches, since internally, the functions are “unrolled” and compiled into similar compositions. Using lists, the results from each branch are concatenated into a single list, upon each end reaching its leaf.</p><p>Breadth-First Search didn&#39;t have anything special to it, in comparison to other functional programming languages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2908466da4595344a71de733e62da4e9/href">https://medium.com/media/2908466da4595344a71de733e62da4e9/href</a></iframe><p>PREDECESSOR and SUCCESSOR were achieved by slight modification of INSERT, by returning the whole sub-tree when the particular value was found. My BST implementation also has other operations, like <em>node_depth/2 </em>and <em>tree_height/1</em>, as well as <em>exists?/2</em> and <em>how_many/2</em> (self explanatory). The MINIMUM and MAXIMUM operations can be achieved through sorting the list output of one of the search functions.</p><h4>Conclusion</h4><p>Once again I invite anyone to help me on this project and collaborate, either by providing improvements, new algorithms or data structures or even test suites for the existing ones. The README has a roadmap with other stuff I’m thinking of implementing, but you don’t have to necessarily implement those, be free to explore other things. I’ll also take any constructive criticism!</p><p>For the next chapter I’m thinking about taking a break from ADS’s and implementing the Binary Search algorithm. Until the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c18e2294dee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing an Algorithm and Data Structures collection in Elixir]]></title>
            <link>https://medium.com/@sashaafm/developing-an-algorithm-and-data-structures-collection-in-elixir-593ce7e140e9?source=rss-f0be80d0ec3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/593ce7e140e9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Sasha Fonseca]]></dc:creator>
            <pubDate>Tue, 09 Feb 2016 16:31:50 GMT</pubDate>
            <atom:updated>2016-02-09T22:40:52.485Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Developing an Algorithm and Data Structures collection in Elixir Part I — Priority Queue</h3><p>This will be a multi-part series about developing an Algorithm and Data Structures collection with Elixir. The source can be found at <a href="https://github.com/sashaafm/exads">https://github.com/sashaafm/exads</a>.</p><p>Exads stands for EliXir Algorithms and Data Structures. This is a side project of mine with the aim to build the most complete and correct library/collection of data structures and algorithms. A roadmap can be found at the README. Since I’m developing on my own free time I’ll gladly take pull requests for new ADS’s, algorithms or corrections to my implementations, I’m a beginner at Elixir after all :)</p><p>There is already an implementation for the Stack and Queue Abstract Data Structures, however since these ADS are trivial to implement I’ll refrain from presenting them. This first post will be about the Priority Queue ADS.</p><h4>Specification</h4><p>The <strong>Priority Queue </strong>is an ADS similar to the Queue, where each element has an associated priority. Instead of removing/serving the elements by a First In, First Out policy, the PQ serves the element with the highest most associated priority. Only if there are elements sharing the same priority will the PQ resort to the FIFO policy. <em>Introduction to Algorithms</em>, 3rd Edition (2010) offers the following specification for the Priority Queue:</p><blockquote><strong>INSERT(S, x)</strong> inserts the element x into the set S, which is equivalent to the operation S =S U {x}.<br><strong>MAXIMUM(S)</strong> returns the element of S with the largest key.<br><strong>EXTRACT-MAX(S)</strong> removes and returns the element of S with the largest key.<br><strong>INCREASE-KEY(S, x, k)</strong> increases the value of element x’s key to the new value k,<br>which is assumed to be at least as large as x’s current key value.</blockquote><p>The book also refers the Priority Queue as usually being implemented with the aid of a Heap Sort ADS. Since one of my aims is to keep all implementations close to Elixir’s main library (for performance and correctness purposes), I shall implement mine resorting to the language’s List module.</p><h4>Implementation</h4><p>Although Elixir is not Object-Oriented, my first instinct was to write a <em>new() </em>function to return a new empty Priority Queue (PQ). Since my implementation is done by the means of a List, this function does nothing more than to return an empty List (an interesting concept in Elixir and other Functional languages is that even if you do not intend the function to return anything, it will always return the result of the last operation. Over time, this builds a good sense of how data is transformed and pipelined around in FP languages).</p><p>Next, I implemented the <strong><em>INSERT(S, x) </em></strong>operation, which I named <strong><em>insert_with_priority(queue, {_item, _prio} = elem)</em></strong>. Right away we can get on with some great <strong>pattern matching</strong>, one of my favourites FP features and specially Elixir’s amazing implementation of it. In the parameters, I pass <em>{_item, prio} = elem</em>, which means the function expects a tuple with two parameters I called <strong><em>item</em></strong><em> </em>and<em> </em><strong><em>prio </em></strong>(the priority of the element) and then I matched that tuple with <strong><em>elem </em></strong>to enable the calling of the whole tuple, instead of adressing the contents individually. This leads to great expressiveness and to writing short and clear code. The <strong><em>item </em></strong>also takes an underscore as a prefix in order to tell the Virtual Machine that although I match that parameter and give it a name, I won’t be using it in the function. This makes for a pretty good way to make the code more readable and understandable, without having to resort to bad practices (I could just name the parameter and just leave an underscore, which in Elixir means that a parameter is passed, but it doesn’t care what it is and doesn’t try to match it, however this way makes it quite clear that the elements are supposed to come in a tuple format, where the first parameter is the item/value of the element). The same applies to <strong><em>prio</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f45056701c4b3d94d5d1fbb4ff578a88/href">https://medium.com/media/f45056701c4b3d94d5d1fbb4ff578a88/href</a></iframe><p>Quite a short implementation. The specification tells it expects to be passed a list of tuples and tuple and that a list of tuples will be returned. The function itself just concats the original queue with the desired element in a list.</p><p>Next is the <strong><em>EXTRACT-MAX(S) </em></strong>which I named <strong><em>get_frontmost_element(queue)</em></strong>. This function returns the element that is next up to be served and the remainder of the queue in a tuple <em>{element, new_queue}</em>. This function actually just makes a call to a private helper function that gave me quite some trouble to implement. This was the first version of the helper (don’t bother trying to understand):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f82810569ebf8d0ba9d23b98646a47a4/href">https://medium.com/media/f82810569ebf8d0ba9d23b98646a47a4/href</a></iframe><p>Not pretty, right? I tried debugging and testint this mess for nearly two hours before I decided there should be an easier way. Then I remembered my intent of using Elixir’s main library as much as possible, and alas I found the perfect function in <strong><em>Enum</em></strong>. <strong>Enum </strong>is a module for operating on any other module that implements the <strong>Enumerable </strong>Protocol. The List module obeys to this requirement and after reading the available functions with some attention I found <strong><em>group_by(enumerable, dict \\ %{}, fun) </em></strong>or simply <strong><em>group_by/3</em></strong>. This function takes an enumerable, an optional Dictionary and a function. It then groups all the elements of the enumerable into a <strong>Map</strong> where each group is defined according to the specified function (it may be the length of each string in a list of string, the date in a map of dates or in my case a list of priorities). After the elements are grouped I could just take the last element in the highermost group (since the elements are grouped as they are processed, the first element with the highest priority will go in the end of highermost group) and then remove it from the original queue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9142d7b48a4baee4275886dae7baee53/href">https://medium.com/media/9142d7b48a4baee4275886dae7baee53/href</a></iframe><p>Much easier, clearer and readable than my first version. A tuple is pattern matched against the <em>group_by/3 </em>function and then the Map is transformed into a List and that last element (the highermost group) is retrieved from the List. Finally a tuple is built with the first item being the last element of that highermost group (it will work even if the list has size 1) and the second item is the original list minus that element. At the top we can also see Elixir’s pattern matching at work on function definitions, where in case of the queue coming as an empty List, it will just return <strong><em>nil</em></strong>.</p><p><strong><em>MAXIMUM(S) </em></strong>is pretty much the same as the previous function’s implementation, however, instead of returning the tuple with the removed element and the new queue without the said element, it just returns that highest priority element. The spec shows that a list of tuples must be passed and that either a tuple or nil will be returned. Once again, pattern matching is used to reuse the helper function and just return the highermost element, not caring about the transformed queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a1861b289ead0fd1e05f547dc8ed23e/href">https://medium.com/media/1a1861b289ead0fd1e05f547dc8ed23e/href</a></iframe><p>Finally, I implemented the <strong><em>INCREASE-KEY(S, x, k) </em></strong>operation. This function actually uses another public function I implemented (<em>position_by_order/2 </em>which retrieves the position by FIFO policy of a given element). I named the function <strong><em>increase_element_priority(queue, {item, prio} = elem, new_prio) when new_prio &gt;= prio</em></strong>. This last bit is important. This is a <strong><em>guard </em></strong>which are Elixir macros to pattern match functions, when they obey the condition it stablishes. Its purpose is to comply with the operation’s specification of the new priority being at least as large as the old one. The function itself uses the <strong>Enum </strong>module again, for the functions <strong><em>take/2 </em></strong>and<strong><em> slice/3. </em></strong>First it determines the position of the element in the queue. Then it uses <em>take/2 </em>to get the first part of the queue, up to where the element is (which before being stored into the variable, is removed from this first part). <em>Slice/3 </em>gets the remaining part of the queue up to its length. Lastly, a new queue is returned through the concatenation of the first part (without the element), the element with the new priority and the remainder of the queue. This whole concatenation section is necessary to preserve the FIFO order of the queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc72b77623f0f5c53d71cf29cc80677c/href">https://medium.com/media/cc72b77623f0f5c53d71cf29cc80677c/href</a></iframe><h4>Testing</h4><p>Since testing this ADS didn’t show anything particularly interesting, I won’t include any details in this first part. However, my test suite wasn’t that strong or robust (I pretty much just did some border/boundary value tests) so I’ll probably get back to it in the future to increase my confidence in this implementation.</p><h4>Conclusion</h4><p>This was the implementation of the Priority Queue in Elixir for my Exads side-project. It has been quite interesting so far to develop these known ADS’s and algorithms using a languages particular mechanisms and features. Pattern matching, specially, is the most useful feature that brings a lot of expressiveness and readibility to the source code. The <strong>Enum </strong>module is also a great asset to rely on if a developer decides to his implementations through <strong>Enumerables</strong>. Although this post only focuses on the four main operations of the PQ, I also implemented other common operations and some others I thought, along the way, could be useful for anyone using this implementation.</p><p>Next on my roadmap is the famous Tree data structure. Like I said at the beginning of this story, my project is available on GitHub (<a href="https://github.com/sashaafm/exads">https://github.com/sashaafm/exads</a>) and I will gladly take all the help I can take to make it the most complete Algorithms and Data Structures collection for Elixir. If you want to contribute, just clone the code and do a Pull Request, or hit me on Twitter :)</p><p>Have a good one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=593ce7e140e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>