<?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 azurewaters on Medium]]></title>
        <description><![CDATA[Stories by azurewaters on Medium]]></description>
        <link>https://medium.com/@azurewaters?source=rss-ac418bebe554------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jkPQWjz4OAqx_HHjkaeqdg.png</url>
            <title>Stories by azurewaters on Medium</title>
            <link>https://medium.com/@azurewaters?source=rss-ac418bebe554------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:48:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@azurewaters/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[Keys to Elm: Updating nested records]]></title>
            <link>https://azurewaters.medium.com/keys-to-elm-updating-nested-records-45f5f598ac7d?source=rss-ac418bebe554------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f5f598ac7d</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm-lang]]></category>
            <dc:creator><![CDATA[azurewaters]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 08:02:41 GMT</pubDate>
            <atom:updated>2024-03-01T17:08:29.090Z</atom:updated>
            <content:encoded><![CDATA[<h4>Updating nested records is not the same as in the Javascript world. This article guides you through the Elm approach.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BtD6koVD1GrhTpw2" /><figcaption>Photo by <a href="https://unsplash.com/@giorgiotrovato?utm_source=medium&amp;utm_medium=referral">Giorgio Trovato</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Note: The “Keys to Elm” series describes a few basics of Elm that aren’t covered in the documentation or on the Internet much, just so you don’t spend time discovering them on your own.</blockquote><p>“Records” in Elm are similar to objects in Javascript. (The main difference is that objects can have associated methods but records cannot — they just hold data.) In Javascript, we can do “nested updates” — things on the lines of customer.billingAddress.zip = ‘12345’. You, naturally, try this in Elm only to figure two things:</p><ol><li>Elm doesn’t use a dot syntax to update fields in records.</li><li>You can’t directly update fields of nested records in Elm.</li></ol><h3>Different syntax</h3><p>What is Elm’s syntax to update records? It’s this:</p><pre>newRecord = { oldRecord | field = newValue }</pre><p>If you are looking at this syntax and asking yourself “Why?”, one answer is that you can do this:</p><pre><br>newRecord = { oldRecord | field1 = newValue1, field2 = newValue2 }</pre><p>In other words, you can update multiple fields with just one line.</p><h3>Nested updates</h3><p>We now know how to update fields of records. But, some fields can be records themselves, like billingAddress in this example:</p><pre>-- NESTED STRUCTURE<br><br>type alias Customer =<br> { name : String<br> , billingAddress : Address     -- The &quot;billingAddress&quot; is of the &quot;Address&quot; type, which is shown below.<br> , mobile : String<br> }<br><br>type alias Address =<br> { street : String<br> , city : String<br> , zip : String<br> }</pre><p>How does one update fields of nested records, like the zip of a customer’s billingAddress? Elm doesn’t let you do the following, for instance:</p><pre>-- This won&#39;t work <br>newCustomer = <br>  { oldCustomer | billingAddress = { oldCustomer.billingAddress | zip = newValue } }</pre><p>So, how <em>does</em> one do this? Firstly, the Elm community wants you to ask yourself whether you really need that nested structure. If there’s a legitimate, technical reason to nest records, then the way to update a nested field is to break the steps down. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bbc67e5f924d1e4140ab235190fe715/href">https://medium.com/media/2bbc67e5f924d1e4140ab235190fe715/href</a></iframe><blockquote>Note: The above code can be more concise but I’ve shown it as is for clarity.</blockquote><p>What’s happening here?</p><ol><li>Since we can’t update nested fields, you have to extract the customer’s billingAddress into its own variable. That’s what’s happening in line 4.</li><li>You can then update its zip as shown on line 8.</li><li>Next, you update the customer’s record with the updated billing address, as in line 10.</li></ol><h3>Alternatives</h3><p>If the reason for using the nested data structure is <strong>organisation</strong> and not a technical one (like that you use Address independently and often in your code), here are a couple of alternatives:</p><h4>One</h4><p>Flatten the data structures but <strong>use part of the fields’ name</strong> to group them. Compare the first approach (“Nested Structure”) to the second one (“Flat Structure”), below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1900104cc28cabd9e21e4b9b65fae1c3/href">https://medium.com/media/1900104cc28cabd9e21e4b9b65fae1c3/href</a></iframe><h4>Two</h4><p>Use comments in your data structure to section-off fields.</p><pre>type alias Model =<br> { newName : String<br> , newZip : String<br><br> -- Customer&#39;s details<br> , name : String<br> , mobile : String<br> <br> -- Billing address<br> , billingAddressStreet : String<br> , billingAddressCity : String<br> , billingAddressZip : String<br> }</pre><p>If the organisation is for you and not for the compiler, why not use the above approach? I’m not saying there’s never a need to use nested records but keep in mind how many more steps you need to take to update nested fields; compare the example in the <strong>Nested Updates</strong> section above, to this:</p><pre>{ customer | billingAddressZip = newZip }</pre><p>Point made?</p><h3>Conclusion</h3><p>Nested updates can be done in Elm. But, they’re cumbersome, almost by design. It won’t do to simply say that that’s what you used to do in Javascript. So, think hard before nesting records.</p><p>That’s it for this short article. Have fun with Elm, people! Cheers!</p><p><em>If you’d like, you can </em><a href="https://www.buymeacoffee.com/azurewaters"><strong><em>support my caffeine habit</em></strong></a><em> with a virtual coffee!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f5f598ac7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slightly advanced guide to custom events in Elm]]></title>
            <link>https://azurewaters.medium.com/slightly-advanced-guide-to-custom-events-in-elm-99960a4f10f7?source=rss-ac418bebe554------2</link>
            <guid isPermaLink="false">https://medium.com/p/99960a4f10f7</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[azurewaters]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 15:00:08 GMT</pubDate>
            <atom:updated>2024-03-01T16:45:07.971Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here’s how to handle drag and drops and any other event!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VrrG8aYm6VmdvRCV" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For the most part, you will get by with the events that have already been built into Elm. But, if you program long enough in Elm — and, oh, why wouldn’t you want to — you will need to pen your own events. But, the <a href="https://package.elm-lang.org/packages/elm/html/latest/Html-Events">documentation</a> is thin on custom events. This article is intended to right that wrong and have you writing custom events with aplomb! With aplomb, I say!</p><h3>Four functions</h3><p>There are four functions in the Html.Events module that you can use to define a custom event handler in Elm. Here are their signatures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/929569e0ca3d38ade3fc517facba394b/href">https://medium.com/media/929569e0ca3d38ade3fc517facba394b/href</a></iframe><p>They differ in whether they <strong>prevent the default action</strong> or <strong>stop the propagation</strong> of the event:</p><ol><li>on Cannot stop propagation and cannot prevent default action.</li><li>stopPropagationOn Can stop propagation of the event but cannot prevent the default action.</li><li>preventDefaultOn Cannot stop the propagation of the event but can prevent the default action.</li><li>custom Can stop the propagation of the event and can also prevent the default action.</li></ol><h3>The on function</h3><p>Here’s the signature of the on function again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/667973489b721459758206a0b43d261b/href">https://medium.com/media/667973489b721459758206a0b43d261b/href</a></iframe><ul><li><strong>First argument:</strong> The String bit is easy enough — for the click event, type in “click”; for touch events, type in “touchstart”, “touchmove”, “touchend”; and so on. The bottom line is that we just need to type up the event name we’d have used in Javascript. (MDN has a full list of events <a href="https://developer.mozilla.org/en-US/docs/Web/Events">here</a>.)</li><li><strong>Second argument:</strong> The custom function expects a decoder as it’s second argument. But, what will the decoder decode? Elm will supply it with the object corresponding to the event we are trapping here. We would have written this in Javascript:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9340a326a5fc5aa2d6373ba7ef303ec8/href">https://medium.com/media/9340a326a5fc5aa2d6373ba7ef303ec8/href</a></iframe><p>You see e being passed to the event handler? That’s what will get parsed by the decoder here. What’s the structure of that e object? It’s the same as in Javascript.</p><p>If you have no use for the data in that object, there’s no need to decode it. Simply use Json.Decode.succeed and have the msg emitted. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e342961f42efa6799e1452aefb360d7/href">https://medium.com/media/0e342961f42efa6799e1452aefb360d7/href</a></iframe><p>If you <strong>do</strong> need the data however, then you’ll have to write a decoder. Suppose we wanted to get the numerical value of a range slider. In Javascript, you’d get it by doing this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1fc9d273bde56fabab0f762fb3611f6/href">https://medium.com/media/d1fc9d273bde56fabab0f762fb3611f6/href</a></iframe><p>In Elm, you’d write the decoder like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/724b27f71f473f0bce67b757953d2f41/href">https://medium.com/media/724b27f71f473f0bce67b757953d2f41/href</a></iframe><p>The decoder is used in the custom event like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9534038d90753d46ede0087332fb918f/href">https://medium.com/media/9534038d90753d46ede0087332fb918f/href</a></iframe><p>And, this is how this custom event could be used in an app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0740212fd2980494825178a435893a9b/href">https://medium.com/media/0740212fd2980494825178a435893a9b/href</a></iframe><p>In other words: when the range slider’s value is altered, the event object’s valueAsNumber property will be parsed using the vanDecoder. The resulting value will be wrapped with the GotAValue message and emitted. We handle this message as usual in the update section of the app. All good?</p><h3>The other three functions</h3><p>Now that you have a hang of the basics, you won’t have trouble using the other three functions. They differ from the on function only in the second argument: instead of just a message, a configuration in the form of a tuple or a record is expected.</p><p>Again, the simplest scenario is when you <strong>don’t</strong> want to decode any data. The code would then look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a180afade338a974a9bda96e89c092b/href">https://medium.com/media/1a180afade338a974a9bda96e89c092b/href</a></iframe><p>If we <strong>do</strong> want the data in the event object, then the solution is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e2f1d1978825bbdfdf7476af68387c/href">https://medium.com/media/b1e2f1d1978825bbdfdf7476af68387c/href</a></iframe><p>Here’s what the above code is doing:</p><ol><li>The eventObjectDecoder is the decoder we write to extract the data from the event object.</li><li>The call to Decode.map msg eventObjectDecoder on line 7 will result in an output in the form of Decoder msg. But, the stopPropagationOn function expects its second argument to be a Decoder (msg, Bool). So, we can’t just pair Decoder msg with a True value and push it through a Decode.succeed like we did earlier, because we’d just end up with a Decoder (Decoder msg, Bool).</li><li>What we need to do is to somehow <strong>transform</strong> the Decoder msg into a msg. The map functions do just that. And, since we are working in the realm of decoding, we need to use map functions within the Decode module.</li><li>Looking at the documentation, the closest fit for our needs is Decode.map2. It takes two Decoder values and routes them through a function to get a single Decoder value.</li><li>So, instead of just passing a True value, we use aDecode.succeed True.</li><li>Finally, we send Tuple.pair, theDecoder msg from line 7, and the Decode.succeed True from line 8 through the Decode.map2 function to get an output in the form of Decoder (msg, Bool).</li></ol><p>(Yes, this is a post hoc explanation; it’s not terribly easy to arrive at this through reasoning alone. But, hopefully, the explanation helps the steps and the concepts stick.)</p><p>The preventDefaultOn function works similarly to stopPropagationOn.</p><p>However, the custom function requires a small change. Here is it’s signature:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0fdcfa01bc57d52431d7480570eb30/href">https://medium.com/media/1b0fdcfa01bc57d52431d7480570eb30/href</a></iframe><p>As you can see, it expects us to send in the configuration, if you will, as a record instead of a tuple. To make life easier, we could define a type alias to hold those values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e2be62d68d2abda04f0b6e1f1bf2f7/href">https://medium.com/media/02e2be62d68d2abda04f0b6e1f1bf2f7/href</a></iframe><p>And, this is how a custom event is defined using the custom function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c70b34034f2b2d1861e233aab1678aeb/href">https://medium.com/media/c70b34034f2b2d1861e233aab1678aeb/href</a></iframe><p>The unique point in the above code is that, instead of a regular function, Decode.map3 combines the three decoders’ outputs using the type alias’ <strong>constructor</strong>. Neat, huh?!</p><h3>Handling drag and drop of files</h3><p>The code below pulls all the concepts we discussed above together and shows how files can be dragged into an app.</p><blockquote><strong>Note: </strong>I referred to <a href="https://developer.mozilla.org/en-US/docs/Web/API/DragEvent">this</a> page to find out the structure of the drag event’s event object.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc2f7ac817893c85d7da855e2003ec76/href">https://medium.com/media/dc2f7ac817893c85d7da855e2003ec76/href</a></iframe><p>You might have noticed that the onDrop custom event on line 49 simply passes a NoOp message, which in turn doesn’t do a darn thing in the update section of the code. The reason it’s put in at all is because there’s a quirk — if you don’t define it, the drag operation won’t work.</p><h3>Conclusion</h3><p>You can write custom events in Elm and trap any event you could with JavaScript. The small hurdle to writing custom events is mostly to do with how the data in the event object is extracted and used. Other than that, it’s easy-peasy, don’t you think?</p><p>That’s it for this article. If you have any particular topics you’d like me to write about, feel free to leave a comment. Cheers!</p><p><em>You can </em><a href="https://www.buymeacoffee.com/azurewaters"><strong><em>buy me a coffee</em></strong></a><em> if you’d like!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99960a4f10f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keys to Elm: Type annotations]]></title>
            <link>https://azurewaters.medium.com/keys-to-elm-reading-types-c3680205a4e9?source=rss-ac418bebe554------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3680205a4e9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[azurewaters]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 11:33:48 GMT</pubDate>
            <atom:updated>2024-03-01T17:09:56.827Z</atom:updated>
            <content:encoded><![CDATA[<p><em>It’s easy for people to forget how hard they found something when they were beginners. The “Keys to Elm” series tries to teach a few things that will hopefully make learning Elm a bit easier.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sOiL8Pi6LkE2NDwF" /><figcaption>Photo by <a href="https://unsplash.com/@ashkfor121?utm_source=medium&amp;utm_medium=referral">Ashkan Forouzani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong><em>Note:</em></strong><em> This article assumes you have </em>some<em> familiarity with the Elm language. Hopefully, you’ve at least finished the “Types” chapter of the </em><a href="https://guide.elm-lang.org/"><em>official guide</em></a><em>.</em></blockquote><h3>Introduction</h3><p>In Elm, <strong>type annotations</strong> are lines above functions that tell you what the <strong>type</strong> of each argument is and also the function’s <strong>return type</strong>. Here’s an example of a function with a type annotation:</p><pre>save : String -&gt; Cmd msg      -- This is the type annotation<br>save markdown =               -- The actual function&#39;s definition starts here<br>  Download.string &quot;draft.md&quot; &quot;text/markdown&quot; markdown</pre><p>What you may be able to intuit is that the argument markdown is of String type. The return type of the function is the one at the very end of the type annotation. In this particular case, the save function returns aCmd msg.</p><p>You’ll encounter type annotations in the documentation and in code examples. Just being able to make sense of the type annotations will have you well on your way to understanding code, writing it, and debugging it.</p><h3>Examples</h3><h4>Example 1</h4><p>Let’s start with a simple example of a type annotation:</p><pre>round : Float -&gt; Int</pre><p>The above means that round is a function that takes a Float as an argument and returns an Int value. As mentioned above, the return type of the function is the very last type in the annotation.</p><h4>Example 2</h4><p>Here’s another:</p><pre>modBy : Int -&gt; Int -&gt; Int</pre><p>This just means that the modBy function takes 2 arguments, both Ints, and outputs an Int. Again, the last type of the type annotation tells us what the type of the function’s output is.</p><h4>Example 3</h4><p>The difficulty level ups to intermediate in this one:</p><pre>identity : a -&gt; a</pre><p>Notice how the a is lower-cased? This means that it can be of any type — an Int, a Float, a Char, a String, a user-defined type. Anything at all. They are therefore called <strong>type variables</strong>.</p><p>Further, the fact that the input and output of the function is type a means that the function will return a value that is of the same type as the argument it was given. To be clear: this does not mean that if you send in a 20, you will get back a 20; all that we can tell from the signature is that sending in an Int will result in an Int.</p><h4>Example 4</h4><p>A slightly more complicated example:</p><pre>always : a -&gt; b -&gt; a</pre><p>Here, we learn from the signature that always is a function that takes two arguments: one of a type and one of b type.</p><p>From the previous example, we learned that a and b could be anything: an Int, a Float, a Bool, a String, a user-defined type — anything at all.</p><p>However, since the output of the function is of type a, it means that the function will return a value that will be of the same type as the first argument.</p><h4>Example 5</h4><p>Ready to up the ante? Here goes:</p><pre>map : (a -&gt; b) -&gt; List a -&gt; List b</pre><p>The <strong>second</strong> argument to the map function is List a, meaning it is a list of a type elements. The <strong>output</strong> of the map function is a list of b type values.</p><p>The <strong>first</strong> argument to the map function is “(a -&gt; b)”. The parentheses signifies that it is a function. In other words, the map function expects a function as its first argument. Specifically, it wants a function that takes an argument of type a and returns a value of type b.</p><p>Now that the type signature is clear to you, it doesn’t take much to deduce that the map function takes a list of a values and passes each of them through the (a -&gt; b) function to get a list of b values, which is sent out as the result of the map function.</p><h4>Example 6</h4><p>Now, take a look at a special case. Here’s the onClick function’s signature:</p><pre>onClick : msg -&gt; Attribute msg</pre><p>You might have noticed that msg is lower-cased, just like a and b were in the previous examples. As we’ve learned so far, lower-cased names like a and b mean that the “type variable” can be of any type. However, as per convention in Elm, we are expected to send inMsgs here. The return value of the function will be an Attribute msg, meaning that the value you sent in will come out wrapped in an Attribute.</p><blockquote>Note: I haven’t gone into what identity or always or any of the functions in the above examples do because that’ll distract us from the task of learning to read types.</blockquote><h3>Using this skill</h3><h4>Prevent errors</h4><p>Elm will infer types even if you don’t annotate your code and your code will not compile if the wrong type of arguments are used. Start fixing errors in your code by checking the type annotations, especially if you are a beginner or are using functions you aren’t familiar with.</p><h4>Find appropriate functions to use</h4><p>Let’s suppose you wanted to make <a href="https://medium.com/@azurewaters/slightly-more-advanced-guide-to-making-http-calls-in-elm-4cb685f7743a">HTTP calls</a>. Here’s the type signature of the Http.get function:</p><pre>Http.get :<br>    { url : String<br>    , expect : Expect msg<br>    }<br>    -&gt; Cmd msg</pre><p>The Http.get function wants a record with the second field of Expect msg type. Looking through the documentation, you’ll see that there are 4 functions whose outputs are of the Expect msg type:</p><pre>Http.expectWhatever : (Result Error () -&gt; msg) -&gt; Expect msg<br><br>Http.expectString : (Result Error String -&gt; msg) -&gt; Expect msg<br><br>Http.expectJson : (Result Error a -&gt; msg) -&gt; Decoder a -&gt; Expect msg<br><br>Http.expectBytes : (Result Error a -&gt; msg) -&gt; Decoder a -&gt; Expect msg</pre><p>So, we just pick one of these functions depending on whether we want String, JSON or Bytes. And, then we plug it into the record of the Http.get call. Like so:</p><pre>-- Assume that GotSampleText is a Msg in your app<br>Http.get :<br>    { url : “https://www.example.com/sampletext<br>    , expect : Http.expectString GotSampleText<br>    }</pre><h4>Substitute values with functions</h4><p>Since Elm is a functional language, you can pass around functions just as easily as you pass around values. In other words, if a function expects an argument of a certain type, you aren’t restricted to sending in only a <strong>value</strong> of that type to it, you can just as easily send in a second <strong>function</strong> whose <strong>return type</strong> will be the same as the expected type; values and functions are interchangeable as long as the types match.</p><p>Suppose we have two functions:</p><pre>-- Here&#39;s the signature of a hypothetical function that takes a number<br>-- and outputs something like, &quot;The total is $70&quot;<br>whatsTheTotal : Int -&gt; String<br><br>-- And, here&#39;s the signature of another hypothetical function that<br>-- totals a list of numbers<br>totalThese : List Int -&gt; Int<br><br>-- You could use the first function in this way:<br>whatsTheTotal 70<br><br>-- Or, you could use it this way:<br>whatsTheTotal (totalThese [10, 20, 40])</pre><p>Since the return type of totalThese is an Int (the same as the input argument for whatsTheTotal), you can simply pass in the function itself. There’s no need to invoke functions, put their values into a variable, and then supply that value into another function. It’s all done in a single step.</p><h3>Conclusion</h3><p>No, people don’t learn to read types overnight. It’ll take practice. However, I hope I have you convinced to pay more attention to the type annotations. Cheers!</p><p><em>If you’d like, you can </em><a href="https://www.buymeacoffee.com/azurewaters"><em>support my caffeine habit</em></a><em> with a virtual coffee!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3680205a4e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slightly more advanced guide to making HTTP calls in Elm]]></title>
            <link>https://azurewaters.medium.com/slightly-more-advanced-guide-to-making-http-calls-in-elm-4cb685f7743a?source=rss-ac418bebe554------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb685f7743a</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[azurewaters]]></dc:creator>
            <pubDate>Thu, 17 Nov 2022 09:58:22 GMT</pubDate>
            <atom:updated>2024-03-01T17:11:59.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Message icon made with craft paper" src="https://cdn-images-1.medium.com/max/1024/0*VvQjVq3wY3kZcx7G" /><figcaption>Photo by <a href="https://unsplash.com/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve covered some basics of making HTTP calls from Elm in my <a href="https://medium.com/@azurewaters/using-supabases-http-endpoints-in-an-elm-app-ffa0afbe9ff3">previous article</a>. These are also covered in the official guide, over <a href="https://guide.elm-lang.org/effects/Http.html">here</a> and <a href="https://package.elm-lang.org/packages/elm/Http/2.0.0/">here</a>. This article pulls all this information together and goes into a little more depth. We’ll cover:</p><ol><li>What to expect with HTTP calls</li><li>How to handle errors in HTTP calls</li><li>How to track the progress of HTTP calls</li></ol><h3>What to expect with HTTP calls</h3><p>As you might have seen in the guide and the package’s documentation, there are multiple ways to make HTTP calls within Elm. The get function&#39;s the simplest, requiring only an address and an argument specifying what is being expected. Let&#39;s start there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02cf0337990f274cc1413f1113bc80c6/href">https://medium.com/media/02cf0337990f274cc1413f1113bc80c6/href</a></iframe><p>The get function of the Http module takes a record as an argument and returns a message. We give the url field the full path of the resource (the API endpoint or the file, for instance). Simple enough. The expect field, though, says it requires to be given an Expect msg type. Looking through the Http module&#39;s documentation, we see that there are four functions that return an Expect msg. Here are their signatures:</p><ol><li>expectWhatever : (Result Error () -&gt; msg) -&gt; Expect msg</li><li>expectString : (Result Error String -&gt; msg) -&gt; Expect msg</li><li>expectJson : (Result Error a -&gt; msg) -&gt; Decoder a -&gt; Expect msg</li><li>expectBytes : (Result Error a -&gt; msg) -&gt; Decoder a -&gt; Expect msg</li></ol><p>If we have no use for what the server sends back, pick expectWhatever. Otherwise, we can pick one of the others depending on what we expect the server to send.</p><blockquote>Note: I won’t be covering expectBytes just yet.</blockquote><h4>When we expect strings</h4><p>If it’s a String we are expecting from the server, of course, pick expectString and give it a Msg to trigger when the server responds. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0021d8d8469813a187039ac7b7de543/href">https://medium.com/media/c0021d8d8469813a187039ac7b7de543/href</a></iframe><p>Notice that GotSomeText was not sent a String but a Result. This is because many things can go wrong when talking to servers. More on that later.</p><h4>When we expect JSON</h4><p>The server may be sending you JSON. No problem. Use expectJSON and supply it with a JSON decoder to parse the data and a message to trigger. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/211112fb2ca96957838a61b9273982e6/href">https://medium.com/media/211112fb2ca96957838a61b9273982e6/href</a></iframe><p>So, what’s happening here?</p><ol><li>On line 17, at the start of the call, we are letting Http.request know that we are expecting JSON, and that when the data comes in, it has to be parsed with the reportDecoder.</li><li>Lines 36 and 37 of reportDecoder are more or less self-explanatory -- look for a field named so-and-so and turn it&#39;s value into an Elm type of such-and-such. Most of the time, you&#39;ll probably be in good stead knowing this much. However, the third line pushes out the comfort zone a tad bit more. But, because of the <strong>amazing pipe operator</strong> (|&gt;) you can sense that it&#39;s just a two step instruction to Elm: (1) Look for a field named “uploadedOn” in the JSON and convert it&#39;s value into an int. (2) Take that int value and then send it to a function called millisToPosix of a module called Time. (Don&#39;t worry about the details right now; we are just learning to articulate the instructions we are giving to Elm. All good?)</li><li>Whether the data can be decoded or not, a Result will be produced. So, we handle both, the success as well as the failure scenarios, in the FetchedAReport section (line 25) of update.</li></ol><h3>How to handle errors in HTTP calls</h3><p>Of course, there are many points of failure in making http calls: the wifi might be down, the server might be on the blitz, the JSON might have changed, etc. Errors may occur. They have to be handled.</p><p>Take a look at the two messages that handle what happens after an http call again:</p><ol><li>GotSomeText (Result Error String)</li><li>FetchedAReport (Result Error Report)</li></ol><p>Both are expecting that an error might occur. That’s why they have a Result as their associated data. The Result has two variants and might take the form of Ok x or Err y. That&#39;s why we have to pattern match in the GotSomeText result branch, for instance, under update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b70b2b65b0a3074c1290fcff6856854c/href">https://medium.com/media/b70b2b65b0a3074c1290fcff6856854c/href</a></iframe><p>If everything worked as expected, great. The first branch’s code (line 3) will get executed. However, in case an error occurred, the second branch (line 5) executes. The errors that can occur are described in the documentation, under <a href="https://package.elm-lang.org/packages/elm/http/latest/Http#Error">Http.Error</a> and summarised in the code snippet below.</p><p>One point to note: if Elm has trouble parsing the JSON, it’ll result inBadBody errors. You may want to use Debug.log and Debug.toString to output those errors to the console to figure out what went wrong. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/919e0784447e3d9553747e2af5e076e7/href">https://medium.com/media/919e0784447e3d9553747e2af5e076e7/href</a></iframe><p>The <a href="https://package.elm-lang.org/packages/elm/core/latest/Debug#log">Debug.log</a> (line 18) outputs the badBodyError to the console. Read it to find out where the problem in the JSON is.</p><h3>How to track the progress of HTTP calls</h3><p>There didn’t seem to be much information on this aspect when I was learning about HTTP calls. Don’t know if it was too simple to be explained or if people didn’t use the feature enough. Either way, here’s what I learned about tracking the progress of HTTP calls.</p><p>If an HTTP call is taking a long time to complete — suppose you are downloading a large file, or uploading a lot of data — you may want to report progress to the user so that they aren’t left thinking that something broke. To do this, you will need to track the progress of your HTTP calls.</p><p>There are three steps to tracking progress of HTTP calls:</p><ol><li>Step 1: Assign an id to the call that you want to track</li><li>Step 2: Let Elm know we want to know the progress of those calls</li><li>Step 3: Handle the updates</li></ol><h4>Step 1: Assign an id to the call that you want to track</h4><p>The Elm Runtime reports progress of HTTP calls, and you can listen for them by subscribing to them. Since there may be more than one call progressing at a given time (maybe multiple files are being downloaded), you will need to give each HTTP call an ID. You cannot do this with the standard Http.get or Http.post functions; you will have to use a custom Http.request. Here’s its format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83a8097917f7b7037a440419d9eae675/href">https://medium.com/media/83a8097917f7b7037a440419d9eae675/href</a></iframe><p><em>Source: </em><a href="https://package.elm-lang.org/packages/elm/http/latest/Http#request"><em>https://package.elm-lang.org/packages/elm/http/latest/Http#request</em></a></p><p>See that tracker bit on line 8? That&#39;s where we give the call an ID.</p><p>Supposing you had two HTTP calls that you were tracking, this is how you&#39;d subscribe to get notified of each of their progress:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8b0edbfed91eef06f839f2eb2cd543/href">https://medium.com/media/3d8b0edbfed91eef06f839f2eb2cd543/href</a></iframe><h4>Step 2: Let Elm know we want to know the progress of those calls</h4><p>Now, we need to let the Elm runtime know that we are interested in receiving updates to the progress of those calls. We can do that in subscriptions, using the IDs we just used. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4df60fc2f111b0eed4dec1968c5970b3/href">https://medium.com/media/4df60fc2f111b0eed4dec1968c5970b3/href</a></iframe><p>As you can see on lines 9 and 10, the IDs we used in Step 1 correspond to the ones in the subscriptions. Now, if the Elm runtime reports progress for the call with the ID &quot;callOne&quot;, the GotProgressOfCallOne message is triggered and if the Elm runtime reports progress for the call with the ID &quot;callTwo&quot;, the GotProgressOfCallTwo message is triggered.</p><h4>Step 3: Handle the updates</h4><p>Now, all we have to do is handle the message when it gets called, in update. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a65d543b9d432a28e5ed2f36af397b62/href">https://medium.com/media/a65d543b9d432a28e5ed2f36af397b62/href</a></iframe><p>You’d have noticed progress. It&#39;s of the Http.Progress type, which contains details about the transfer, whether outgoing or incoming. Here is the Progress type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ca78476adb6a39d3640e9e3f457082/href">https://medium.com/media/33ca78476adb6a39d3640e9e3f457082/href</a></iframe><p><em>Source: </em><a href="https://package.elm-lang.org/packages/elm/http/latest/Http#Progress"><em>https://package.elm-lang.org/packages/elm/http/latest/Http#Progress</em></a></p><h3>Conclusion</h3><p>That’s it. You’re all set. You have most of what you need to work with HTTP calls in Elm.</p><p>Do you have questions? Would you like me to explain something else? Let me know in the comments.</p><p>Have fun!</p><p><em>If you’d like, you can </em><a href="https://www.buymeacoffee.com/azurewaters"><strong><em>support my caffeine habit</em></strong></a><em> with a virtual coffee!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb685f7743a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Supabase’s HTTP endpoints in an Elm app]]></title>
            <link>https://azurewaters.medium.com/using-supabases-http-endpoints-in-an-elm-app-ffa0afbe9ff3?source=rss-ac418bebe554------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffa0afbe9ff3</guid>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[azurewaters]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 15:52:22 GMT</pubDate>
            <atom:updated>2024-03-01T17:13:36.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M__2HJ24Q08oQ3Lu" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>There are two ways for your app to access Supabase — through their “API” and through their “API”. Let me explain:</p><p><strong>One:</strong> Supabase can be accessed through a traditional REST API. With these, you can use the equivalents of JavaScript’s “fetch” command. You can see the URLs you need listed in the “Bash” sub-section of the <strong>API</strong> section of your Supabase project’s <strong>control panel</strong>.</p><pre>READ ALL ROWS</pre><pre>curl &#39;&lt;https://abcdefghij.supabase.co/rest/v1/reports?select=*&gt;&#39; \\<br>-H &quot;apikey: SUPABASE_KEY&quot; \\<br>-H &quot;Authorization: Bearer SUPABASE_KEY&quot;</pre><p><strong>Two: </strong>Supabase also provides you with libraries, including one in JavaScript, which abstract away the fetch commands. You can learn how to access your data through the “JavaScript” sub-section of the <strong>API</strong> section of your control panel. With the library, all you need to do is specify the operation and its parameters. This saves you from repeatedly specifying the fetch commands, the URL and the credentials.</p><figure><img alt="Screenshot of code fetching all columns from the reports table using Supabase’s library." src="https://cdn-images-1.medium.com/max/816/1*2OwNr1o_sPvrvroi3WusjQ.png" /></figure><p>I chose to do my last side-project using the REST API to access Supabase. My reasoning was:</p><ol><li>Less code in JavaScript. I thought that if all the code was in Elm, there’d be less chances of unhandled errors. This held true even at the end of the project.</li><li>Lesser number of decoders. It was silly of me to expect I’d be writing fewer decoders in Elm if I chose the HTTP endpoints — they’d be the same no matter the method of access.</li><li>Less boilerplate code. I did end up writing less boilerplate code — there was no need to set up outgoing ports, no need to subscribe to them in JavaScript, and no need to subscribe to incoming ports’ data within Elm.</li></ol><h3>Making HTTP calls to Supabase from Elm:</h3><p>Here’s what a HTTP request looks like in Elm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de47c9f683990960556f0e3050c0a0a6/href">https://medium.com/media/de47c9f683990960556f0e3050c0a0a6/href</a></iframe><p>HTTP calls to Supabase require you to specify: a url, an apikey, a method, and an authorisation key if you are accessing “row-level secured” data.</p><p>To find these:</p><ul><li>Go to [Your project] &gt; API &gt; Introduction to get the “API URL”. All the other URLs you’ll use will be variations of this. However, if you’re using the Storage APIs, you’ll need to append “/storage/v1/object/[bucket name]” to the Project URL to get it to work.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*YrWCrkv8t-qWbuGtpJVSkQ.png" /></figure><ul><li>Go to [Your project] &gt; API &gt; [table name], and on the top of the rightmost column, choose “Bash”, click the “hide” button and choose “anon (public)”.</li><li>Scroll down to the section describing what you want to do (e.g. “Read rows”). On the right, you’ll see the URL, the method it uses (DELETE, GET, POST or PUT), the “apikey”, and the parameters the operation needs. (Note that the “authorisation key” will not be accurate because that key only gets produced once a user logs in.)</li></ul><pre>curl -X POST &#39;&lt;https://xyz.supabase.co/rest/v1/&gt;[table name]&#39; \\<br>-H &quot;apikey: SUPABASE_KEY&quot; \\<br>-H &quot;Authorization: Bearer SUPABASE_KEY&quot; \\<br>-H &quot;Content-Type: application/json&quot; \\<br>-H &quot;Prefer: return=representation&quot; \\<br>-d &#39;{ &quot;some_column&quot;: &quot;someValue&quot;, &quot;other_column&quot;: &quot;otherValue&quot; }&#39;</pre><p>Construct the HTTP call.</p><ul><li>Note that you’ll pass the “apikey” (and all the stuff that starts with “-H” in the rightmost column) as a header. (Note that the “Authorization” key needs the word “Bearer “ added before the value.) For example:</li></ul><pre>-H &quot;apikey: SUPABASE_KEY&quot; \\<br>-H &quot;Authorization: Bearer SUPABASE_KEY&quot; \\<br>-H &quot;Content-Type: application/json&quot; \\<br>-H &quot;Prefer: return=representation&quot; \\</pre><p>turns into</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af3c23df6ba055e38cb1346da271926a/href">https://medium.com/media/af3c23df6ba055e38cb1346da271926a/href</a></iframe><ul><li>Encode all the required parameters (all the stuff that starts with “-d” in the rightmost column) as JSON, and pass them as the request’s jsonBody. (Note that sometimes lists of parameters are needed.) For example:</li></ul><pre>-d &#39;{ &quot;some_column&quot;: &quot;someValue&quot;, &quot;other_column&quot;: &quot;otherValue&quot; }&#39;</pre><p>turns into</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dec788681d1afea80c2b3da1a964731/href">https://medium.com/media/2dec788681d1afea80c2b3da1a964731/href</a></iframe><ul><li>Specify how the response will be handled.</li></ul><ol><li>What is expected as a response? Will it be a string, some JSON, or some bytes. You can ignore whatever is sent, as well.</li><li>Write a decoder to handle the response in case you are not ignoring it.</li><li>Specify the format of the message that’ll be trigged once the response is decoded.</li><li>Write the handler for the message in the update function.</li></ol><pre>, expect = Http.expectJson UserSignedUp signUpResponseDecoder</pre><h3>Pain points:</h3><ul><li>The biggest pain is Supabase’s lack of documentation.</li></ul><ol><li>The format of responses are not specified anywhere. One has to use software like Postman to figure out what might be returned. I suppose Supabase, probably rightly, thinks that most of their users will use the library they’ve provided.</li><li>The link to the Supabase Storage’s REST API uses is tucked away in the documentation. The API is not entirely accurate either — some URLs need a small tweak (you’ll need to append “/storage/v1/object/[bucket name]” to the URL shown) before they work, and the return types, though specified here, are not all as specified.</li><li>You can mitigate the pain by using Postman or the Rested plugin to test your HTTP calls and figure out what is being returned.</li></ol><ul><li>Policies for the “object” have to be set up in Supabase before the storage can be accessed in a secure way. I spent quite some time figuring this out because you only get very obscure errors when things fail.</li><li>A lot of code needs to be written in Elm to handle an HTTP call. However, know that once you’re through, you’ll have a bullet-proof application on your hands. No runtime errors!</li></ul><p>However, once I had everything up and running, it was a joy to use the web app, and a very satisfying effort.</p><p>Hope all this helped you use Supabase within your Elm app!</p><p><em>If you’d like, you can </em><a href="https://www.buymeacoffee.com/azurewaters"><strong><em>buy me a coffee</em></strong></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffa0afbe9ff3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Elm, TailwindCSS and Parcel to work together]]></title>
            <link>https://azurewaters.medium.com/getting-elm-tailwindcss-and-parcel-to-work-together-1c6bad88563e?source=rss-ac418bebe554------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c6bad88563e</guid>
            <category><![CDATA[parcel-js]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[elm-lang]]></category>
            <dc:creator><![CDATA[azurewaters]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 15:58:05 GMT</pubDate>
            <atom:updated>2021-06-23T15:58:05.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnGrivimft-QCpuq7pAkiQ.jpeg" /></figure><p>7 June 2021</p><p>Here is a no-frills, step-by-step guide to help you get Elm, TailwindCSS and Parcel working together.</p><ol><li>Firstly, update node to the latest version. If you don’t already have it, install it by following the instructions for the LTS version <a href="https://nodejs.org/en/">here</a>.</li><li>Create a new folder for your project.</li><li>Open Terminal and navigate to the project folder.</li><li>Initialise Elm by running elm init.</li><li>Initialise npm by running npm init -y.</li><li>Install Parcel (version 2.0 beta as of this writing) by running npm install -D parcel@next.</li><li>Install TailwindCSS, PostCSS and Autoprefixer by running npm install -D tailwindcss@latest postcss@latest autoprefixer@latest.</li><li>Create a file called “postcss.config.js” at the root of your project’s folder. To have Tailwind process your CSS files and have Autoprefixer add in browser prefixes, type the code <a href="https://tailwindcss.com/docs/installation#add-tailwind-as-a-post-css-plugin">here</a> into the file.</li><li>Create a file called “styles.css” and add in the following at the very start of the file. Type the code <a href="https://tailwindcss.com/docs/installation#include-tailwind-in-your-css">here</a> into the file.</li><li>Go ahead and create an index.html file, a JS file, and an Elm file with whatever content you want.</li><li>Once ready, type in npm start into the terminal. On the first run, Parcel will install all that it needs to process Tailwind CSS. As usual, open “http://localhost:1234” to see your code running.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c6bad88563e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>