<?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 Alexander V. on Medium]]></title>
        <description><![CDATA[Stories by Alexander V. on Medium]]></description>
        <link>https://medium.com/@alex-vvf?source=rss-f4d2433c4425------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8zfVc_OgL7pTjsCdOHOBQQ.png</url>
            <title>Stories by Alexander V. on Medium</title>
            <link>https://medium.com/@alex-vvf?source=rss-f4d2433c4425------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:45:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex-vvf/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[Min-Maxing Octopus Energy’s smart tariffs. Can I have my Agile cake and eat it too?]]></title>
            <link>https://medium.com/@alex-vvf/min-maxing-octopus-energys-smart-tariffs-can-i-have-my-agile-cake-and-eat-it-too-d6c1dbf66abf?source=rss-f4d2433c4425------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c1dbf66abf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[min-max]]></category>
            <category><![CDATA[electricity-bills]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[octopus-energy]]></category>
            <dc:creator><![CDATA[Alexander V.]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 18:29:56 GMT</pubDate>
            <atom:updated>2025-02-13T15:55:34.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*Lwtm4HvN58rF29v2dz3U-A.png" /></figure><p>TLDR: The complete code can be found on <a href="https://github.com/eelmafia/octopus-minmax">GitHub</a>.</p><p>It happened again. It was January 19th 2025 when I checked the next day’s electricity prices and saw that Agile would hit the cap of 100p/kWh again, after already doing so a couple of times in December. To those not part of the Octopus Energy smart tariff cult, this probably sounds insane, so I should probably give some context.</p><p>Octopus Energy’s Agile tariff is a smart electricity tariff that gives you access to half-hourly energy prices, updated daily. The price you pay per kilowatt-hour (kWh) is derived from the market price of wholesale electricity the next day. That means if wholesale electricity prices go down, my bills go down, too, sometimes even to negative pricing, meaning I get <strong>paid </strong>to use electricity. This is what Agile prices look like on an average day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cV4MMXn9Mh8UdF5Tnc_TqQ.png" /><figcaption>Screenshot from <a href="https://energy-stats.uk/octopus-agile-southern-scotland/">https://energy-stats.uk/octopus-agile-southern-scotland/</a></figcaption></figure><p>It’s usually cheaper than a standard tariff for most hours outside the peak 16:00–20:00 spike caused by people coming home from work and cooking, doing the washing, etc. If you can shift your load to other times of the day, you’ll save money compared to a regular tariff.</p><p>Obviously, it can’t all be rainbows and sunshine. Sometimes, for a long list of reasons, the price of wholesale electricity can increase quite dramatically, leading to some days being significantly more expensive than a standard tariff. No better example than a week ago (22/01/25) when the prices became silly and hit the cap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LFAQCBLMJqw-bTuhJeQtg.png" /></figure><p>With all that said, you might wonder, why bother gambling when any day can be eye-wateringly expensive?</p><p>Two reasons</p><ol><li>On average, over a long stretch of time, it <strong>IS </strong>cheaper than a normal tariff. That’s because your regular 12m tariff prices are padded with an extra ‘risk margin’ to account for fluctuations, as no matter, what your supplier HAS to provide you electricity at that rate.</li><li>You can just switch when times get tough. And because the Octopus gods are benevolent, switching costs nothing.</li></ol><p>That’s the whole point of this post. A few months ago, people discovered that you can switch from a smart tariff like Agile to another smart tariff like Octopus Go, which has guaranteed prices as often as you like. This is nice because if you expect an expensive week/month ahead, you can just switch to Go and return to Agile when things stabilise.</p><p>But that’s not enough for me. I want to be as efficient as possible, so I’ll swap not for expensive periods but on a day-by-day basis. I noticed that when you switch, your new tariff goes into effect from 12 am on the day of your switch. This means if, for example, I forget to check Agile prices and find out at 10 pm that I am now financially ruined, I can switch to Octopus Go, and the costs for that day will be re-calculated based on the new tariff and not Agile.</p><p>The conspiratorial person in me thinks this is just a leftover behaviour from when switching tariffs used to take days/weeks, and the programmer octopuses (not octopi!) were so good at their job that they automated switching to happen instantly. Still, the same rule of “new tariff starts at midnight” remained. However, the rational person in me knows that the Octopus gods did this on purpose because they love me (I am their strongest soldier) and want me to minmax the system.</p><p>To please them, I plan to do precisely this. The idea is to write some code to get my usage and costs for the day under my active tariff, then calculate how much it would cost had I been on a different tariff, and, finally, automatically switch my tariff if it’s cheaper. It should also send logs to my Discord server so I can easily see what’s going on. The plan is to automate running this daily, ensuring I only pay the lowest amount. If it works, I’ll get the benefits of Octopus Agile with none of the risks. Truly a case of having my cake and eating it, too.</p><p>For this project, I’m also going to have the code running on my Raspberry Pi 5 so that it can do its thing independently, regardless of what I’m doing or if I’m even home. If you just want the code, you can find it <a href="https://github.com/eelmafia/octopus-minmax">here</a>.</p><p>What you need:</p><ul><li>Octopus Home Mini (important)</li><li>Your Octopus API key</li><li>A Raspberry Pi or somewhere else to run the code</li></ul><p><strong>Note</strong>: In case you aren’t an Octopus Energy customer yet, you can use my <a href="https://share.octopus.energy/coral-lake-50">referral </a>and we’ll get £50 each!</p><p>My first stop is Octopus’ API <a href="https://developer.octopus.energy/">documentation</a>, which I use to find out how to get all the data I need.</p><p>Right off the bat, Octopus’s API has a handy GraphQL query (<a href="https://developer.octopus.energy/graphql/reference/queries#api-queries-account">account</a>) to get your current tariff, standing charge, and Home Mini device ID.</p><p>Using the device ID, I can use another query to get the consumption for the day. It even returns the actual cost delta for every 30-minute interval, which we can sum up to get the total cost later. <em>Note: This is why the Home Mini is important. Without it, you can’t get access to real-time usage.</em></p><pre>def get_acc_info():<br>    query = gql(account_query.format(acc_number = config.ACC_NUMBER))<br>    result = gql_client.execute(query)<br><br>    tariff_code = result[&#39;account&#39;][&#39;electricityAgreements&#39;][0][&#39;tariff&#39;][&#39;tariffCode&#39;]<br>    region_code = tariff_code[-1]<br>    device_id = result[&#39;account&#39;][&#39;electricityAgreements&#39;][0][&#39;meterPoint&#39;][&#39;meters&#39;][0][&#39;smartDevices&#39;][0][&#39;deviceId&#39;]<br>    curr_stdn_charge = result[&#39;account&#39;][&#39;electricityAgreements&#39;][0][&#39;tariff&#39;][&#39;standingCharge&#39;]<br><br>    if &quot;GO&quot; in tariff_code:<br>        current_tariff = &quot;GO&quot;       <br>    elif &quot;AGILE&quot; in tariff_code:<br>        current_tariff = &quot;AGILE&quot;<br>    else:<br>        raise Exception(f&quot;ERROR: Unknown tariff code: {tariff_code}&quot;)<br><br>    # Get consumption for today<br>    result = gql_client.execute(gql(consumption_query.format(device_id = device_id, start_date = f&quot;{date.today()}T00:30:00Z&quot;, end_date = f&quot;{date.today()}T23:59:59Z&quot; )))<br>    consumption = result[&#39;smartMeterTelemetry&#39;]<br><br>    return (current_tariff, curr_stdn_charge, region_code, consumption)</pre><p>Now that we know what tariff we’re on, I need to find out what the rates of the opposite tariff are. For my use case, I’m swapping between Octopus Go and Octopus Agile, so I need to determine the available tariff for whichever product I’m switching to. I couldn’t see a simple query from the GraphQL API, so I turned to the <a href="https://developer.octopus.energy/rest/">REST API</a>, which makes this trivial. All you need to do is hit the /products endpoint to get a list of all active electricity tariffs. With the full product code, I now need to get the standard unit rates.</p><pre>def get_potential_tariff_rates(tariff, region_code):<br>    all_products = rest_query(f&quot;{config.BASE_URL}/products&quot;)<br>    tariff_code = next(<br>        product[&quot;code&quot;] for product in all_products[&#39;results&#39;]<br>        if product[&#39;display_name&#39;] == (&quot;Agile Octopus&quot; if tariff == &quot;AGILE&quot; else &quot;Octopus Go&quot;)<br>        and product[&#39;direction&#39;] == &quot;IMPORT&quot;<br>        and product[&#39;brand&#39;] == &quot;OCTOPUS_ENERGY&quot;<br>    )<br>    # Residential tariffs are always E-1R (i think, lol)    <br>    product_code = f&quot;E-1R-{tariff_code}-{region_code}&quot;<br><br>    today = date.today()<br>    unit_rates = rest_query(f&quot;{config.BASE_URL}/products/{tariff_code}/electricity-tariffs/{product_code}/standard-unit-rates/?period_from={today}T00:00:00Z&amp;period_to={today}T23:59:59Z&quot;)<br>    standing_charge = rest_query(f&quot;{config.BASE_URL}/products/{tariff_code}/electricity-tariffs/{product_code}/standing-charges/&quot;)<br><br>    return (standing_charge[&#39;results&#39;][0][&#39;value_inc_vat&#39;], unit_rates[&#39;results&#39;])</pre><p>To know if switching would be cheaper, I need to merge the earlier queried consumption numbers with the unit rates of the potential tariff.</p><pre>def calculate_potential_costs(consumption_data, rate_data):<br>    period_costs = []<br>    for consumption in consumption_data:<br>        read_time = consumption[&#39;readAt&#39;].replace(&#39;+00:00&#39;, &#39;Z&#39;)<br>        matching_rate = next(<br>             rate for rate in rate_data<br>            if rate[&#39;valid_from&#39;] &lt; read_time &lt;= rate[&#39;valid_to&#39;]<br>        )<br>        <br>        consumption_kwh = float(consumption[&#39;consumptionDelta&#39;]) / 1000<br>        cost = float(&quot;{:.4f}&quot;.format(consumption_kwh * matching_rate[&#39;value_inc_vat&#39;]))<br><br>        period_costs.append({<br>             &#39;period_end&#39;: read_time,<br>             &#39;consumption_kwh&#39;: consumption_kwh,<br>             &#39;rate&#39;: matching_rate[&#39;value_inc_vat&#39;],<br>             &#39;calculated_cost&#39;: cost,<br>         })<br>    return period_costs</pre><p>Because my usage data is in half-hourly intervals when switching TO Agile, matching the half-hourly intervals together is easy, but because the Go unit rates are returned as</p><pre>{<br> &quot;valid_from&quot;: &quot;2025–01–15T05:30:00Z&quot;,<br> &quot;valid_to&quot;: &quot;2025–01–16T00:30:00Z&quot;,<br> },<br>{<br> &quot;valid_from&quot;: &quot;2025–01–15T00:30:00Z&quot;,<br> &quot;valid_to&quot;: &quot;2025–01–15T05:30:00Z&quot;,<br> }</pre><p>This means the function shouldn’t try to match the intervals but instead check if the usage interval fits between unit rates. E.g. for the usage interval 07:30:00—08:00:00 instead of looking for the complimentary time interval in the Agile unit rates, it should instead find <em>where </em>that 30m interval happens between as that covers both cases in one go.</p><p>Add the standing charges, and now I have the full cost for today on both tariffs. All that’s left to do is to compare and switch if necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*Li09a5Fo-i2e0xZkBPntsQ.png" /><figcaption>Example case of when it’s cheaper to stay put</figcaption></figure><p>In the case it <em>does </em>find it’s cheaper to switch, I thought the process would be quite simple as I saw the ReplaceAgreement <a href="https://developer.octopus.energy/graphql/reference/mutations#api-mutations-replaceagreement">mutation </a>in the GraphQL docs, but sadly, using that with today’s date returns the error:<br>{‘message’: ‘Must replace agreement in future.’}</p><p>Well, that’s not good. I was hoping this would make my life easy, but no. I don’t know why you can switch on the same day if done via the website but not via the public API. Looks like we have to do it the hard way use Playwright. If they need me to do it through the website then that’s how I’ll do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*0qIQE-Hb0kSTzBlG.gif" /></figure><p>I’m mainly using Playwright versus digging through their internal API because setting up a Playwright script should take no time and it’s much simpler. The only downside of Playwright is that it requires ~ 0.5–1 GB of RAM to run but if ran in headless mode (no display rendered) it should be less than that. And besides, a Raspberry PI 4+ should be able to handle it just fine.</p><pre>def switch_tariff(target_tariff):<br>    with sync_playwright() as playwright:<br>        browser = playwright.chromium.launch(<br>            headless=True)<br>        context = browser.new_context( viewport= {&quot;width&quot;: 1920, &quot;height&quot;: 1080} )<br>        page = context.new_page()<br>        page.goto(&quot;https://octopus.energy/&quot;)<br>        page.wait_for_timeout(1000)<br>        page.get_by_label(&quot;Log in to my account&quot;).click()<br>        page.wait_for_timeout(1000)<br>        page.get_by_placeholder(&quot;Email address&quot;).click()<br>        page.wait_for_timeout(1000)<br>        page.get_by_placeholder(&quot;Email address&quot;).fill(config.OCTOPUS_LOGIN_EMAIL)<br>        page.wait_for_timeout(1000)<br>        page.get_by_placeholder(&quot;Email address&quot;).press(&quot;Tab&quot;)<br>        page.wait_for_timeout(1000)<br>        page.get_by_placeholder(&quot;Password&quot;).fill(config.OCTOPUS_LOGIN_PASSWD)<br>        page.wait_for_timeout(1000)<br>        page.get_by_placeholder(&quot;Password&quot;).press(&quot;Enter&quot;)<br>        page.wait_for_timeout(1000)<br>        page.goto(f&quot;https://octopus.energy/smart/{target_tariff.lower()}/sign-up/?accountNumber={config.ACC_NUMBER}&quot;)<br>        page.wait_for_timeout(10000)<br>        page.locator(&quot;section&quot;).filter(has_text=&quot;Already have a SMETS2 or “&quot;).get_by_role(&quot;button&quot;).click()<br>        page.wait_for_timeout(10000)<br>        context.close()<br>        browser.close()</pre><p>That’s all there is to requesting the switch. All that’s left is to accept the terms and conditions and it’s done.</p><p>Because I couldn’t replace the agreement through the API, I assumed I’d have to hack something together to accept the TnCs. I initially thought I might have to use Gmail’s API, but thankfully, I found out the <a href="https://developer.octopus.energy/graphql/reference/mutations#api-mutations-accepttermsandconditions">acceptTermsAndConditions</a>mutation exists. Hooray. It needs the enrolmentIdpassed, which we can find from querying productEnrolments and finding the enrolment whose status == IN_PROGRESS .</p><p>Then just pass the ID and the account number to the <a href="https://developer.octopus.energy/graphql/reference/mutations#api-mutations-accepttermsandconditions">acceptTermsAndConditions</a> mutation and it should be all. However, what’s weird is that sometimes productEnrolmentssays that the enrolment in question is complete without me having done anything. Somehow, it auto-accepts the terms and conditions, and the switch goes through. I can’t pinpoint when and what causes it, though.</p><pre>def accept_new_agreement():<br>    query = gql(enrolment_query.format(acc_number = config.ACC_NUMBER))<br>    result = gql_client.execute(query)<br>    try:<br>        enrolment_id = next(entry[&#39;id&#39;] for entry in result[&#39;productEnrolments&#39;] if entry[&#39;status&#39;] == &quot;IN_PROGRESS&quot;)<br>    except StopIteration:<br>        # Strangely sometimes the enrolment skips &#39;IN_PROGRESS&#39; and just auto-accepts, so we check if it&#39;s completed with today&#39;s date<br>        today = datetime.now().date()<br>        <br>        for entry in result[&#39;productEnrolments&#39;]:<br>            for stage in entry[&#39;stages&#39;]:<br>                if stage[&#39;name&#39;] == &#39;post-enrolment&#39;:<br>                    last_step_date = datetime.fromisoformat(stage[&#39;steps&#39;][-1][&#39;updatedAt&#39;].replace(&#39;Z&#39;, &#39;+00:00&#39;)).date()<br>                    if last_step_date == today and stage[&#39;status&#39;] == &#39;COMPLETED&#39;:<br>                        send_discord_message(&quot;Post-enrolment automatically completed with today&#39;s date.&quot;)<br>                        return<br><br>        raise Exception(&quot;ERROR: No completed post-enrolment found today and no in-progress enrolment.&quot;)<br>    query = gql(accept_terms_query.format(account_number = config.ACC_NUMBER, enrolment_id = enrolment_id))<br>    result = gql_client.execute(query)</pre><p>When that happens, there’s nothing to accept, so we just return. Just to make sure, as a last step I query my account details again to see if the active tariff on the account is the new Go tariff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*FbwoXd-dSQjOgkY5axTlPg.png" /></figure><p>Looks to be. Mission successful!</p><p>Now I can just rest and not pay much attention to the costs knowing that I’ll always be on the cheapest tariff. The days of worrying about 100p/kWh are a thing of the past.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c1dbf66abf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Give Gleam a try for your next side project]]></title>
            <link>https://medium.com/@alex-vvf/give-gleam-a-try-for-your-next-side-project-e89858be4708?source=rss-f4d2433c4425------2</link>
            <guid isPermaLink="false">https://medium.com/p/e89858be4708</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alexander V.]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 20:22:27 GMT</pubDate>
            <atom:updated>2024-07-31T20:22:27.698Z</atom:updated>
            <content:encoded><![CDATA[<p>Looking for something new and shiny to add to your stack? Gleam is the (somewhat) new kid on the block, created with developer experience in mind, it offers a unique feel compared to other languages thanks to its design philosophy of having a small footprint without sacrificing utility.</p><p>This blog isn’t meant to “Gleam-pill” you or to argue that Gleam is the best at everything. Instead, I want to highlight why I have been enjoying Gleam over other languages and hopefully in doing so spark just enough interest in you to give it a try the next time you’re building something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FiuuNZ8K6UO8h6mfKFZ5tw.png" /><figcaption>Gleam’s mascot is a pink starfish named Lucy.</figcaption></figure><h3>What is Gleam?</h3><p>Gleam is a</p><ul><li>statically typed</li><li>general purpose</li><li>scalable</li><li>fault-tolerant</li></ul><p>functional programming language running on the <a href="https://en.wikipedia.org/wiki/BEAM_(Erlang_virtual_machine)">Erlang BEAM VM</a> (more on that later). Think Erlang but with type-safety out of the box and without the steep learning curve.</p><p>For those who might be unaware of the Erlang runtime system’s capabilities: WhatsApp successfully scaled to <a href="https://newsletter.systemdesign.one/p/whatsapp-engineering">50 Billion messages</a> a day with only a team of 32 engineers thanks to it. That’s 578,703 messages per second btw. Discord is another Erlang VM success story, <a href="https://discord.com/blog/how-discord-scaled-elixir-to-5-000-000-concurrent-users">see here</a>.</p><p>All of that is to say, the ideas and technology behind Gleam are not someone’s new quirky concepts, but a battle-tested and proven framework. Unlike the majority of new projects that fizzle out and quickly become abandoned, Gleam is under active development. Version 1 was released on <a href="https://gleam.run/news/gleam-version-1/">March 4th</a> this year and only a few months later we’ve seen three big updates with <a href="https://gleam.run/news/auto-imports-and-tolerant-expressions/">v1.3</a> being the most recent one, focusing on improving developer experience. It’s this combination of a strong focus on DevEx backed by an established architecture that makes Gleam stand out as a language with a lot of potential.</p><p>P.s. If you’ve never used a functional programming language before, then this is your opportunity as I would argue Gleam is the best FP “entry” language.</p><h3>A brief look at some of Gleam’s best parts.</h3><h4>Multilingual</h4><p>Gleam can also compile down to JavaScript meaning your code can also run in the browser. This is neat because it means you can write your frontend and your backend in the same language, saving time and complexity.</p><p>Gleam can also call Erlang and Elixir code with the @externalkeyword. For example, I needed a way to stop the runtime but Gleam doesn’t support that (yet?). No problem, creating a function to call Erlang’s haltwas trivial.</p><pre>@external(erlang, &quot;erlang&quot;, &quot;halt&quot;)<br>pub fn terminate() -&gt; Nil</pre><p>Because of this, your Gleam project can work with any existing Erlang/Elixir code, including the vast amount of Hex libraries.</p><p>Bonus: you can also call Rust code using <a href="https://github.com/rusterlium/rustler">Rustler</a>.</p><h4>Snakes &gt; Camels</h4><p>Gleam_requires_snake_case,_unlike_a_lot_of_other_languages. But_it’s_not_just _variable_names,_numbers_too! How often have you stumbled upon a big number and rolled your eyes because it’s hard to read?</p><pre>var time_in_ms = 10000000000 //This should carry jail time<br>var better_time_in_ms = 10_000_000_000</pre><p>I am a mere human so I can’t tell what that the first variable is at a glance. I can’t even tell after looking at it for 5 seconds. Crazy how much of a difference adding a few underscores makes, huh?</p><p>Some languages, like Python and JS, allow you to use underscores to separate numbers, but what I like about Gleam is that it’s enforced so you won’t have to deal with ugly codebases. It’s a small QOL thing but it makes a big difference.</p><h4>From snake oil to pipe dreams</h4><p>There’s an epidemic plaguing the newer generation of programmers. Too many young devs have never experienced the pleasure of piping. Who is to blame? Some say the rise of JavaScript and OOP, I say the reason is, in fact, League Of Legends.</p><p>Jokes aside, if we look at Stack Overflow’s recent <a href="https://survey.stackoverflow.co/2024/technology#most-popular-technologies-language">2024 survey</a> we see that within the top 10 most used languages, only one language supports pipe forward operators natively — Bash/Shell (and who knows how many reported using it because they do npm run every day?).</p><p>All this is to say, pipe-forward operators have become essentially extinct for most developers and in my opinion, they are better than dot chaining and nested function calls. Not only is it more readable, especially when done vertically, but you can also use it for functions that take more than 1 argument and pipe the value in whichever position you want.</p><pre><br>fn pipeless_function(url: String) {<br>  let url = url<br>  let response = fetch(url)<br>  let json = get_json(response)<br>  let obj = parse_json(json)<br>  let data = extract_user_info(True, obj)<br>}<br><br>fn pipeful_function(url: String) {<br>  let data =<br>    url<br>    |&gt; fetch<br>    |&gt; get_json<br>    |&gt; parse_json<br>    |&gt; extract_user_info(True, _) //Pass the value in the second position<br>}</pre><p>JavaScript has been <a href="https://github.com/tc39/proposal-pipeline-operator">spinning its wheels</a> on pipes for a long time now and who knows if and when it will happen. I really wish more languages had this natively because using pipe forwards makes reading complex code much easier. Not to mention you also don’t allocate memory for all these unnecessary variables.</p><p>You will notice there is a trend with Gleam and focusing on good developer experience, unlike some languages that just pump out features only a small subset ever uses (I won’t name names here).</p><h4>Scalability &amp; Concurrency</h4><blockquote>Yes.</blockquote><p>There’s not much more to say. Built on top of Erlang and running on the BEAM guarantees you have one powerful language on your hands, capable of cheaply and easily scaling to the moon with fault-tolerance baked in.</p><p>For those not aware of the Erlang runtime system and more specifically the BEAM VM, it’s kind of like having Docker and Kubernetes built into the language. Every ‘process’ (think green thread) has its own memory and is isolated from every other process. If one fails it won’t affect the others (unless you want it to), and something called a ‘supervisor’ can react to a process failing and either restart it, kill it, or spawn a new one.</p><p>The craziest part is, the BEAM is more than 30 years old! If you want to see this in action and be amazed, I recommend this <a href="https://www.youtube.com/watch?v=JvBT4XBdoUE">presentation </a>by Sasa Juric on general Erlang/Elixir concurrency (still applicable to Gleam). If you want to learn more about doing it in Gleam specifically, this <a href="https://www.youtube.com/watch?v=WaHx6n2UZJg">talk </a>by Raúl Chouza shows how to use the ‘Actor’ model in Gleam, a powerful abstraction over the simple process, which is what you’ll end up reaching for most often in the real world.</p><h4>Notice a pattern?</h4><p>JavaScript fans rejoice, Gleam has a very large list of control flows to make you feel right at home. Here is a long list describing them:</p><ul><li>Pattern Matching</li></ul><p>Yeah, really, that’s it. There is no if…else, no while, no for, no switch. It’s all just case statements. Think of it like a switchon steroids.</p><p>Case statements in Gleam do exhaustive pattern matching meaning you need to account for every possible shape of the data which might initially sound annoying but it means you’re less likely to let something just slip your mind and blow up later.</p><p>I will admit that, at first, I thought this was a bad decision because who doesn’t love their if statements? But the truth is, after a while, you just get used to it and you start to see the whole world through casestatements. And that’s when you realise that it’s not restrictive, but in fact, freeing. When there is only one way of doing things you won&#39;t waste time thinking about or debating which way is better, instead, you just get on with it. It also means you won’t have to deal with those “<em>I think this </em><em>if should be a </em><em>switch instead</em>” type of comments on your PRs. Plus, I find it’s more concise and just looks better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*SMVX9U2MX5e4lDEbFJB-6w.png" /></figure><p>Gleam also doesn’t have any loops so you’ll have to use recursion for everything (your University professor will be proud).</p><blockquote>But recursion has worse performance than iteration! Won’t somebody think of the stack frames??</blockquote><p>I hear you yell, but fear not — Gleam has tail-call optimised recursion. Gleam will unroll the recursive call into a loop if the last thing the function calls is itself. This means your stack frames are safe and you won’t need to create more of them leading to recursion having the same performance as a normal loop but looking more elegant, which is all that really matters.</p><h4>Error Messages</h4><pre>Object reference not set to an instance of an object</pre><p>This is an actual error you can see in C#. Modern compilers have gotten a bit better and generally will at least point you to where the error is but you still have to figure out why exactly something isn’t working. Gleam places importance on having useful error messages to help developers debug their code. Here are a few examples.</p><pre>error: Incorrect arity<br>  ┌─ /src/one/two.gleam:3:8<br>  │<br>3 │ use &lt;- func<br>  │        ^^^^ Expected no arguments, got 1<br><br>The function on the right of `&lt;-` here takes no arguments.<br>But it has to take at least one argument, a callback function.<br><br>See: https://tour.gleam.run/advanced-features/use/</pre><p>Not only does it tell you where the issue is, it tells you how to fix it and gives you a link to read more.</p><p>The compiler will also give you tips, for example, if you’re pattern-matching redundantly.</p><pre>warning: Redundant list<br>  ┌─ /src/warning/wrn.gleam:2:14<br>  │<br>2 │         case [1, 2] {<br>  │              ^^^^^^ You can remove this list wrapper<br><br>Instead of building a list and matching on it, you can match on its<br>contents directly.<br>A case expression can take multiple subjects separated by commas like this:<br><br>    case one_subject, another_subject {<br>      _, _ -&gt; todo<br>    }<br><br>See: https://tour.gleam.run/flow-control/multiple-subjects/</pre><p>For anyone just starting out with Gleam or FP in general, this will save them a lot of headaches. It’s just a small example of how helpful the compiler is but it gets the point across.</p><h4>Performance</h4><p>The best part is that none of this impacts speed. To show this, I ran a benchmark comparing it to a few other languages. It was only apt to test the performance by using an exercise from the book <em>Programming Erlang: Software for a Concurrent World </em>by Joe Armstrong, one of the co-creators of Erlang.</p><p>The exercise is as follows:<br>- create N processes linked together in a ring<br>- send a message that loops the ring M times (so that M*N messages are sent in total)<br>- time how long it takes to complete</p><p>Conveniently, I found this <a href="https://github.com/meox/O-Ring">project</a> which has implementations of the same ring benchmark in multiple other languages, but not in Gleam. To compare, I just ended up writing my <a href="https://github.com/NoxQ/Gleam-Ring">own</a>.</p><p>Here is the graph showing the average time in milliseconds using 200_000 nodes and sending a message around the ring 30 times for a total of 6_000_000 messages sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC8VCvtMASGi0anLQBYIuA.png" /></figure><p>As you can see, Gleam holds its own compared to its BEAM brothers. It shouldn’t be a surprise because Gleam adds no overhead to the Erlang runtime as it compiles first to Erlang (same as Elixir) and then to BEAM bytecode.</p><h3>Conclusion</h3><p>In conclusion, I’ve just barely scratched the surface, I haven’t even mentioned Gleam’s built-in Result type, no null pointers, labelled arguments, or the use expression, but this post is already long enough as it is.</p><p>Anyways, I know that nothing I mentioned is unique to Gleam, but it’s the combination of these features together that makes Gleam a treat to use. When was the last time you were working on a project and the language you were using actively added to the enjoyment? I hope that I have at least piqued your interest enough to consider it for your next side project.</p><p>Gleam is designed to have a small surface area making it easy to pick up. You can learn the syntax and how to use it in a day just by doing the <a href="https://tour.gleam.run/">Gleam tour</a>. Other great resources are the <a href="https://gleam.run/">website</a>, <a href="https://hexdocs.pm/gleam_stdlib/">hexdocs</a>, <a href="https://exercism.org/tracks/gleam">exercism</a>, and the <a href="https://discord.gg/Fm8Pwmy">discord</a>. And in case you do end up liking it, consider <a href="https://github.com/sponsors/lpil">sponsoring </a>it.</p><p>Now go put “try Gleam” on your to-do list before you forget.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e89858be4708" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>