<?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 Sergio Nogueira Filho on Medium]]></title>
        <description><![CDATA[Stories by Sergio Nogueira Filho on Medium]]></description>
        <link>https://medium.com/@scnfilho?source=rss-eb1a2a67a0cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h5piwUSRqvvevrbJKfsSkw.jpeg</url>
            <title>Stories by Sergio Nogueira Filho on Medium</title>
            <link>https://medium.com/@scnfilho?source=rss-eb1a2a67a0cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:56:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scnfilho/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[Elixir broke my imperative mind]]></title>
            <link>https://medium.com/magnetis-backstage/elixir-broke-my-imperative-mind-5d2fb2d53502?source=rss-eb1a2a67a0cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d2fb2d53502</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-paradigms]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sergio Nogueira Filho]]></dc:creator>
            <pubDate>Wed, 05 Oct 2016 21:04:43 GMT</pubDate>
            <atom:updated>2016-10-05T22:38:39.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n33hJt3TJcyern8bppbPWQ.jpeg" /></figure><p>Earlier this year I started playing around with the <a href="http://elixir-lang.org/">Elixir programming language</a>. Some time later I got to try it out in a small, non-critical-path project. It wasn’t my first time on functional programming, but I was mind-blown by how simple it was to solve the uncommon problem of <strong>spelling numbers</strong>. If you’ve ever had to solve this problem, it’s likely that the first thing you tried was to use a 3rd-party lib. That’s what I tried too, but I couldn’t find one — especially in the case of my project, since I had to write out numbers in <strong>Portuguese</strong>.</p><p>In this article, we’ll rewrite the same lib, but for the English language.</p><h4>Disclaimer</h4><p>I’m falling in love with Elixir. You’ve probably seen this expression used before. One can learn a lot of different ways to solve problems when in love with a programming language — the downside is that you usually ignore its problems and shortcomings. This might be a part of not having been in a big project using it. Or it could be because it’s just too damn awesome.</p><h3>The perks of a modern programming language</h3><p>Programming languages created more recently have the advantage of being born based on knowledge over things that work well and things that don’t. Let’s take Java for an example. If you’ve ever been part of a Java project, you probably know about tools like ant, maven or gradle. These are in the scope of building and managing dependencies. Those are required activities for almost any serious project. Still they’re done by third party tools — they were created <em>after</em> Java and must be separately installed to be used. So after the industry as a whole acknowledge such tools as essential, it’s easy to expect newer tools to be more closely integrated or even ship with them.</p><p>A simple example of a tool that ships with the language is Ruby’s <strong>irb</strong>. It’s an interactive shell (REPL) that runs ruby code. It also allows to load some environment, that’s what happens when you run <em>rails console</em> in a rails project.</p><p>Elixir learns a lot from previous programming languages, specially from Ruby. It also includes an interactive shell called <strong>iex.</strong> After installing Elixir all you have to do is type <em>iex</em> in your terminal:</p><pre>~ $ iex</pre><pre># ... bunch of stuff that don&#39;t really matter right now</pre><pre>iex(1)&gt; 1 + 1<br>2</pre><p>Not impressive, I know. But REPLs are extremely powerful devices for <strong>learning</strong> the language and <strong>debugging</strong>.</p><h4>Enter Mix</h4><p>Another great tool that ships with Elixir is <strong>mix</strong>. The <a href="http://elixir-lang.org/getting-started/mix-otp/introduction-to-mix.html">official tutorial</a> says mix is</p><blockquote>a build tool […] that provides tasks for creating, compiling, testing your application, managing its dependencies and much more</blockquote><p>And it’s using mix that we create the structure for our project:</p><pre>mix new humanumbers</pre><p>This will create a directory called <strong>humanumbers</strong> inside the current directory, with a structure similar to this one:</p><pre>humanumbers<br>├── config<br>│   └── config.exs<br>├── lib<br>│   └── humanumbers.ex<br>├── mix.exs<br>├── README.md<br>└── test<br>    ├── humanumbers_test.exs<br>    └── test_helper.exs</pre><p>As you can see mix gives you a base module file and test helper, along with a sample config file and a sample test. Let’s see them working:</p><pre> $ mix test<br># ... more messages that don&#39;t matter at the moment</pre><pre>Finished in 0.03 seconds (0.03s on load, 0.00s on tests)<br>1 test, 0 failures</pre><pre>Randomized with seed 532609</pre><p>There’s also that <em>mix.exs</em> file over there. There’s a lot more to it than I’d like to talk about here, but let’s look at this bit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bec3e564a9c22127a227fd72d267e38/href">https://medium.com/media/7bec3e564a9c22127a227fd72d267e38/href</a></iframe><p>This is means we can <strong>build</strong>, <strong>manage dependencies</strong> and <strong>test</strong> with nothing but Elixir itself. Yes, this is obviously not unique to Elixir, many other languages ship with these features or a subset of them. I believe those are becoming requirements for productive development and Elixir meets them well.</p><h3>The code</h3><p>At this point, we can start test-driving some code. After two red-green cycles we have these tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e7199c6c2261cb8f476e19cf7f61583/href">https://medium.com/media/1e7199c6c2261cb8f476e19cf7f61583/href</a></iframe><p>And this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c776a35cc821bf1096b1acc362896848/href">https://medium.com/media/c776a35cc821bf1096b1acc362896848/href</a></iframe><p>Still not impressive, right? Specially if you come from a Ruby background, almost nothing is new in the entire article so far. But if you’re an Elixir programmer you’re probably cringing. Because that’s not how you‘d typically solve this in Elixir.</p><h4>Pattern Matching</h4><p>We can refactor this code like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/376d19fa141e0bf7ff23141fe808a68b/href">https://medium.com/media/376d19fa141e0bf7ff23141fe808a68b/href</a></iframe><p>This is called <strong>pattern matching</strong> in a function definition. We can have multiple definitions (called <strong>clauses</strong>) for the same function. Once the function is called, the first clause that <strong>matches </strong>will be executed. This is a contrived example because we only have one integer argument, but there are <a href="http://elixir-lang.org/getting-started/pattern-matching.html">many other forms of pattern matching</a> that I won’t describe here.</p><p>Also, when I said we were refactoring, I lied. The change we made does change the behavior of the code. In the previous code, if you called <em>humanize(2)</em> you’d get “one”. Now we get a <em>FunctionClauseError</em> because we don’t have a default case:</p><pre>iex(2)&gt; Humanumbers.humanize(2)<br>** (FunctionClauseError) no function clause matching in Humanumbers.humanize/1<br>    lib/humanumbers.ex:2: Humanumbers.humanize(2)</pre><p>This might seem like a tiny detail but I think it’s huge. It means some forgotten edge cases can cause <strong>errors</strong> instead of just weird behavior.</p><p>So, the logical next steps would be to add more numbers to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec2fd10378c59259e5cfcf84c87a201/href">https://medium.com/media/8ec2fd10378c59259e5cfcf84c87a201/href</a></iframe><p>The first time I got to this point I told myself “this isn’t actual programming!”. I was wrong. You can try to refactor this by creating constants, maps, separating the names in a file, but it won’t get very different and it IS a computer program. It’s just different. It’s declarative programming, we describe <strong>what</strong> to achieve instead of <strong>how</strong> to achieve it — like we’re used to in imperative code. Declarative programming is a lot more common in functional languages, but not exclusive to them. The easiest common example I can think of right now are the LINQ features in C#.</p><h4>Recursion</h4><p>Obviously that code can’t go on forever, it would be silly to have as many lines as numbers we want to describe. Numbers 21 to 29 start exhibiting a very clear pattern, so we use those simple clauses up to 20, and for numbers after that we can use a more generic approach (I’ll start omitting tests for brevity — they all have the same structure as the first ones):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3567aa9f32f4352b9ab8bab7faaa36da/href">https://medium.com/media/3567aa9f32f4352b9ab8bab7faaa36da/href</a></iframe><p>Great! With one additional line of code we get “twenty-one” all the way up to “twenty-nine”. But if we call <em>humanize(30)</em> we get “twenty-ten”, so we need to add more simple clauses and generalize the last one a little more:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a371b932a17cdfb0b896005c5ccfe310/href">https://medium.com/media/a371b932a17cdfb0b896005c5ccfe310/href</a></iframe><p>Here we do some math to separate the tens from the units, meaning we can now print any number up to “ninety-nine”!</p><p><strong>Recursion</strong> is absolutely not a “feature” of Elixir. Pretty much any language with functions/methods/procedures supports recursion. That said, describing a problem as a part of itself is a lot more commonly used in functional programming. Such a powerful tool comes with risks: at the current state of our code, if we call <em>humanize(100)</em> we go into infinite recursion and eventually crash! We need to <strong>guard</strong> against that!</p><h4>Guard clauses</h4><p>If you come from a Ruby background you might have heard this expression before. It’s when you short circuit a method with a conditional return. In Ruby this could be written like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f2514b10196b5e8b514d9c113d13702/href">https://medium.com/media/9f2514b10196b5e8b514d9c113d13702/href</a></iframe><p>But in Elixir, function definitions actually support guard clauses. A function definition is skipped if its guard clause isn’t matched:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3144c336f6178e1d680f1dc42dc7f2e/href">https://medium.com/media/d3144c336f6178e1d680f1dc42dc7f2e/href</a></iframe><p>This is a little bit different, though. Instead of returning <em>nil</em>, we get another <em>FunctionClauseError</em> just like we did with pattern matching. We now need to add another definition for numbers above 100.</p><h4>Private Functions</h4><p>Numbers between 100 and 999 follow a rather simple pattern of writing the hundreds (1xx = one, 2xx = two, …), adding “hundred” and then writing out the rest. So we can add a new definition for our function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee86f5351a4d0194519198ae9e5e29e1/href">https://medium.com/media/ee86f5351a4d0194519198ae9e5e29e1/href</a></iframe><p>But there’s an exception to that rule. When that <em>rest</em> is 0, like for 200, we’re writing “two hundred zero”. To avoid that, we can add a private function and pattern match on the <em>rest</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d752f5ad0e33043d25631123ba1b7fc/href">https://medium.com/media/7d752f5ad0e33043d25631123ba1b7fc/href</a></iframe><p>Again, not an exclusive feature, but it’s good to know you can use <strong>private functions</strong> (defined with <em>defp</em>) to split the complexity of your code.</p><p>With this, we can print numbers up to 999. Above 1000, the pattern repeats itself, but to handle it we need some harder math. Bear with me for this one.</p><p>The only new words that still need to be introduced are the ones that come on every three <strong>orders of magnitude</strong>, that is, “thousand”, “million”, “billion” and so on. So we need to extract that information from the number and write a function to give us that word.</p><p>The other tricky part is that we need to split the “big” part of the number from the small one, and recursively write out the latter. That’s because a “billion” can still contain a “million”, which can still contain a “thousand”. For instance, 1,234,567 starts with “one million”, that’s our big part, and we then write out the rest, where “two hundred thirty-four thousand” is now the big part. Let’s look at the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b096a0e4f913ea1a765ee80adebc8f45/href">https://medium.com/media/b096a0e4f913ea1a765ee80adebc8f45/href</a></iframe><p>Let’s see what’s happening on each step here:</p><p>First we calculate what we call the <em>order</em>, if you look at the end where we define the <em>human_order</em> function, you’ll see that this is just mapping 1 for “thousand”, 2 for “million” and so on.</p><p>We then use that to calculate the <em>order_base</em>, which is 1,000 for <em>order</em> 1, 1,000,000 for <em>order</em> 2. So the number 1,234,567 would have <em>order</em> 2 and <em>order_base</em> 1,000,000.</p><p>Lastly, we use the <em>order_base</em> to split the number between its big part and small part (2,345,678 would be split into 2 and 345,678), to then call <em>human_big_number</em>, a private function we defined to handle the edge case of the small part being 0, where we have to do the same we did for the hundreds (avoiding “one million, zero thousand, zero”).</p><h4>The Pipe Operator</h4><p>There’s one last feature we can use to improve our code here. If you look at this part of the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5205e75240954a06481ec7375dced28e/href">https://medium.com/media/5205e75240954a06481ec7375dced28e/href</a></iframe><p>You can see a chain of data processing, usually written in this unnatural way. Elixir has a pipe operator (|&gt;), similar to Unix’s (|), that allows you <strong>prepend</strong> the first argument to a function call. We can use that feature here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c48b09ce44b2798c6aca9bc24e986a3/href">https://medium.com/media/9c48b09ce44b2798c6aca9bc24e986a3/href</a></iframe><p>This feature allows for a much clearer visualization of a series of transformations. You can also add line breaks before each pipe when necessary.</p><h3>Not so declarative anymore…</h3><p>At this point our code can handle numbers up to 999,999,999, and increasing that is as simple as adding a new clause to the <em>human_order</em> function. But it doesn’t look as declarative. Specially if you look at the way we handle the bigger numbers you’ll see a lot of <strong>how</strong> to get there. I believe there’s a spectrum between imperative and declarative, and as much as we try to stay by the declarative end, there will always be restrictions that push us towards more imperative approaches. Also, I might have missed some opportunities for more declarative code due to my lack of experience with the language.</p><h3>Conclusion</h3><p>Having used Ruby, Elixir is a very comfortable language for learning functional programming because it’s <strong>familiar</strong> in many aspects. We also benefit a lot from it’s <strong>modern</strong> platform, which gives us the tools we need to start working right away (like mix and ExUnit). These two aspects are very important for a beginner because the focus should be on the paradigm shift.</p><p>This specific problem motivated me to write because I got to a good enough solution a lot quicker than I had expected. Of course there’s still a lot of work to do and edges to trim, but the core of the problem is solved. If you want to see the code as a whole and contribute, please visit the <a href="https://github.com/scnfilho/humanumbers">repository on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d2fb2d53502" width="1" height="1" alt=""><hr><p><a href="https://medium.com/magnetis-backstage/elixir-broke-my-imperative-mind-5d2fb2d53502">Elixir broke my imperative mind</a> was originally published in <a href="https://medium.com/magnetis-backstage">magnetis backstage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>