<?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 Steven Vandevelde on Medium]]></title>
        <description><![CDATA[Stories by Steven Vandevelde on Medium]]></description>
        <link>https://medium.com/@icidasset?source=rss-364a61c8ad1a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U9Jor73OveX64--a2u8U9Q.jpeg</url>
            <title>Stories by Steven Vandevelde on Medium</title>
            <link>https://medium.com/@icidasset?source=rss-364a61c8ad1a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:44:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@icidasset/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[Functional Programming & Elixir — Pt. 1, The Basics]]></title>
            <link>https://medium.com/making-internets/functional-programming-elixir-pt-1-the-basics-bd3ce8d68f1b?source=rss-364a61c8ad1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd3ce8d68f1b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Steven Vandevelde]]></dc:creator>
            <pubDate>Wed, 06 Jul 2016 18:43:16 GMT</pubDate>
            <atom:updated>2016-11-01T19:33:32.853Z</atom:updated>
            <content:encoded><![CDATA[<p>Functional Programming &amp; Elixir — Pt. 1, The Basics</p><p><em>It might be difficult to get into functional programming because of the complexity and the terminology. The goal of these articles is to explain the terminology in a simple manner, reduce the complexity and at the same time, give code samples written in </em><a href="http://elixir-lang.org/"><em>Elixir</em></a><em> and show how Elixir helps us with functional programming. </em><strong><em>This first article is all about functions, variables and patterns.</em></strong></p><h3>Functions</h3><h4>First-class functions</h4><p>This doesn’t say much, but it basically just means that functions can be stored in variables, that you can pass them to other functions and invoke them there. In Elixir these are called <strong>anonymous functions</strong>.</p><pre>some_function = fn(arg) -&gt; do_whatever end</pre><p>You also have <strong>named functions</strong>.</p><pre>defmodule Do do<br>  def something do<br>    do_whatever<br>  end<br>end</pre><p>These cannot be passed down to other functions. But you can convert them to anonymous functions.</p><pre>some_function.( &amp;Do.something/0 )<br><em>#</em> <em>`/0` is the amount of arguments the function accepts, ie. the arity</em></pre><p>There’s also another syntax which you’ll see sometimes, for example:</p><pre>Enum.reduce([“hello”, “ “, “world”], &amp;(&amp;2 &lt;&gt; &amp;1))<br><em># Returns “hello world”</em></pre><p>So what is this `&amp;(&amp;2 &lt;&gt; &amp;1)` thing? It’s a concise anonymous function, a so-called partially applied function. Where `&amp;1` is the first argument of the function and `&amp;2` the second.</p><p>To fully explain the example, `&lt;&gt;` concats the two strings (ie. the two function arguments). Check the <a href="http://elixir-lang.org/docs/v1.1/elixir/Enum.html#reduce/2">Elixir docs</a> for more info about the `Enum.reduce` function.</p><h4>Composing</h4><p>Composing, <em>function composition</em>, is essentially executing a sequence of functions. That is, the result of each function is passed as the argument of the next.</p><pre>add_one = fn(integer) -&gt;<br> integer + 1<br>end</pre><pre>multiply_by_four = fn(integer) -&gt;<br> integer * 4<br>end</pre><pre># execute functions<br>multiply_by_four.(add_one.(1)) # returns ‘8’<br>multiply_by_four.(add_one.(add_one.(2))) # returns ‘16’</pre><p>Elixir provides a way to make it more clear what we’re trying to do here. This operator is called the pipe operator.</p><pre>2 |&gt; add_one.() |&gt; add_one.() |&gt; multiply_by_four.()</pre><pre><em># This is easier to read, especially for mathematical operations.<br># ((2 + 1) + 1) * 4</em></pre><p><em>This is the syntax for anonymous functions, which looks a bit odd, if I were using named functions I could omit the trailing `.()`</em></p><h4>Closures</h4><p>A closure is a function which has the following properties:</p><ul><li>Is a first-class function</li><li>Remembers the values of all the variables in scope when the function was created</li></ul><pre>x = 2</pre><pre>f_x = fn -&gt;<br> y = :math.pow(x, 2)<br> y<br>end</pre><pre>f_x.() # returns 4</pre><pre>x = 3</pre><pre>f_x.() # still returns 4</pre><p><em>`:math` is a Erlang module, which in Elixir are represented by atoms. Elixir runs on top of the </em><a href="http://www.erlang-factory.com/upload/presentations/708/HitchhikersTouroftheBEAM.pdf"><em>Erlang VM</em></a><em>, which makes it possible to use Erlang code with Elixir</em></p><h4>Higher-order functions</h4><p>A higher-order function (HoF) is a function which takes one or more functions as arguments and/or a function that returns a new function, <em>which is a closure</em>.</p><p><strong>Example</strong></p><pre>in_p_tags = &amp;(“&lt;p&gt;” &lt;&gt; &amp;1 &lt;&gt; “&lt;/p&gt;”)<br>in_nav_tags = &amp;(“&lt;nav&gt;” &lt;&gt; &amp;1 &lt;&gt; “&lt;/nav&gt;”)<br>in_body_tags = &amp;(“&lt;body&gt;” &lt;&gt; &amp;1 &lt;&gt; “&lt;/body&gt;”)</pre><pre>wrap = fn(wrapping_functions) -&gt;<br> fn(html) -&gt;<br>   reducer = fn(function, acc) -&gt; function.(acc) end<br>   Enum.reduce(wrapping_functions, html, reducer)<br> end<br>end</pre><pre>wrap.([in_p_tags, in_body_tags]).(“Text”)</pre><pre><em># result:<br># &lt;body&gt;&lt;p&gt;Text&lt;/p&gt;&lt;/body&gt;</em></pre><pre>wrap.([in_nav_tags, in_body_tags]).(“&lt;a href=\”…\”&gt;Link&lt;/a&gt;”)</pre><pre><em># result:<br># &lt;body&gt;&lt;nav&gt;&lt;a href=”…”&gt;Link&lt;/a&gt;&lt;/nav&gt;&lt;/body</em>&gt;</pre><p>This example sums it up, we have:</p><ul><li>First-class functions</li><li>Function composition in the form of a reducer</li><li>A closure, the function returned by the `wrap` function</li><li>A higher-order function named `wrap`</li></ul><h3>Pattern matching &amp; Immutability</h3><p>In Elixir the `=` operator doesn’t only do assignment, but also pattern matching. That’s why it’s called the <strong>match</strong> operator. This also means that variables aren’t really places in memory that values are stored in, but rather<br><strong>labels for the values</strong>. That is, Elixir/Erlang allocates memory for the values, not the variables.</p><pre># attached the value ‘1’ to the label ‘nr’<br>nr = 1</pre><pre># rebind the ‘nr’ label to the value ‘2’<br>nr = 2</pre><pre># let’s see why this is called the match operator<br># the following is a valid expression,<br># because of the previous expression<br>2 = nr</pre><pre># this is not, because 3 does not match 2,<br># this will raise a MatchError<br>3 = nr</pre><p>We can also do destructuring:</p><pre># 1. destructure by using tuples<br>{ a, b } = { :ok, “Hi” }</pre><pre>do_something_with(a)</pre><pre># this won’t work,<br># we need 3 variable names on the left side<br>{ a, b } = { :ok, “Hi”, “extra-extra” }</pre><pre># this will work<br>{ a, b, type } = { :ok, “Hi”, “extra-extra” }<br>{ a, b, _ } = { :ok, “Hi”, “extra-extra” }</pre><pre># 2. destructure by using lists<br>[ a, b ] = [ “first”, “second” ]</pre><pre><em># `_` is used to ignore a value</em></pre><p><strong>Why this is useful</strong></p><p>Say you have a function that returns a tuple, but you don’t want to do this all the time:</p><pre>result = some_function()<br>state = elem(result, 0)<br>message = elem(result, 1)</pre><pre><em># `elem` gets a specific item out of the tuple.</em></pre><p>Wouldn’t it be way easier if we could just write:</p><pre>{ state, message } = some_function()</pre><p>Yes, it is.</p><h4>Immutability</h4><p>With that in mind, in Elixir, all data types are immutable.</p><pre>tuple = { :number, 1 }</pre><pre># if we would change the tuple, we would get a new one<br># for example, change the second value in the tuple:<br>put_elem(tuple, 1, 1000)</pre><pre><em># returns new tuple: { :number, 1000 }<br># tuple variable still points to the tuple: { :number, 1 }</em></pre><p><strong>Why this is useful</strong></p><p>Imagine if we didn’t have immutable date types.</p><pre>state = %{ example: “Property” }</pre><pre>func_a = fn(s) -&gt;<br> # remove ‘example’ property from the state map<br> Map.delete(s, :example)<br>end</pre><pre>func_b = fn(s) -&gt;<br> str = s.example &lt;&gt; “: example”<br>end</pre><pre>func_a.(state)<br>func_b.(state)</pre><p><em>`%{}` is a key-value store, a </em><a href="http://elixir-lang.org/docs/stable/elixir/Map.html"><em>map</em></a></p><p>In this case `func_b` would break, because it depends on the `example` property and we deleted that property in `func_a`.</p><p>If we apply immutability, for example, `Map.delete` produces an error,<br>or as in Elixir, `Map.delete` returns a new map and doesn’t touch the original map, `func_b` will work fine.</p><h3>Conclusion</h3><p>I think we have discussed all the basics of functional programming and Elixir. Except for some basic Elixir types, but you can look those up easily. Elixir has some pretty good <a href="http://elixir-lang.org/getting-started/introduction.html">getting-started guides</a>.</p><p><strong>Next up in the functional programming category is what to do and what not do with functions.</strong> Or to put in technical terms, limiting side-effects, data-first and using map and reduce instead of a loop.</p><p><em>Thanks to </em><a href="https://medium.com/u/90179c2db184"><em>Brooklyn Zelenka</em></a><em> and </em><a href="https://medium.com/u/786cdd7fe548"><em>Izaak Schroeder</em></a><em> for all the help!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd3ce8d68f1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/making-internets/functional-programming-elixir-pt-1-the-basics-bd3ce8d68f1b">Functional Programming &amp; Elixir — Pt. 1, The Basics</a> was originally published in <a href="https://medium.com/making-internets">Making Internets</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>