<?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 rizan on Medium]]></title>
        <description><![CDATA[Stories by rizan on Medium]]></description>
        <link>https://medium.com/@qrizan?source=rss-1c4ed2c9b9d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F9lI3eaM2ZMrNEsZcTjqxQ.gif</url>
            <title>Stories by rizan on Medium</title>
            <link>https://medium.com/@qrizan?source=rss-1c4ed2c9b9d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:11:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@qrizan/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[Higher-Order Functions in Elixir Explained Simply]]></title>
            <link>https://medium.com/@qrizan/higher-order-functions-in-elixir-explained-simply-dc60327ac337?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc60327ac337</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[high-order-functions]]></category>
            <category><![CDATA[elixirlang]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 13:02:09 GMT</pubDate>
            <atom:updated>2025-04-05T13:02:09.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UlLbupHr-mmwW1O5BAhF4Q.png" /></figure><p>Elixir is a functional programming language that runs on the <strong>Erlang VM</strong>. One of the core features in functional programming is the <strong>Higher-Order Function (HOF)</strong>. In this article, we’ll explore what higher-order functions are, how they work in Elixir, and how we can use them to write cleaner and more efficient code.</p><h4>What is a Higher-Order Function?</h4><p>A <strong>higher-order function</strong> is a function that can:</p><ul><li><strong>Take one or more functions as arguments</strong>, and/or</li><li><strong>Return a function as a result</strong></li></ul><p>In Elixir, functions are treated as <em>first-class citizens</em>. This means we can:</p><ul><li>Store functions in variables</li><li>Pass them as parameters</li><li>Return them from other functions</li></ul><h4>Example: Passing a Function as an Argumen</h4><p>Elixir’s Enum module includes many higher-order functions. Let’s start with a simple example:</p><pre>Enum.map([1, 2, 3], fn x -&gt; x * 2 end)<br># Output: [2, 4, 6]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*ffsKwAcuV2h2d0dd7Pt92g.png" /></figure><p>Explanation:</p><ul><li>Enum.map/2 is a higher-order function.</li><li>The second argument is an <strong>anonymous function</strong>: fn x -&gt; x * 2 end.</li></ul><p>We can also use the shorthand syntax with &amp;:</p><pre>Enum.map([1, 2, 3], &amp;(&amp;1 * 2))</pre><h4>Example: Returning a Function from Another Function</h4><pre>defmodule Math do<br>  def multiplier(n) do<br>    fn x -&gt; x * n end<br>  end<br>end<br><br>double = Math.multiplier(2)<br>IO.puts double.(5)  # Output: 10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*NfHeyALlYY8oka10h-_oxA.png" /></figure><p>Explanation:</p><ul><li>The multiplier/1 function returns another function.</li><li>We store it in the double variable and call it with double.(5).</li></ul><h4>Why Use Higher-Order Functions?</h4><p>So, why should we care about higher-order functions?</p><ul><li><strong>Reusable</strong>: We can write generic code that adapts to different use cases.</li><li><strong>Composable</strong>: Works perfectly with Elixir’s |&gt; (pipe) operator, making data flow clear and readable.</li><li><strong>Efficient</strong>: Reduces repetition and improves code abstraction.</li></ul><h4>Common Higher-Order Functions in Enum</h4><p>Elixir’s Enum module provides many useful higher-order functions, such as:</p><ul><li>Enum.map/2</li><li>Enum.filter/2</li><li>Enum.reduce/3</li><li>Enum.each/2</li><li>Enum.reject/2</li></ul><p>Example:</p><pre>Enum.filter([1, 2, 3, 4, 5], fn x -&gt; rem(x, 2) == 0 end)<br># Output: [2, 4]</pre><h4>Mini Case Study: Filter and Transform a List</h4><p>Let’s say we want to get only even numbers from a list and multiply each by 3:</p><pre>[1, 2, 3, 4, 5, 6]<br>|&gt; Enum.filter(&amp;rem(&amp;1, 2) == 0)<br>|&gt; Enum.map(&amp;(&amp;1 * 3))<br># Output: [6, 12, 18]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*gNgkFhC29sJiWe9Qnej_qg.png" /></figure><p>Using pipelines and higher-order functions, we can write concise and readable code that’s easy to maintain.</p><h4>References</h4><ul><li><a href="https://codesignal.com/learn/courses/functional-programming-concepts-in-elixir/lessons/introduction-to-higher-order-functions"><strong>Introduction to Higher-order Functions</strong></a></li><li><a href="https://serokell.io/blog/elixir-for-beginners"><strong>From Pipes to Pattern Matching and Beyond</strong></a></li></ul><h4>Conclusion</h4><p>Higher-order functions are a fundamental part of working with Elixir. By understanding how to use them, we can:</p><ul><li>Write modular, expressive code</li><li>Take full advantage of Elixir’s functional nature</li><li>Build applications that are easier to test and scale</li></ul><p>Whether we’re building tools, APIs, or web applications with Phoenix, mastering higher-order functions will make us more effective Elixir developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc60327ac337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Function Clauses in Elixir: Simple Guide]]></title>
            <link>https://medium.com/@qrizan/understanding-function-clauses-in-elixir-simple-guide-2e6c65aa8ad0?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6c65aa8ad0</guid>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 13:01:20 GMT</pubDate>
            <atom:updated>2025-03-29T13:01:20.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0Z87KFK2w45KaytsLGEBjQ.png" /></figure><p>In Elixir, there’s an interesting feature called <strong>function clauses</strong>. It allows us to define multiple functions with the same name, but each handling different patterns of arguments. This guide will introduce function clauses in a simple and easy-to-understand way.</p><h4>What are Function Clauses?</h4><p>Function clauses let us define several versions of a function with the same name, but each version matches different argument patterns. When a function is called, Elixir automatically picks the matching clause based on the arguments provided.</p><p>Here’s a simple example:</p><pre>defmodule Greeting do<br>  def hello(&quot;Elixir&quot;) do<br>    &quot;Hello, Elixir!&quot;<br>  end<br><br>  def hello(name) do<br>    &quot;Hello, #{name}!&quot;<br>  end<br>end<br><br>IO.puts(Greeting.hello(&quot;Elixir&quot;))   # Hello, Elixir!<br>IO.puts(Greeting.hello(&quot;World&quot;))    # Hello, World!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*KhAkmiWoZ2_Jr1I84eFE0Q.png" /></figure><ul><li>The first clause matches only when the argument is &quot;Elixir&quot;.</li><li>The second clause matches any other argument.</li></ul><h4>When to Use Function Clauses?</h4><p>We use function clauses to:</p><ol><li><strong>Simplify Code</strong>: Avoid multiple conditions like if or case by directly using different clauses.</li><li><strong>Clarify Function Intent</strong>: Each clause clearly defines a specific scenario.</li><li><strong>Utilize Pattern Matching</strong>: Easily handle arguments matching specific patterns.</li></ol><h4>More Examples of Function Clauses</h4><p>Here are additional examples to understand function clauses better:</p><ul><li><strong>Using Guards</strong></li></ul><p>Besides patterns, we can add extra conditions using guards (when):</p><pre>defmodule CheckNumber do<br>  def describe(n) when is_integer(n) and n &gt; 0 do<br>    &quot;Positive number&quot;<br>  end<br><br>  def describe(0), do: &quot;Zero&quot;<br><br>  def describe(n) when is_integer(n) and n &lt; 0 do<br>    &quot;Negative number&quot;<br>  end<br><br>  def describe(_), do: &quot;Not a number&quot;<br>end<br><br>IO.puts(CheckNumber.describe(5))    # Positive number<br>IO.puts(CheckNumber.describe(-3))   # Negative number<br>IO.puts(CheckNumber.describe(0))    # Zero<br>IO.puts(CheckNumber.describe(&quot;a&quot;))  # Not a number</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*jP9yB17uL0FG5yxELET97w.png" /></figure><p>Here, guards (when) allow us to specify additional conditions clearly.</p><ul><li><strong>Recursive Functions</strong></li></ul><p>Function clauses are very useful for recursive functions:</p><pre>defmodule Sum do<br>  def total([]), do: 0<br>  def total([head | tail]), do: head + total(tail)<br>end<br><br>IO.puts(Sum.total([1, 2, 3, 4]))  # 10</pre><ul><li>total([]) handles the empty list.</li><li>total([head | tail]) takes the first element (head) and adds it recursively to the sum of the remaining elements (tail).</li></ul><h4>Tips for Using Function Clauses</h4><p>To use function clauses effectively:</p><ul><li><strong>Clause Order Matters</strong>: Elixir checks clauses from top to bottom. Place specific clauses first.</li><li><strong>Use Guards</strong>: Guards make conditions clearer and more readable.</li><li><strong>Limit the Number of Clauses</strong>: If you have too many clauses, consider breaking your function into multiple smaller functions.</li></ul><h4>References</h4><ul><li><a href="https://elixirschool.com/en/lessons/basics/functions"><strong>Elixir School: Functions</strong></a></li><li><a href="https://exercism.org/tracks/elixir/concepts/multiple-clause-functions"><strong>Elixir: Multiple Clause Functions</strong></a></li></ul><h4>Conclusion</h4><p>Function clauses are a powerful Elixir feature that helps us write clean, clear, and efficient code. By mastering pattern matching and guards, we can easily manage different argument scenarios in functions. Hopefully, this guide helps you become more comfortable writing readable and maintainable Elixir</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6c65aa8ad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrency in Elixir: The Basics of 'spawn', 'send', and 'receive']]></title>
            <link>https://medium.com/@qrizan/understanding-concurrency-in-elixir-the-basics-of-spawn-send-and-receive-1300a65df974?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1300a65df974</guid>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 13:02:47 GMT</pubDate>
            <atom:updated>2025-03-22T13:02:47.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pZBipeakG3VUhO_heBqcxA.png" /></figure><p>Modern applications often need <strong>concurrency</strong> — the ability to run multiple processes at the same time — so that the system can be more responsive, efficient, and robust. Unlike many other languages, Elixir provides a simple yet safe concurrency model derived from Erlang’s heritage. In this article, we’ll discuss three core Elixir concurrency concepts: spawn, send, and receive, and see how they work together.</p><h4>Why Concurrency?</h4><ul><li><strong>Better Performance</strong>: By breaking big tasks into multiple parallel processes, we can make better use of available resources.</li><li><strong>Responsiveness</strong>: Applications won’t “lock up” waiting for one process. Other processes can continue running.</li><li><strong>Fault Tolerance</strong>: If one process fails, it doesn’t automatically take down the others, thanks to isolation between processes.</li></ul><h4>What Are Elixir Processes?</h4><p>Elixir processes are not the same as operating system processes. They’re <strong>very lightweight</strong> and can number in the hundreds of thousands or even millions within a single application. Each process does not share memory directly with others; instead, processes communicate using <strong>asynchronous message passing</strong>. This design makes Elixir applications highly reliable and easily scalable.</p><p>Key highlights:</p><ul><li><strong>Lightweight</strong>: Creating and stopping processes doesn’t put too much load on system resources.</li><li><strong>Isolated</strong>: An error in one process doesn’t break other processes.</li><li><strong>Asynchronous</strong>: Sending messages doesn’t block the sender process.</li></ul><h4>Creating a Process with &#39;spawn&#39;</h4><p>To start using concurrency in Elixir, we first create a new process. The spawn function accepts either an anonymous function or a function from a module. Here’s the simplest example:</p><pre>spawn(fn -&gt;<br>  IO.puts(&quot;Hello from a new process!&quot;)<br>end)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*uTf7NLF8snKPiY61y_QGrQ.png" /></figure><p>This code:</p><ol><li>Runs the fn -&gt; ... end block in a separate process.</li><li>Ends the process once the code within finishes executing.</li></ol><p>We can also capture the <strong>PID (Process Identifier)</strong> if we want to interact with the newly created process later:</p><pre>pid = spawn(fn -&gt;<br>  IO.puts(&quot;Hello from a new process!&quot;)<br>end)<br><br>pid<br>#PID&lt;0.110.0&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*htqdPfrk6Wg7P9IYyhKMyQ.png" /></figure><p>The PID is a unique identifier for that process.</p><h4>Sending Messages with &#39;send&#39;</h4><p>Elixir processes communicate by sending messages to each other using the send/2 function:</p><pre>send(pid, message)</pre><ul><li>pid is the identifier of the target process.</li><li>message can be any data type (string, integer, atom, tuple, etc.).</li></ul><p>Example:</p><pre>pid = spawn(fn -&gt;<br>  receive do<br>    msg -&gt;<br>      IO.puts(&quot;Process received a message: #{inspect(msg)}&quot;)<br>  end<br>end)<br><br>send(pid, &quot;Hello!&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*FME13R-9-xQzdN2cZihyJQ.png" /></figure><p>We created a new process that uses receive to wait for a single message. When we send the string &quot;Hello!&quot;, the process prints:</p><pre>Process received a message: &quot;Hello!&quot;</pre><h4>Receiving Messages with &#39;receive&#39;</h4><p>Inside a process, we use the receive block to check its message queue. The process will wait for messages that match the defined patterns. For example:</p><pre>receive do<br>  {:hello, name} -&gt;<br>    IO.puts(&quot;Hello, #{name}!&quot;)<br>  :done -&gt;<br>    IO.puts(&quot;Process finished.&quot;)<br>  _other -&gt;<br>    IO.puts(&quot;Unknown message.&quot;)<br>end</pre><ul><li>{:hello, name} captures a tuple with the atom :hello and one additional argument.</li><li>:done captures a message that is just the atom :done.</li><li>_other captures any message that doesn’t match the previous patterns.</li></ul><p>In practice, we often write a recursive function so the process can <strong>continuously</strong> wait for messages. For instance:</p><pre>defmodule MessageReceiver do<br>  def start do<br>    receive do<br>      {:hello, name} -&gt;<br>        IO.puts(&quot;Hello, #{name}!&quot;)<br>      :done -&gt;<br>        IO.puts(&quot;Process finished.&quot;)<br>      _ -&gt;<br>        IO.puts(&quot;Unknown message.&quot;)<br>    end<br><br>    start()  # Call itself to keep the process active<br>  end<br>end<br><br>pid = spawn(MessageReceiver, :start, [])<br>send(pid, {:hello, &quot;Elixir&quot;})<br># Output: Hello, Elixir!<br>send(pid, :done)<br># Output: Process finished.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*5hCpcT4qM9RvcvMgVLUFyA.png" /></figure><p>After receiving :done, we could stop the process by not calling start() again or using another termination mechanism as needed.</p><h4>Conclusion</h4><p>By understanding spawn, send, and receive, we’ve grasped the essential building blocks of Elixir’s concurrency model. Because processes in Elixir are lightweight and isolated, our applications can become more scalable and resilient to errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1300a65df974" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Structs and Maps in Elixir]]></title>
            <link>https://medium.com/@qrizan/understanding-structs-and-maps-in-elixir-51d40ab29794?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/51d40ab29794</guid>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[mapstruct]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 13:02:34 GMT</pubDate>
            <atom:updated>2025-03-15T13:02:34.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-_pP7D-qETVBjurwLloTiA.png" /></figure><p>In Elixir, there are two commonly used data structures to store key-value pairs:<strong> Maps and Structs</strong>. While similar, they serve slightly different purposes. This article clearly explains their differences, usage examples, and when to choose a Map or a Struct.</p><h4>Understanding Maps in Elixir</h4><p>A map is a simple key-value data structure, similar to dictionaries in other programming languages. With maps, we can easily store data with key-value pairs.</p><p><strong>Example:</strong></p><pre>user = %{name: &quot;Alice&quot;, age: 30, city: &quot;Jakarta&quot;}</pre><p>Accessing data from a Map:</p><pre>IO.puts(user.name)    # Alice<br>IO.puts(user[:age])   # 30</pre><p>Updating a Map:</p><pre>updated_user = %{user | age: 31}<br>IO.inspect(updated_user)<br># Result: %{name: &quot;Alice&quot;, age: 31, city: &quot;Jakarta&quot;}</pre><p>Maps are flexible, allowing easy addition or removal of fields.</p><h4>Understanding Structs in Elixir</h4><p>Structs are specialized Maps with a clearly defined structure. They ensure data consistency according to the original definition.</p><p><strong>Example:</strong></p><pre>defmodule User do<br>  defstruct id: nil, name: nil, age: 0<br>end</pre><p>After defining a Struct, we can use it directly:</p><pre>user = %User{id: 1, name: &quot;Alice&quot;, age: 30}<br>IO.puts(user.name) # Alice</pre><p>The advantage of Structs over Maps is that Structs ensure data consistency. We can’t randomly add new fields:</p><pre># This will cause an error, as &#39;country&#39; is not defined in the Struct<br>user_invalid = %{user | country: &quot;Indonesia&quot;}</pre><h4>Practical Example in Elixir (Struct &amp; Map)</h4><p>Here is a simple application example for managing user data. We use Structs to <em>ensure consistent user data</em> and Maps to<em> store all users conveniently</em>.</p><p>Complete example we can run directly in IEx:</p><pre>defmodule User do<br>  defstruct id: nil, name: nil, age: 0<br>end<br><br>defmodule UserManager do<br>  defstruct users: %{}<br><br>  # Add a new user to the users Map<br>  def add_user(manager, %User{id: id} = user) do<br>    %{manager | users: Map.put(manager.users, id, user)}<br>  end<br><br>  # Get user by ID<br>  def get_user(manager, id) do<br>    Map.get(manager.users, id)<br>  end<br><br>  # List all users<br>  def list_users(manager) do<br>    Map.values(manager.users)<br>  end<br>end</pre><p><strong>How to Run in IEx:</strong></p><p>Copy the above code into IEx session</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Aeyy0AQfloEzv_x25YVaaA.png" /></figure><p>Then enter the following commands:</p><pre>manager = %UserManager{}<br><br>manager = UserManager.add_user(manager, %User{id: 1, name: &quot;Alice&quot;, age: 30})<br>manager = UserManager.add_user(manager, %User{id: 2, name: &quot;Bob&quot;, age: 25})<br><br>alice = UserManager.get_user(manager, 1)<br>IO.inspect(alice, label: &quot;Alice&#39;s Data&quot;)<br><br>users = UserManager.list_users(manager)<br>IO.inspect(users, label: &quot;All Users&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*KxOY84BDruyQEOqcux37Ww.png" /></figure><p>Output:</p><pre>Alice&#39;s Data: %User{age: 30, id: 1, name: &quot;Alice&quot;}<br><br>All Users: [<br>  %User{age: 30, id: 1, name: &quot;Alice&quot;},<br>  %User{age: 25, id: 2, name: &quot;Bob&quot;}<br>]</pre><h4>When to Use Maps or Structs?</h4><ul><li><strong>Use Maps</strong> for flexible, changing data such as configurations, metadata, or API responses.</li><li><strong>Use Structs</strong> for data with a fixed, consistent structure, such as user profiles or application entities. Structs ensure clarity and data safety.</li></ul><h4>References</h4><ul><li><a href="https://www.tutorialspoint.com/elixir/elixir_maps.htm">Elixir — Maps</a></li><li><a href="https://www.tutorialspoint.com/elixir/elixir_structs.htm">Elixir — Structs</a></li></ul><h4>Conclusion</h4><p>Both <strong>Structs and Maps</strong> are useful for managing data in Elixir. <em>Structs ensure data consistency and a clear structure</em>, while <em>Maps offer flexibility for dynamic data</em>. Knowing when to use each will help us create clear, organized, and maintainable Elixir applications..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51d40ab29794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Tasks in Elixir: A Simple Introduction]]></title>
            <link>https://medium.com/@qrizan/working-with-tasks-in-elixir-a-simple-introduction-104247e33b50?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/104247e33b50</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[basics-elixir]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 13:02:42 GMT</pubDate>
            <atom:updated>2025-03-08T13:02:42.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KJuk4ihpERf3jkt3HpbBOQ.png" /></figure><p>Elixir runs on the <strong>Erlang VM</strong>, known for handling concurrency smoothly. One of the easiest ways to leverage this is by using the <strong>Task module</strong>. Tasks let you run functions in separate processes so they don’t block your main flow. Here’s a quick, beginner-friendly look at how to use them.</p><h4>Introducing a Function</h4><p>Imagine we want a function that simulates heavy work, sleeping for a couple of seconds, then returning a result. In IEx, you can define:</p><pre>defmodule MathTasks do<br>  def square(number) do<br>    IO.puts(&quot;Calculating square of #{number}...&quot;)<br>    :timer.sleep(2000)  # simulating a long operation<br>    result = number * number<br>    IO.puts(&quot;Result: #{result}&quot;)<br>    result<br>  end<br>end</pre><p>After typing this in IEx, the function exists in our current session. Calling:</p><pre>MathTasks.square(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*fHshXR_RAQYSs5xd7iAnZw.png" /></figure><p>prints two messages and returns 100 after a 2-second pause. The function runs only when invoked, so we see real output at that moment.</p><ul><li><strong>Running Multiple Tasks in Parallel</strong></li></ul><p>If we want to call square/1 on several numbers at once, use Task.async and Task.await:</p><pre>numbers = [10_000, 20_000, 30_000]<br><br>tasks =<br>  Enum.map(numbers, fn n -&gt;<br>    Task.async(fn -&gt; MathTasks.square(n) end)<br>  end)<br><br>results =<br>  Enum.map(tasks, fn task -&gt;<br>    Task.await(task, 5000)  # waits up to 5 seconds<br>  end)<br><br>IO.inspect(results, label: &quot;Squares&quot;)</pre><p>Each item in numbers runs in its own process, and we wait for each to finish (up to five seconds). Because these calls run <strong>concurrently</strong>, the overall time is similar to just the longest single run—rather than adding up for each number.</p><blockquote><strong><em>Important:</em></strong><em> Make sure the </em><em>MathTasks module is defined in the </em>same<em> IEx session (or compiled from a file) so the new Task processes recognize it.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*Ir6ubcHI9ROyFEOw8keHYw.png" /></figure><h4>Starting a Task Without Waiting</h4><p>Sometimes we don’t need a result back. In that case, Task.start runs a function in the background:</p><pre>Task.start(fn -&gt;<br>  IO.puts(&quot;Background task started...&quot;)<br>  :timer.sleep(2000)<br>  IO.puts(&quot;Background task done!&quot;)<br>end)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ZSuon_sXzX49nVw-Jy15mA.png" /></figure><p>This doesn’t block our main process. We won’t get a return value, but we can continue other work immediately.</p><h4>References</h4><ul><li><a href="https://hexdocs.pm/elixir/1.13/Task.html">Elixir Documentation — Task</a></li><li><a href="https://elixirbyexample.com/task">Elixir By Example — Task</a></li></ul><h4>Conclusion</h4><p>By splitting heavy operations across processes, you can handle long computations or external calls without freezing your main flow. This approach keeps your application responsive and leverages the concurrency strengths of the Erlang VM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=104247e33b50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding GenServer in Elixir: A Flexible Way to Manage State]]></title>
            <link>https://medium.com/@qrizan/understanding-genserver-in-elixir-a-flexible-way-to-manage-state-1379ac382eef?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1379ac382eef</guid>
            <category><![CDATA[genserver]]></category>
            <category><![CDATA[elixirlang]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 13:02:17 GMT</pubDate>
            <atom:updated>2025-03-01T13:02:17.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5kGHf7PRcJnFyegc2G0zcg.png" /></figure><p>When we dive deeper into Elixir, we often come across <strong>GenServer</strong>, a core part of Elixir’s <strong>OTP (Open Telecom Platform)</strong>. While Agents allow us to handle simple state (like getting or updating data), GenServer provides more control over the process life cycle, message handling, error management, and timeouts. In this article, we’ll explore how GenServer works and why it’s so vital for building stateful applications in Elixir.</p><h4>What Is GenServer?</h4><ul><li><strong>It’s a Process</strong><br>Just like an Agent, a GenServer is a process running on the Erlang VM (BEAM).</li><li><strong>It Uses Callbacks</strong><br>Agents focus on simple get/update operations, whereas GenServer relies on callbacks such as handle_call/3, handle_cast/2, and handle_info/2 to manage messages in a structured way.</li><li><strong>It Maintains State</strong><br>A GenServer keeps internal state between function calls, letting us update data as needed.</li><li><strong>It’s More Flexible</strong><br>We can handle timeouts, unexpected messages, and choose between synchronous (call) or asynchronous (cast) operations.</li></ul><h4>A Simple GenServer Example</h4><p>Let’s create a CounterServer module that manages an integer:</p><pre>defmodule CounterServer do<br>  use GenServer<br><br>  # -- PUBLIC API --<br><br>  # Starts the GenServer with an optional initial value<br>  def start_link(initial_value \\ 0) do<br>    GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)<br>  end<br><br>  # Retrieves the current value<br>  def get_value do<br>    GenServer.call(__MODULE__, :get_value)<br>  end<br><br>  # Increments the current value by 1<br>  def increment do<br>    GenServer.cast(__MODULE__, :increment)<br>  end<br><br>  # -- CALLBACKS --<br><br>  @impl true<br>  def init(initial_value) do<br>    # Set the initial state<br>    {:ok, initial_value}<br>  end<br><br>  @impl true<br>  def handle_call(:get_value, _from, state) do<br>    # Respond with the current state<br>    {:reply, state, state}<br>  end<br><br>  @impl true<br>  def handle_cast(:increment, state) do<br>    # Increase the state by 1<br>    {:noreply, state + 1}<br>  end<br>end</pre><p><strong>How It Works</strong></p><ul><li><strong>use GenServer</strong>: Includes GenServer functionality in our module.</li><li><strong>start_link/2</strong>: Launches the GenServer with an optional initial value, and registers it under the module name CounterServer.</li><li><strong>init/1</strong>: Called when the GenServer starts. We return {:ok, initial_value} as the initial state.</li><li><strong>handle_call(:get_value, ...)</strong>: Handles a synchronous request (GenServer.call). We return {:reply, state, state}, giving the caller our state while keeping state unchanged.</li><li><strong>handle_cast(:increment, ...)</strong>: Handles an asynchronous request (GenServer.cast). We add 1 to the current state and return {:noreply, state + 1}.</li></ul><h4>Trying It Out in IEx</h4><p>We can test the code above directly in IEx:</p><ul><li><strong>Open IEx</strong></li></ul><pre>iex</pre><ul><li><strong>Define the Module</strong></li></ul><p>Paste the CounterServer code into IEx and press Enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*hSFRJlfNKktazIAE9uzU1A.png" /></figure><ul><li><strong>Start the GenServer</strong></li></ul><pre>CounterServer.start_link()</pre><ul><li><strong>Check the Initial Value</strong></li></ul><pre>CounterServer.get_value()<br># Returns 0</pre><ul><li><strong>Increment</strong></li></ul><pre>CounterServer.increment()<br>CounterServer.get_value()<br># Returns 1</pre><p>Now we have a GenServer that stores and updates a simple counter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*f7sJtXfNQ6rCyvUxcbaxhQ.png" /></figure><h4>Types of Messages</h4><p><strong>Synchronous Call</strong></p><ul><li>Uses GenServer.call(server, message).</li><li>The caller waits for a reply from handle_call/3.</li><li>Ideal for operations where we need an immediate response, like fetching data or performing a calculation that must be returned.</li></ul><p><strong>Asynchronous Cast</strong></p><ul><li>Uses GenServer.cast(server, message).</li><li>The caller does not wait for a reply (fire-and-forget).</li><li>Great for updates that don’t need a direct response.</li></ul><p><strong>Info Messages</strong></p><ul><li>Handled in handle_info/2 for messages that don’t fit into call or cast, such as timeouts or internal system messages.</li></ul><h4>State and Business Logic</h4><p>Unlike Agents, which focus on simple “get and update,” GenServer allows us to write more comprehensive logic within callbacks. For example:</p><ul><li><strong>Complex Calculations</strong><br>If we need to inspect a significant amount of data before updating the state, we can do that in handle_call/3 or handle_cast/2.</li><li><strong>Scheduled Operations</strong><br>We can set timeouts for our GenServer and handle them in handle_info/2.</li><li><strong>Error Handling</strong><br>Should an error occur, GenServer can be restarted by the OTP supervisor (if included in a supervision tree), making the system more resilient.</li></ul><h4>When Should We Use GenServer?</h4><ol><li><strong>We Need More Than Simple Get/Update</strong><br>If we need scheduling, multiple message types, or more advanced processing, GenServer is the right tool.</li><li><strong>We Have Larger or More Complex State</strong><br>GenServer is flexible for managing data that might grow and change frequently.</li><li><strong>We Want Both Synchronous and Asynchronous Access</strong><br>GenServer accommodates calls (call) and casts (cast) depending on whether we need a response.</li><li><strong>We Want to Leverage OTP Patterns</strong><br>GenServer integrates seamlessly with supervision trees, registries, PubSub, and more, supporting robust and fault-tolerant applications.</li></ol><h4>Tips and Best Practices</h4><ul><li><strong>Avoid Heavy Tasks in </strong><strong>handle_call/3</strong><br>The caller is blocked until a reply is returned. For lengthy tasks, consider splitting them off into separate processes (like Task).</li><li><strong>Choose Between </strong><strong>call and </strong><strong>cast Carefully</strong><br>Use call when you need a result to be returned, and cast for quick updates that don’t require a response.</li><li><strong>Use Monitoring/Debugging Tools</strong><br>Running :observer.start() in IEx lets us observe processes, memory usage, and message flow in real time.</li><li><strong>Watch Your State Size</strong><br>If the data grows large or needs to be permanent, consider a database (like Ecto) or caching solutions (ETS, Cachex).</li></ul><h4>References</h4><ul><li><a href="https://hexdocs.pm/elixir/GenServer.html"><strong>Elixir Documentation: Genserver</strong></a></li><li><a href="https://elixir-lang.org/downloads/cheatsheets/gen-server.pdf"><strong>GenServer — a cheat sheet</strong></a></li><li><a href="https://www.scoutapm.com/elixirs-genservers-overview-and-tutorial/"><strong>Elixir GenServers: Overview and Tutorial</strong></a></li></ul><h4>Conclusion</h4><p><strong>GenServer</strong> is a cornerstone of many <strong>OTP</strong>-driven applications in Elixir, giving us structured state management and powerful message handling. Through callbacks like handle_call/3 and handle_cast/2, we decide how our system processes messages and evolves its state.</p><p>While Agents are great for simpler scenarios, GenServer becomes essential when we need a more detailed process model, mixing synchronous and asynchronous communication or tighter integration with OTP features. By learning GenServer, we harness the full concurrency power of the Erlang VM to build reliable and fault-tolerant systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1379ac382eef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Agents in Elixir: A Simple Way to Store Changing Data]]></title>
            <link>https://medium.com/@qrizan/understanding-agents-in-elixir-a-simple-way-to-store-changing-data-4953860f4736?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4953860f4736</guid>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 13:01:55 GMT</pubDate>
            <atom:updated>2025-02-22T13:01:55.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Sp8WQF--HOPgbTO-1p3B5A.png" /></figure><p>When we start learning <strong>Elixir</strong>, one question that often comes up is how to manage data that changes over time — such as a <strong>counter</strong> or a <strong>cache</strong>. Luckily, Elixir provides a straightforward solution: <strong>Agent</strong>. In this article, we’ll explore what Agents are, why they’re helpful, and how we can work with them step by step.</p><h4>Why Do We Need Agents?</h4><p>In functional programming, data is <strong>immutable</strong> — once created, we don’t directly modify it. But sometimes, we need a way to store information that’s updated regularly. That’s where <strong>Agent</strong> comes in.</p><p>Think of an Agent as a “storage box” living in a separate process. This box can hold data for us. Whenever we want to retrieve or update that data, we open the box, look at what’s inside, or put in something new.</p><p><strong>Key Benefits of Agents:</strong></p><ul><li><strong>Easy to Use:</strong> Compared to GenServer, which involves more callbacks, Agents focus on simple read/update functions.</li><li><strong>Ideal for Temporary Data:</strong> We can store things like counters, small caches, or to-do lists that don’t need a database.</li><li><strong>Lightweight:</strong> An Agent runs as a single process, but can be accessed from anywhere in our application</li></ul><h4>Creating Our First Agent</h4><p>Let’s create a Counter module that stores a single number:</p><pre>defmodule Counter do<br>  use Agent<br><br>  # Start the Agent with an initial value (default is 0)<br>  def start_link(initial_value \\ 0) do<br>    Agent.start_link(fn -&gt; initial_value end, name: __MODULE__)<br>  end<br><br>  # Read the current value<br>  def get_value do<br>    Agent.get(__MODULE__, fn state -&gt; state end)<br>  end<br><br>  # Increment the current value by 1<br>  def increment do<br>    Agent.update(__MODULE__, fn state -&gt; state + 1 end)<br>  end<br>end</pre><p>Here’s what we’re doing:</p><ol><li>We use Agent to tap into built-in Agent functionality.</li><li>We define start_link/1 to launch the Agent with an optional initial_value (default is 0).</li><li>The function fn -&gt; initial_value end specifies the initial data for our Agent.</li><li>By setting name: __MODULE__, we name the Agent after this module (Counter), making it easy to reference.</li><li>We provide get_value and increment functions to read or update the stored number.</li></ol><p><strong>Trying It Out in IEx</strong></p><p>Open our terminal and run:</p><pre>iex</pre><ul><li><strong>Define the Module</strong></li></ul><p>Copy and paste the Counter module code into IEx, then press Enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Pt0OkgKniRUgWWbrpfNLcw.png" /></figure><ul><li><strong>Start the Agent</strong></li></ul><pre>Counter.start_link()</pre><ul><li><strong>Check the Initial Value</strong></li></ul><pre>Counter.get_value()<br># Returns 0 by default</pre><ul><li><strong>Increment</strong></li></ul><pre>Counter.increment()<br>Counter.get_value()<br># Returns 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*8QIzA45S43RhNyaREpSNFQ.png" /></figure><p>We’ve successfully created and managed data in memory without any complex process logic.</p><h4>Storing More Than Just Numbers</h4><p>Agents aren’t limited to a single integer. We can store <strong>lists</strong>, <strong>maps</strong>, or any other data structure. Let’s look at a simple <strong>to-do list</strong> example:</p><pre>defmodule TodoList do<br>  use Agent<br><br>  def start_link(initial_items \\ []) do<br>    # Start the Agent with an initial list (by default, an empty list)<br>    Agent.start_link(fn -&gt; initial_items end, name: __MODULE__)<br>  end<br><br>  def add_item(item) do<br>    # Update the list by prepending a new item<br>    Agent.update(__MODULE__, fn items -&gt; [item | items] end)<br>  end<br><br>  def get_all do<br>    # Retrieve the current list<br>    Agent.get(__MODULE__, fn items -&gt; items end)<br>  end<br><br>  def remove_item(item) do<br>    # Remove the specified item from the list<br>    Agent.update(__MODULE__, fn items -&gt; List.delete(items, item) end)<br>  end<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*VaySTa_qh36KgDpLGk2p-g.png" /></figure><p>Here’s a breakdown of what’s happening in the TodoList module:</p><ul><li><strong>use Agent</strong>: We include the Agent functionality.</li><li><strong>start_link/1</strong>: We start the Agent with an optional initial list (initial_items). By default, it uses an empty list [].</li><li><strong>add_item/1</strong>: We prepend a new item to the existing list.</li><li><strong>get_all/0</strong>: We read all current items from the list (returning them as is).</li><li><strong>remove_item/1</strong>: We delete a given item from the list using List.delete/2.</li></ul><p>Once we compile this code in IEx, we can run:</p><pre>TodoList.start_link()<br>TodoList.add_item(&quot;Learn Elixir&quot;)<br>TodoList.add_item(&quot;Explore Agents&quot;)<br>TodoList.get_all()<br># [&quot;Explore Agents&quot;, &quot;Learn Elixir&quot;]<br>TodoList.remove_item(&quot;Learn Elixir&quot;)<br>TodoList.get_all()<br># [&quot;Explore Agents&quot;]</pre><p>This showcases how Agents make it easy to maintain small sets of data without needing a database setup.</p><h4>Understanding &#39;name: __MODULE__&#39;</h4><ul><li>__MODULE__ is a special macro that returns the module’s name (like :&quot;Elixir.Counter&quot;).</li><li>By setting name: __MODULE__, we register our Agent under the same name as the module.</li><li>Even though the Agent is defined in Counter or TodoList, any part of our application can refer to it by that name, rather than dealing with process IDs (PIDs).</li></ul><h4>When Should We Use Agents?</h4><ul><li><strong>Data Doesn’t Require Persistent Storage</strong><br>If we don’t need to write data to a database or disk, Agents are often enough.</li><li><strong>Data Is Small or Temporary</strong><br>Agents keep data in memory, so if our data might grow too large, this may not be the right approach.</li><li><strong>Simple Read/Update</strong><br><em>Agents</em> are great for straightforward operations. If we need transactional logic or more complex patterns, a <em>GenServer</em> or a database solution (like <em>Ecto</em>) might be better.</li></ul><h4>Quick Tips</h4><ul><li><strong>Keep Agent Logic Simple:</strong> Limit Agents to storing and updating data. Put more complex logic elsewhere.</li><li><strong>Use Supervisors in Production:</strong> Typically, we’ll add Agents to a supervision tree, so they restart automatically on failure.</li><li><strong>Be Mindful of Concurrent Access:</strong> Multiple processes might update an Agent at the same time, so plan accordingly for potential conflicts.</li></ul><h4>References</h4><ul><li><a href="https://hexdocs.pm/elixir/Agent.html"><strong>Elixir Documentation: Agent</strong></a></li><li><a href="https://elixirschool.com/en/lessons/intermediate/concurrency#agents-4"><strong>Elixir School: Agent</strong></a></li></ul><h4>Conclusion</h4><p><strong>Agents</strong> offer a quick and easy way to handle changing data in Elixir. With just a few lines of code, we can store, retrieve, and modify data in memory — perfect for small-scale use cases, quick prototypes, or certain features that don’t need to live in a database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4953860f4736" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutability and Variable Binding in Elixir]]></title>
            <link>https://medium.com/@qrizan/immutability-and-variable-binding-in-elixir-512fa14d30e9?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/512fa14d30e9</guid>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 13:01:49 GMT</pubDate>
            <atom:updated>2025-02-22T10:41:51.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*s9XhebIeHqwjF17Cgn2lKg.png" /></figure><p>Elixir is a modern <strong>functional programming</strong> language that runs on the Erlang VM (BEAM). It’s often praised for its ability to handle massive concurrency while remaining reliable and fault-tolerant. A key concept in Elixir is <strong>immutability</strong>, which means we treat data as something that cannot be changed after it’s created. In this article, we will discuss how immutability works in Elixir, explore its unique approach to variable binding, and see how it compares to more traditional imperative languages.</p><h4>Immutability</h4><p>In Elixir, data structures (like lists, maps, tuples, and structs) are <strong>immutable</strong>. Once we create a piece of data, it stays the same forever. If we want to “change” it, Elixir actually creates a <strong>new</strong> data structure based on the old one, leaving the original data untouched.</p><p>For example, consider the following list:</p><pre>original_list = [1, 2, 3]<br>new_list = [0 | original_list]<br><br># original_list remains [1, 2, 3]<br># new_list becomes [0, 1, 2, 3]</pre><p>Although it appears that we added 0 to the existing list, Elixir simply created a new list with 0 as the head and referenced the old list as its tail. This approach helps us avoid unexpected side effects and makes it much easier to manage concurrency in our applications.</p><h4>Variable Binding in Elixir</h4><p>Elixir doesn’t use assignment in the same way many imperative languages do. When we write:</p><pre>iex&gt; x = 10<br>10<br>iex&gt; x = 20<br>20</pre><p>we might assume that x changed from 10 to 20. However, Elixir is actually creating a <strong>new binding</strong> for x in the current scope, without mutating the old value. Here’s a slightly more detailed example:</p><pre>defmodule Example do<br>  def demonstrate_binding do<br>    x = 5<br>    IO.puts(&quot;Initial x: #{x}&quot;) <br>    # Prints: Initial x: 5<br><br>    x = x + 10<br>    IO.puts(&quot;x after &#39;change&#39;: #{x}&quot;)<br>    # Prints: x after &#39;change&#39;: 15<br>  end<br>end<br><br>Example.demonstrate_binding()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*RA87wdYLQT1kfQm2vw4DYA.png" /></figure><p>In this code, when we write x = x + 10, Elixir calculates 5 + 10 = 15 and then binds x to 15. The original x = 5 is not actually altered; Elixir just points x to a new value. This design ensures that we do not unknowingly alter data elsewhere in our program.</p><h4>Pattern Matching and Immutability</h4><p>Elixir uses <strong>pattern matching</strong> to destructure and compare data. The = operator in Elixir doesn’t just assign a value; it matches a value against a pattern:</p><pre>iex&gt; {a, b} = {1, 2}<br>{1, 2}<br>iex&gt; a<br>1<br>iex&gt; b<br>2</pre><p>If the structure on the left does not match the data on the right, Elixir raises a MatchError. Under the hood, immutability complements pattern matching by ensuring that we are only reading the data, not rewriting it in place.</p><p>Here’s a short code snippet that safely handles mismatched patterns:</p><pre>defmodule SafeMatcher do<br>  def safe_match(tuple) do<br>    try do<br>      {a, b} = tuple<br>      {:ok, a + b}<br>    rescue<br>      MatchError -&gt; {:error, &quot;Mismatched tuple&quot;}<br>    end<br>  end<br>end</pre><p>If tuple doesn’t match the shape {a, b}, we get {:error, &quot;Mismatched tuple&quot;} instead of a crash.</p><h4>Comparing with Imperative Languages</h4><ul><li><strong>Python</strong></li></ul><p>In Python, lists are mutable. If we do this:</p><pre>list_a = [1, 2, 3]<br>list_b = list_a<br>list_b.append(4)<br><br>print(list_a)  # [1, 2, 3, 4]<br>print(list_b)  # [1, 2, 3, 4]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*TMs-7UM_xYoPShLmTQL26Q.png" /></figure><p>Both list_a and list_b end up with [1, 2, 3, 4] because they reference the same underlying list, and the append operation mutates it in-place.</p><ul><li><strong>JavaScript</strong></li></ul><p>JavaScript also allows in-place mutation on arrays:</p><pre>let arrA = [1, 2, 3];<br>let arrB = arrA;<br>arrB.push(4);<br><br>console.log(arrA); // [1, 2, 3, 4]<br>console.log(arrB); // [1, 2, 3, 4]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*Jsl-ec37NFgAgnwJd-eCOg.png" /></figure><p>Again, both arrA and arrB end up pointing to the same updated array.</p><ul><li><strong>Elixir</strong></li></ul><pre>list_a = [1, 2, 3]<br>list_b = list_a<br>list_b = list_b ++ [4]<br><br>IO.inspect(list_a) # [1, 2, 3]<br>IO.inspect(list_b) # [1, 2, 3, 4]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*F7DGGs99-rY8PA8EwATH8A.png" /></figure><p>Here, list_a remains [1, 2, 3], and list_b becomes a completely new list [1, 2, 3, 4]. No mutation takes place on the old list.</p><h4>Why Immutability Matters</h4><ul><li><strong>Data Safety</strong></li></ul><p>Because data can’t change once it’s created, we reduce the risk of accidental or hidden updates. Our data structures are always consistent, which makes our code easier to reason about.</p><ul><li><strong>Concurrency Made Easier</strong></li></ul><p>Elixir’s concurrency model, inherited from Erlang, relies on processes that share no mutable state. Since our data is immutable, we can safely pass it between processes without worrying that one process will overwrite values used by another.</p><ul><li><strong>Predictable and Testable Code</strong></li></ul><p>When every operation that appears to modify data actually creates a new version, we avoid side effects. A function given the same inputs will produce the same outputs every time, which simplifies testing and debugging.</p><h4>References</h4><ul><li><a href="https://www.tutorialspoint.com/elixir/elixir_variables.htm"><strong>Elixir — Variables</strong></a></li><li><a href="https://clouddevs.com/elixir/immutability-and-data-structures/#:~:text=Immutability%20is%20a%20core%20principle,constant%20and%20cannot%20be%20modified."><strong>Understanding Elixir’s Immutability</strong></a></li></ul><h4>Conclusion</h4><p>In Elixir, we treat data as something that cannot be changed once created. Instead of updating existing data, we create new versions whenever something needs to “change.”</p><p>This approach helps us write code that is easier to follow and debug, because we always know that our data isn’t being modified behind the scenes. It also makes concurrency simpler and safer, since multiple processes can share data without interfering with each other.</p><p>By embracing immutability, we build more reliable and fault-tolerant systems, which in turn makes our development experience smoother and more enjoyable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512fa14d30e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Looping in Elixir: A Friendly Guide for Beginners]]></title>
            <link>https://medium.com/@qrizan/looping-in-elixir-a-friendly-guide-for-beginners-1a095838bd3e?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a095838bd3e</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[looping-in-elixir]]></category>
            <category><![CDATA[elixirlang]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 13:01:37 GMT</pubDate>
            <atom:updated>2025-02-08T13:01:37.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mMAB9MNXAbzMU9zwHvgjdw.png" /></figure><p>Have we begun exploring Elixir and noticed it doesn’t provide a standard for or while loop like other languages? Elixir takes a unique approach to iteration that might feel different at first, but it’s actually quite powerful once we get the hang of it.</p><p>Before we dive in, let’s make sure Elixir is installed on our machine. We can write our code in a .exs file and run it with elixir filename.exs, or we can open IEx (Interactive Elixir) in a terminal to experiment in real time.</p><h4>Why Doesn’t Elixir Use Traditional Loops?</h4><p>Elixir is a functional programming language that runs on the Erlang VM (BEAM). In functional programming, our goal is to minimize side effects — like mutating variables in place. Traditional loops often involve something like i++, which modifies state. Instead, Elixir encourages <strong>recursion</strong> and higher-level collection transformations (with Enum or list comprehensions). While this can seem a bit unusual at first, it can lead to cleaner, more maintainable code in the long run.</p><h4>Recursion</h4><ul><li><strong>Basic Recursion Concept</strong></li></ul><p>In Elixir, recursion is a fundamental way to process data repeatedly. We write a function that calls itself, transforming the data with each step, until it meets a stopping condition.</p><p>For example, let’s print numbers from n down to 1:</p><pre>defmodule ExampleRecursion do<br><br>  # When n is less than or equal to 0, we stop by returning :ok<br>  def print_numbers(n) when n &lt;= 0, do: :ok<br><br>  # Otherwise, we print the current n and call print_numbers(n-1)<br>  def print_numbers(n) do<br>    IO.puts(n)<br>    print_numbers(n - 1)<br>  end<br><br>end<br><br># Calling print_numbers(5) will print numbers from 5 down to 1<br>ExampleRecursion.print_numbers(5)<br># Output:<br># 5<br># 4<br># 3<br># 2<br># 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*CZpTtlMOobmNg6hHp2I9og.png" /></figure><ul><li><strong>Tail Recursion</strong></li></ul><p>Elixir supports <em>tail recursion</em>, meaning if our recursive call is the last expression in a function, Elixir can optimize it to avoid building up the call stack. This becomes especially helpful when dealing with large data sets.</p><p>Let’s see how we can sum a list using tail recursion:</p><pre>defmodule TailRecursion do<br><br>  # If the list is empty, return the accumulator (our final sum)<br>  def sum_list([], acc), do: acc<br><br>  # Otherwise, add the head of the list to acc, then recurse on the tail<br>  def sum_list([head | tail], acc) do<br>    sum_list(tail, acc + head)<br>  end<br><br>end<br><br># We start the accumulator at 0, summing up each element<br>IO.puts TailRecursion.sum_list([1, 2, 3, 4, 5], 0)<br># Output: 15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Qyn1KNOOCJDLpUs0vBrjLQ.png" /></figure><p>Since sum_list(tail, acc + head) is called at the end of the function, Elixir applies tail call optimization, letting us process bigger lists safely.</p><h4>The ‘Enum&#39; Module</h4><p>Sometimes, we don’t want to write recursion ourselves. That’s where Enum shines. It offers many functions to work with collections (lists, maps, etc.), such as:</p><ul><li>Enum.each to perform an action on each element (without returning a new list)</li><li>Enum.map to transform each element and return a new list</li><li>Enum.reduce to combine all elements into a single value</li><li>Additional helpers like Enum.filter, Enum.reject, Enum.sort, and more</li></ul><p>Here are a few examples:</p><pre># We have a list of integers<br>list = [1, 2, 3, 4, 5]<br><br># 1) Perform an action on each element<br># In this case, we print each number to the console<br>Enum.each(list, fn x -&gt; IO.puts(&quot;Number: #{x}&quot;) end)<br><br># 2) Transform each element, creating a new list<br># Here, we multiply each number by 2<br># Enum.map returns a new list with the transformed values<br>doubled = Enum.map(list, fn x -&gt; x * 2 end)<br>IO.inspect(doubled)<br># [2, 4, 6, 8, 10]<br><br># 3) Combine elements into a single value<br># We start from 0, then add each element to our accumulator<br># The final result is the sum of the list<br>total = Enum.reduce(list, 0, fn x, acc -&gt; x + acc end)<br>IO.puts(&quot;Total: #{total}&quot;)<br># 15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*sJvX_nzSTP4d-kL9s_derQ.png" /></figure><p><strong>Enum vs. Stream</strong></p><p>If we’re curious about when to use Enum versus Stream, we can check out <strong>&quot;</strong><a href="https://medium.com/@qrizan/elixir-essentials-a-simple-comparison-of-enum-and-stream-for-data-processing-948b4a506c39"><strong>Elixir Essentials: A Simple Comparison of Enum and Stream for Data Processing.</strong></a><strong>&quot;</strong> In a nutshell, Enum evaluates eagerly (all at once), while Stream evaluates lazily (on demand). This distinction matters if we need to handle very large data sets efficiently.</p><h4>List Comprehension</h4><p>Elixir provides a for keyword, but it’s not used for traditional looping. Instead, it’s a way to generate new lists based on existing ones—also known as <strong>list comprehension</strong>.</p><pre># We have a list of numbers<br>list = [1, 2, 3, 4, 5]<br><br># Create a new list where each element is doubled<br>doubled = for x &lt;- list do<br>  x * 2<br>end<br><br>IO.inspect(doubled)<br># [2, 4, 6, 8, 10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*sP5_FuvtjoapBTYx39F4ww.png" /></figure><ul><li><strong>Adding Filters</strong></li></ul><p>We can also filter the elements that we want to include in the new list:</p><pre># Only include even numbers<br>only_evens = for x &lt;- list, rem(x, 2) == 0 do<br>  x<br>end<br><br>IO.inspect(only_evens)<br># [2, 4]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*H3iCIoZ3J6QhmHsZPZcITg.png" /></figure><ul><li><strong>Using Multiple Generators</strong></li></ul><p>List comprehensions can process multiple lists at the same time:</p><pre># Generate pairs from two lists<br>pairs = for x &lt;- [1, 2], y &lt;- [3, 4] do<br>  {x, y}<br>end<br><br>IO.inspect(pairs)<br># [{1, 3}, {1, 4}, {2, 3}, {2, 4}]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*DXG6KJ-YQn6-iAnhtSFw6Q.png" /></figure><p>List comprehension is great when we need to transform data efficiently and concisely. However, if we only need to iterate without creating a new list, Enum.each might be a better choice.</p><h4>References</h4><ul><li><a href="https://www.tutorialspoint.com/elixir/elixir_loops.htm">Elixir — Loops</a></li><li><a href="https://elixirschool.com/blog/recursion">Understanding Recursion with Elixir</a></li><li><a href="https://elixirschool.com/en/lessons/basics/comprehensions">Elixir School: Comprehensions</a></li></ul><h4>Conclusion</h4><p>Even though Elixir doesn’t have a conventional for or while, we can still handle iteration in a clean and expressive way:</p><ol><li><strong>Recursion</strong>, especially tail recursion, for handling data step by step (and large data safely).</li><li><strong>The </strong><strong>Enum module</strong>, which provides plenty of ready-made functions for transforming and aggregating collections.</li><li><strong>List comprehensions</strong>, which let us build new lists from existing data via the for keyword—remember, it’s not a traditional loop!</li></ol><p>By learning these approaches, we gain insight into functional programming’s core philosophy: <em>transforming data rather than mutating it</em>. We hope this guide helps us feel comfortable with Elixir’s style of “looping.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a095838bd3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir Essentials: A Simple Comparison of Enum and Stream for Data Processing]]></title>
            <link>https://medium.com/@qrizan/elixir-essentials-a-simple-comparison-of-enum-and-stream-for-data-processing-948b4a506c39?source=rss-1c4ed2c9b9d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/948b4a506c39</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[elixir-enum]]></category>
            <category><![CDATA[elixir-stream]]></category>
            <dc:creator><![CDATA[rizan]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 13:02:06 GMT</pubDate>
            <atom:updated>2025-02-01T13:02:06.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GXwf4hhLLKU2QcXKZ9l2dg.png" /></figure><p>Elixir is an increasingly popular functional programming language known for building fast, scalable, and reliable applications. Two core modules for processing collections in Elixir are <strong>Enum</strong> and <strong>Stream</strong>. While both are used for data manipulation, they operate differently. In this article, we will explore what Enum and Stream are, how they work, and when to use each, along with examples that measure execution time.</p><h4>Enum in Elixir</h4><p><strong>Enum</strong> is a module that provides functions to iterate over, manipulate, and manage collections such as lists, maps, and ranges. Enum uses <strong>eager evaluation</strong>, meaning that every operation is executed immediately, and a new data structure is produced after each step.</p><p><strong>Example:</strong></p><p>Suppose we have a list of numbers and we want to square each number. We can use Enum.map/2 as follows:</p><pre># A list of numbers<br>numbers = [1, 2, 3, 4, 5]<br><br># Squaring each number<br>squared = Enum.map(numbers, fn x -&gt; x * x end)<br><br># Displaying the result<br>IO.inspect(squared)  # Output: [1, 4, 9, 16, 25]</pre><ul><li>The function Enum.map/2 iterates over each element in numbers, squares it, and produces a new list named squared.</li></ul><p><strong>Verifying Execution Time with Enum</strong></p><p>To understand how fast Enum processes data, we can measure the execution time using :timer.tc/1. Save the following code in a file (for example, executiontime-enum.exs) and run it locally.</p><pre>defmodule EnumExample do<br>  def process_numbers do<br>    {time, _squared} = :timer.tc(fn -&gt;<br>      numbers = Enum.to_list(1..1_000_000)<br>      Enum.map(numbers, fn x -&gt; x * x end)<br>    end)<br><br>    IO.puts(&quot;Enum Execution Time: #{time / 1_000_000} seconds&quot;)<br>  end<br>end<br><br>EnumExample.process_numbers()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VlR3B452WAOqXzCQ-6eL9g.png" /></figure><ul><li>:timer.tc/1 measures the time taken (in microseconds) to execute the function passed to it.</li><li>We convert the range 1..1_000_000 into a list and square each number using Enum.map/2.</li><li>The variable _squared is prefixed with an underscore to indicate it is intentionally unused.</li><li>The execution time is then printed in seconds.</li></ul><h4>Stream in Elixir</h4><p><strong>Stream</strong> is another module for processing collections, but it uses <strong>lazy processing</strong>. This means that operations are performed only when the data is actually needed. This approach is more efficient for very large or infinite collections because it does not process the entire data set at once.</p><p><strong>Example:</strong></p><p>Consider a scenario where we want to take the first 10 numbers from a large range after doubling each number:</p><pre># Building a Stream pipeline<br>stream =<br>  1..1_000_000<br>  |&gt; Stream.map(fn x -&gt; x * 2 end)<br>  |&gt; Stream.take(10)<br><br># Executing the pipeline and converting the stream into a list<br>result = Enum.to_list(stream)<br><br># Displaying the result<br>IO.inspect(result)  # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]</pre><ul><li>Stream.map/2 creates a pipeline that doubles each number, but the operation is not immediately executed.</li><li>Stream.take/2 specifies that only the first 10 results are needed.</li><li>When we call Enum.to_list/1, the pipeline is executed, and the resulting list is produced.</li></ul><p><strong>Verifying Execution Time with Stream</strong></p><p>We can also measure the execution time of the Stream pipeline using :timer.tc/1. Save the following code in a file (for example, executiontime-stream.exs) and run it locally.</p><pre>defmodule StreamExample do<br>  def process_numbers do<br>    {time, _result} = :timer.tc(fn -&gt;<br>      stream =<br>        1..1_000_000<br>        |&gt; Stream.map(fn x -&gt; x * 2 end)<br>        |&gt; Stream.take(10)<br><br>      Enum.to_list(stream)<br>    end)<br><br>    IO.puts(&quot;Stream Execution Time: #{time / 1_000_000} seconds&quot;)<br>  end<br>end<br><br>StreamExample.process_numbers()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yt1DGuWdUowGTNeZkq08OA.png" /></figure><ul><li>Similar to the Enum example, :timer.tc/1 is used to measure the time required to run the Stream pipeline.</li><li>The pipeline doubles each number in the range 1..1_000_000 and takes only the first 10 numbers.</li><li>The pipeline is executed when Enum.to_list/1 is called, and both the execution time and the resulting list are printed.</li><li>Typically, the execution time for Stream is significantly lower because only the necessary elements are processed.</li></ul><h4>When to Use Enum and When to Use Stream</h4><p><strong>Use Enum When:</strong></p><ul><li>The collection is small to medium in size, allowing the entire dataset to be processed at once without memory issues.</li><li>Immediate results are needed right after the operation.</li><li>The operations are simple and do not involve heavy computation.</li></ul><p><strong>Use Stream When:</strong></p><ul><li>The collection is very large or potentially infinite, making it impractical to process all data at once.</li><li>Memory usage should be minimized by processing only the required elements.</li><li>The operations are complex and can benefit from lazy evaluation for improved efficiency.</li></ul><h4>References</h4><ul><li><a href="https://cratecode.com/info/elixir-enum-stream-modules">Working with Elixir Enum and Stream Modules</a></li><li><a href="https://hexdocs.pm/elixir/Enum.html">Elixir enum Documentation</a></li><li><a href="https://hexdocs.pm/elixir/Stream.html">Elixir stream Documentation</a></li></ul><h4>Conclusion</h4><p>By exploring these examples and explanations, we can choose the right tool for our data processing needs in Elixir. The provided examples illustrate the differences in approach and performance between <strong>Enum and Stream</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948b4a506c39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>