<?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 Wouter In t Velt on Medium]]></title>
        <description><![CDATA[Stories by Wouter In t Velt on Medium]]></description>
        <link>https://medium.com/@wintvelt?source=rss-df5e2683a420------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8oIBiXehWTj03nmZ.</url>
            <title>Stories by Wouter In t Velt on Medium</title>
            <link>https://medium.com/@wintvelt?source=rss-df5e2683a420------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:20:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wintvelt/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[Updating nested records in Elm]]></title>
            <link>https://medium.com/elm-shorts/updating-nested-records-in-elm-15d162e80480?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/15d162e80480</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Thu, 16 Feb 2017 10:46:02 GMT</pubDate>
            <atom:updated>2017-02-16T10:46:02.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple helper functions to pipeline nested record updates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7x3VHvAkVf0tylturZFvg.jpeg" /><figcaption>More records | <a href="https://pixabay.com/nl/macro-man-muziek-persoon-koningin-1841013/">Photo credit</a></figcaption></figure><blockquote>TL;DR: If you define your own record type (alias), Elm does not give you built-in functions to update a field in this record. You need to do this manually, or make your own setter function(s). For this, I always follow a simple pattern, that has made updating records easier and my code a lot cleaner.</blockquote><h3>The problem with updating nested records</h3><p>Updating nested records in Elm can be a pain. Suppose you have a nested record structure like this:</p><pre>type alias Movie = <br>    { title : String<br>    , director : String<br>    , rating : Int<br>    }<br>  <br>type alias Model = <br>    { currentMovie : Movie<br>    , ...<br>    }</pre><p>At some point, you probably want to update e.g. the rating of the current movie. Elm does not allow you to that like this:</p><pre>-- THIS WILL NOT COMPILE<br>case msg of<br>    Rated newRating -&gt;<br>        { model <br>        | currentMovie = <br>            { model.currentMovie | rating = newRating }<br>        }</pre><p>The pattern { model.currentMovie | … } is unfortunately not allowed in Elm. So instead, you could write something like this:</p><pre>case msg of<br>    Rated newRating -&gt;<br>        let<br>            oldCurrentMovie = model.currentMovie<br>            newCurrentMovie = <br>                { oldCurrentMovie | rating = newRating }<br>        in<br>            { model <br>            | currentMovie = newCurrentMovie<br>            }</pre><p>It is readable, and easy to understand for others and my future self. Still, it’s a lot of code to update a field in a record. So I started looking for something better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-AsaavQVx_m6rdZXGB-8ow.jpeg" /><figcaption>Recording help | <a href="https://pixabay.com/p-393041/?no_redirect">Photo Credit</a></figcaption></figure><h3>Special helper functions to the rescue</h3><p>Whenever you define a record type alias in Elm, you get the dotted getter functions for free. Your setter functions however— to change something in your record (immutable-style of course)— you have to define for yourself.</p><p>For the example above, the more or less standard way is to define these setters as follows:</p><pre>setTitle : String -&gt; Movie -&gt; Movie<br>setTitle newTitle movie =<br>    { movie | title = newTitle }</pre><p>For each field, you would have to make a separate setter function.</p><p>This standard signature, with Movie -&gt; Movie at the end, has a nice advantage: You can use pipes (|&gt;) to update any selection of multiple fields.</p><pre>newMovie =<br>    oldMovie<br>    |&gt; setDirector &quot;Clint Eastwood&quot;<br>    |&gt; setRating 5</pre><p>This bit of code will output a new movie, with the title and the director set to the new values.</p><p>But what about updating the nested currentMovie record inside the Model record? If you have made a setter function for your model, you could do this:</p><pre>newModel =<br>    oldModel<br>    |&gt; setCurrentMovie<br>        ( oldModel.currentMovie<br>          |&gt; setDirector &quot;Clint EastWood&quot;<br>        )</pre><p>Yuk. This doesn’t really looks like it’s worth making the custom setter functions.</p><p>In this case, the argument order of the setters gets in the way. To resolve that, you could define some additional setter helpers that simply flip the arguments. I know: this means you have to define even more custom functions. But bear with me.</p><pre>asDirectorIn : Movie -&gt; String -&gt; Movie<br>asDirectorIn =<br>    flip setDirector</pre><p>My naming convention is &quot;as&quot;-your fieldName here-&quot;In&quot;. By adding such an additional helper (which does one thing: it flips the arguments), you can create really compact updates like this:</p><pre>newModel =<br>    &quot;Clint EastWood&quot;<br>    |&gt; asDirectorIn oldModel.currentMovie<br>    |&gt; asCurrentMovieIn oldModel</pre><p>You start with the new value of the field, and with each piped line, you add another wrapper around it, until you get to the outer/ upper record of the structure. With these new helper functions, you can update a field in a record structure that is several layers deep.</p><p>You can also combine them to update multiple fields at the lowest level:</p><pre>newModel =<br>   oldModel.currentMovie<br>   |&gt; setDirector &quot;Clint EastWood&quot;<br>   |&gt; setRating 5<br>   |&gt; asCurrentMovieIn oldModel</pre><h3>Only make the setters you need</h3><p>I really like the readability and compactness of this pattern. Defining two custom setters for each field in a record is of course less enjoyable..</p><p>So it has become something of a habit for me to <strong><em>not</em></strong> define any setters up-front. But instead, I just throw in the set[FieldName] or as[FieldName]In functions as the need arises. The compiler has my back, and warns me that the function doesn’t exist (yet). And only then do I build the specific setter helpers. As it turns out, a lot of fields don’t need setters at all, so it saves me a lot of unnecessary work.</p><p>Hopefully these helpers can ease your pain of updating nesting records too.</p><p>If you just want to play with the pattern: you can tweak and run the demo below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Frunelm.io%2Fc%2F0p5&amp;src=https%3A%2F%2Frunelm.io%2Fc%2F0p5&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=runelm" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e3342c4f9ded5320f8ed1a93433c269/href">https://medium.com/media/2e3342c4f9ded5320f8ed1a93433c269/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*bwZJydx8czq4ssYYGj9ZcQ.jpeg" /><figcaption>Pipes rock! 😉</figcaption></figure><p><em>Epilogue: For more advanced updates to deeply nested records, Evan did publish a </em><a href="https://github.com/evancz/focus/tree/2.0.1#possible-anti-pattern"><em>Focus package</em></a><em> at one point. Do make sure you read the caveats as well.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15d162e80480" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/updating-nested-records-in-elm-15d162e80480">Updating nested records in Elm</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tricks with case expressions in Elm]]></title>
            <link>https://medium.com/elm-shorts/tricks-with-case-statements-in-elm-80223b85484f?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/80223b85484f</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Thu, 09 Feb 2017 20:06:15 GMT</pubDate>
            <atom:updated>2017-02-13T10:56:31.898Z</atom:updated>
            <content:encoded><![CDATA[<h4>3 tricks to get more out of case expressions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBw1VK_vnXMsOm4042w8cQ.jpeg" /><figcaption>Branches | Image credit : <a href="http://www.publicdomainpictures.net/view-image.php?image=176213&amp;picture=tree-branch">Publicdomainpictures.net</a></figcaption></figure><p>The case..of expression is at the core of many elm app. All of my update functions start with one, like:</p><pre>update msg model =<br>  case msg of<br>    AddItem -&gt;<br>      ...<br>  <br>    EditItem itemId -&gt;</pre><p>And (despite a desire to use .map wherever I can) my code still has plenty of</p><pre>case maybeStuff of<br>  Just stuff -&gt;<br>    ...<br>  <br>  Nothing -&gt;<br>    ...</pre><p>But besides iteration over a Msg, or any other Union Type, there are some other nice things you can do with the case expression, which makes it much more versatile.</p><h3>#1. Use case expressions to operate on lists</h3><p>With the case expression you can also disect lists into separate branches. If you want to do different things with a list if it has zero, one or many items, you don’t need List.isEmpty or List.length. Instead, you can build a case expression for it. Like this:</p><pre>case myList of<br>    <strong>[] -&gt;</strong><br>        ...<br>  <br>    <strong>[ item ] -&gt;<br>        </strong>...<strong> </strong><br> <br>    <strong>items -&gt;</strong><br>        ... </pre><p>The last branch covers all cases where there is more than one item in the list. The branches need to cover all possible states of the list, but fortunately, the compiler has your back, and will warn you if you missed one.</p><p>A more advanced application is to combine it in a recursive function. An example is below. This function compares the first two items in a list, and combines them if the second one is actually a child item of the first. After that, it (recursively) calls itself on the remainder of the list.</p><pre>rollUp : List Record -&gt; List Record<br>rollUp items =<br>    case items of<br>        -- there are at least 2 items left<br>        <strong>a :: b :: rest</strong> -&gt;<br>            -- the first is the parent of the second<br>            if b.parent == a.id then<br>                -- combine the first two and make resursive call<br>                { a | children = b.content :: a.children }<br>                    :: rest<br>                    |&gt; rollUp<br>            else<br>                -- keep the first and <br>                -- make recursive call with second item and rest<br>                a :: (rollUp &lt;| b :: rest)<br>  <br>        <strong>other </strong>-&gt;<br>            -- there are 0 or 1 items in the list<br>            -- return list unchanged<br>            other</pre><p>This pattern I learned from going through the source code for the List.Extra package.</p><p><a href="https://github.com/elm-community/list-extra/blob/5.0.1/src/List/Extra.elm">elm-community/list-extra</a></p><p>Of course you can simply install this package and use its greatness. But for understanding the pattern, the source code is a great read, and well documented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALRgH7qdkhhzwuU5Ep0zkg.jpeg" /><figcaption>Photo credit: <a href="https://www.flickr.com/photos/sagamiono/4209289068">PLEASE QUEUE HERE | Michael | Flickr</a></figcaption></figure><h3>#2. Case expressions for ad hoc combined variables</h3><p>Sometimes when your update gets a Msg with new data, you may want to compare the new and the old value, before you do the update. In my case, this was to update some other variable in my model, and trigger animations, or to trigger some conditional message to the user.</p><p>Especially when the new and the old values are Union Types, comparing old and new values may become quite verbose.</p><p>Fortunately, you can create an ad hoc Tuple (or List or any other structure) of the old and the new value and put it in a case expression:</p><pre>case <strong>( oldValue, newValue )</strong> of<br>    ...</pre><p>and make branches for those.</p><p>Below is a simple example: the function userMessage returns an appropriate user message, depending on the type of change from the old to the new status.</p><pre>type Status<br>    = Connected<br>    | Disconnected</pre><pre>userMessage : Status -&gt; Status -&gt; Maybe String<br>userMessage oldStatus newStatus =<br>    case ( oldStatus, newStatus ) of<br>        <strong>( Connected, Disconnected ) -&gt;</strong><br>            Just &quot;Sorry, you were disconnected just now&quot;</pre><pre>        <strong>( Disconnected, Connected ) -&gt;</strong><br>            Just &quot;Hooray, you are connected!&quot;<br>  <br>        <strong>( _, _ ) -&gt;</strong><br>            Nothing</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*YFf5QfBmWRfv3iKCruNBDw.jpeg" /><figcaption>Photo credit: <a href="https://commons.wikimedia.org/wiki/File:Surgeon&#39;s_knot.jpg">Wikimedia Commons</a></figcaption></figure><h3>#3. Case expressions with literals and variables</h3><p>Any lower cased name in your case branches is used for pattern matching. So if you have a branch SelectWidget id -&gt;, then you can use the id in that branch to update the right widget in your model.</p><p>However, you can also put literals like 4, or &quot;users&quot; in your branches to match to specific values.</p><p>So if you have an Int and you want different actions for 0,1, any other value, you could make a simple case expression for this:</p><pre>case someInt of<br>  0 -&gt;<br>    ...<br>  <br>  1 -&gt;<br>    ...<br>  <br>  _ -&gt;<br>    ...</pre><p>A good real-life example of this is a custom url parser. The function below splits a url like /items/14 into a list of string segments like [ &quot;items&quot; , &quot;14&quot; ]. The actual parsing is done by a case expression on the segments.</p><pre>simpleParse : String -&gt; Route<br>simpleParse url =<br>    let<br>      segments =<br>        String.split &quot;/&quot; url<br>        |&gt; List.filter (\s -&gt; s /= &quot;&quot;)<br>    in<br>      case segments of<br>        <strong>[] -&gt;</strong><br>            Home<br>  <br>        <strong>[ &quot;items&quot; ] -&gt;</strong><br>            Items<br>  <br>        <strong>[ &quot;items&quot;, id ] -&gt;</strong><br>            ItemDetail id<br>  <br>        <strong>_ -&gt;</strong><br>            Home</pre><p><em>Credits for this pattern to Josh Adams, in whose Time tracker Elm app I first saw this pattern used.</em></p><h3>Not for every case</h3><p>Even with all its goodness, there are still situations where a case expression will not work, and you will need to use different pattern.</p><p><strong>No constants in case.</strong><br>You can use literals, including Union Typed variables, in case expressions. But you cannot use constants.</p><pre>-- THIS WORKS<br>case language of<br>  &quot;Spanish&quot; -&gt;<br>     ...<br>  <br>-- THIS DOES NOT WORK<br>localLanguage = &quot;Spanish&quot;</pre><pre>case language of<br>  localLanguage -&gt;<br>    ...</pre><p>The second one does not work because elm uses the localLanguage in the branch as a pattern matcher: if language matches the general pattern that it is a “thing that could be anything” (basically always), it will assign the value of that part insidelanguage (in this case the whole language) to the new variable localLanguage.</p><p>For constructed types we use this all the time in branches like Just user -&gt; to do something with the user inside a Maybe, or in the pattern a::b::rest in the earlier example.</p><p>Elm always uses lower case variables in case branches for pattern matching, and only allows literals. Elm does not allow case expressions on constants or assigned values. Probably this has to do the guarantees on the compiler needs to make that your branches cover all possible cases.</p><p><strong>No pattern matching on record contents.</strong><br>In case expressions, you can use literals inside strong types (using its type constructor), but I have not yet found a way to use the literals on record type constructor.</p><pre>-- THIS WORKS<br>type Locale = Locale String String<br>  <br>case someLocale of<br>  Locale &quot;es&quot; &quot;es&quot; -&gt;<br>    ...<br>  <br>-- THIS DOES NOT WORK<br>type alias Locale = { language : String, country : String }<br>  <br>case someLocale of<br>  Locale &quot;es&quot; &quot;es&quot; -&gt;<br>    ...</pre><p>Still, I hope the tricks above will help you get more out of case expressions, and help you make your code more readable too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*XRJNfiGUR7lm5RBDJnJWAg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80223b85484f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/tricks-with-case-statements-in-elm-80223b85484f">Tricks with case expressions in Elm</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Records in Elm]]></title>
            <link>https://medium.com/elm-shorts/intro-to-records-in-elm-51bc5e933a57?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/51bc5e933a57</guid>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Wed, 01 Feb 2017 17:02:01 GMT</pubDate>
            <atom:updated>2017-02-01T17:02:01.790Z</atom:updated>
            <content:encoded><![CDATA[<h4>Free functions, and other useful bits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iB1R6V3kuK_ez67-C9wyjQ.jpeg" /><figcaption>Records | Image credit <a href="https://www.pexels.com/u/unsplash/">Pexels Unsplash</a></figcaption></figure><p>Records are everywhere in Elm. Your first Model in Elm (or maybe your second) was a record. We use them to hold data of various other types together in one structure. They are a bit like objects in javascript. You can define a record with multiple fields of different types, and then use them elsewhere, e.g. in a list.</p><pre>type alias User =<br>    { id : Int <br>    , name : String<br>    , age : Int<br>    }</pre><pre>type alias UserList = List User</pre><p>Records have limitations too. You cannot iterate or map over the fields in a record. To the frequent frustration of those coming from javascript (like me), Elm has no record[key] to dynamically access fields. In Elm (like in javascript), the fields in a record can be of any type (which is 👍). But dynamic typing would break the type safety guarantee of the Elm compiler.</p><p>Fortunately, there is plenty of other goodness in Elm Records. Here’s a couple of lesser known features of Records, that you may find useful.</p><h3>#1. Free functions</h3><p>Records come with free functions too. Let’s examine the following User record:</p><pre>type alias User =<br>    { id : String<br>    , name : String<br>    , age : Int<br>    }</pre><p>The basic features are that you can get the name of a user like this:</p><pre>someName = someUser.name </pre><p>And you can create an updated user with a new name and age like this:</p><pre>newUser = <br>   { oldUser <br>   | name = newName<br>   , age = newAge<br>   }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*KWuY-M-hMIg10AVDnvwlVg.jpeg" /><figcaption>Free with your records</figcaption></figure><p>But there is more! With the User record defined as a type alias, you also get the following functions for free:</p><pre>User : String -&gt; String -&gt; Int -&gt; User<br>.id : User -&gt; String<br>.name : User -&gt; String<br>.age : User -&gt; Int</pre><p>The capitalized function User is a constructor. You can use it to construct a User by supplying all fields as arguments. In a previous post, you can find more detail on <a href="https://medium.com/elm-shorts/an-intro-to-constructors-in-elm-57af7a72b11e">using constructors</a>.</p><p>The other free functions are <em>getter</em> functions. That’s right, these functions begin with a . (dot).</p><p>Let’s look at a practical use case: Let’s say you have a List of Users, and you want to have only the names of these users. With the free dot-function, all you need is this:</p><pre>userNames = List.map .name users</pre><p>The List.map function takes two arguments, the first is a function to turn some a into some b. In this case, it turns a User into a String (where the string contains the name). The second argument is a list of a, in this case the list of users. The output is a list of b. So with this simple statement, all the names are extracted from our list of user records. Using the free dotted function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXRzcYR-UiZklqD1oSoHCg.jpeg" /><figcaption>Similar records | <a href="https://www.pexels.com/photo/woman-in-gray-knit-sweater-holding-files-26662/">Image credit</a></figcaption></figure><h3>#2. Different records with the same fields</h3><p>What if you have the same field that appears in multiple record types? In my own code, I frequently have fields likeid : Int which appear in multiple record types. Something like this:</p><pre>type alias Exam =<br>    { id : Int<br>    , subject : String<br>    }</pre><pre>type alias StudyBlock =<br>    { id : Int<br>    , time : Float<br>    }</pre><pre>type alias ExamItem =<br>    { id : Int<br>    , title : String<br>    , pages : Int<br>    }</pre><p>Whenever my code hands out a new id to create some new record, I need to find out the highest id in my data, and create a new one. And I like my ids to be unique across my app.</p><p>This is where I use the following pattern:</p><pre>type alias RecordWithID a =<br>    { a | id : Int }</pre><pre>maxId : List (RecordWithID a) -&gt; Int<br>maxId list =<br>    list<br>        |&gt; List.map (.id)<br>        |&gt; List.maximum<br>        |&gt; Maybe.withDefault -1</pre><pre>newId : Data -&gt; Int<br>newId data =<br>    (maxId data.exams)<br>        |&gt; max (maxId data.examItems)<br>        |&gt; max (maxId data.studyBlocks)<br>        |&gt; (+) 1</pre><p>The beauty of this is, the function maxId can handle records with different fields. The function only cares about the used field id. So you can call this function with a List of any type of record, as long as the record has an id field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*X-N7Zi0Okf0Gzqb1EKMQGA.jpeg" /><figcaption>Fields in Ireland | <a href="https://pixabay.com/nl/ierland-landschap-velden-dublin-347172/">Image credit</a></figcaption></figure><h3>#3. Efficient access to record fields in functions and patterns</h3><p>A somewhat hidden feature of Elm is that you can selectively access fields in the records for use in functions. Which is particularly handy for nested records.</p><p>This is probably best explained in an example. Let’s say you have a record like this:</p><pre>type alias MovingThing =<br>    { thing : { content : String }<br>    , x : Int<br>    , y : Int<br>    }</pre><p>What if you want a function that updates the content field in the thing in this record. One way to do this in Elm is like this:</p><pre>setContent : String -&gt; MovingThing -&gt; MovingThing<br>setContent newContent movingThing =<br>    let<br>        oldThing = movingThing.thing<br>        newThing = { oldThing | content = newContent }<br>    in<br>        { movingThing | thing = newThing }</pre><p>But you can also do this:</p><pre>setContent : String -&gt; MovingThing -&gt; MovingThing<br>setContent newContent (<strong>{ thing } as movingThing</strong>) =<br>    { movingThing <br>    | thing = { thing | content = newContent }<br>    }</pre><p>The argument ({ thing } as movingThing) says:</p><ul><li>From the record, I want to be able to access the field thing, and I don’t care about whatever other fields are there.</li><li>And I want to be able to reference the complete record too as an argument named movingThing. That’s what the as statement does.</li></ul><p>This allows you to get to the nested thing record inside the MovingThing, without using the let statement.</p><p>You can use variations of this pattern too. If you only want to access to a field, { y } (without the as) is sufficient. Or if you want access to multiple fields, you could also do e.g. { thing, x, y }.</p><p>This works in case statements too. Suppose your MovingThing is tracked in someSituation state, which has the following type:</p><pre>type Situation<br>    = NoMovement<br>    | Alive MovingThing</pre><p>You can use the same trick:</p><pre>assess situation =<br>    case situation of<br>        Alive ({ thing } as movingThing) -&gt;<br>            ...<br>  <br>        NoMovement -&gt;<br>            ...</pre><h3>Further reading</h3><p>Hopefully these 3 tricks will help you get more mileage out of your records in Elm, and make your Elm code more compact and readable.</p><p>For further reading, you could check out these resources:</p><ul><li>The official docs have the <a href="http://elm-lang.org/docs/records">basic intro into records</a> in Elm.</li><li>The <a href="https://github.com/evancz/elm-sortable-table/blob/master/examples/1-presidents.elm#L83-L94">elm-sortable-table examples</a> (by Evan himself 👍) also use the dotted-getter-functions to render a record in the table.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*5cS10NXnVFBFggWWiIVTng.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51bc5e933a57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/intro-to-records-in-elm-51bc5e933a57">Intro to Records in Elm</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the right Elm SPA architecture]]></title>
            <link>https://medium.com/elm-shorts/choosing-the-right-elm-spa-architecture-d6e8275f6899?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e8275f6899</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Wed, 25 Jan 2017 19:02:00 GMT</pubDate>
            <atom:updated>2017-01-25T19:14:17.201Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how this impacts your users and your code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b8xHOQm9SuaQdTCbRAZlg.jpeg" /><figcaption>Choices in navigation</figcaption></figure><p>There are lots of different ways to setup navigation in Elm. E.g. URLs with or without hashes. You can render links in your views as a [ href &quot;/movies&quot; ] or use [ onClick (RouteChange Movies) ]. Lots of choices to make, and each choice comes with its own specific consequences for users and for your code.</p><p>I was looking for a way to set up SPA navigation in my Elm app that best fitted my needs. So I set out to bring some structure in the choices to make and their implications.</p><p>There is no <em>one </em>best way to do SPA navigation in Elm. But hopefully the overview below will help you choose the right setup for your situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*_Ad_bVD6Q3-RlbB-7wTafA.png" /></figure><h3>Choice #1: URLs with or without hashes?</h3><p>One of the questions for you is whether you (and possibly your user) are OK with using a hash (#) in the url. Personally, I would prefer a hash-less<br>mydomain.com/movies/time-bandits over<br>mydomain.com/#/movies/time-bandits.<br>The first one looks cleaner, is the same as the purely server-side rendered version. So probably easier to read/write for the user too.</p><p>But the hash symbol does have a formal role. Any browser will interpret everything after the # as being “on the current page”. So it will send a reload request to the server. Which in a SPA is exactly what we want: we want the one Single Page Application to be in control of what is rendered.</p><p>If you are just starting to fiddle with Navigation, or you are OK with the hash, or you do not care either way, go with hashed URLs. The local state of your app will always be preserved.</p><p>If you do want hash-less URLs, you have to be a bit more careful. If your view functions use a [ href … ] elements for internal SPA navigation, you will need to add special treatment. Otherwise, the hash-less url will cause a page reload, with loss of your apps state. The special treatment consists of adding a custom onClick handler that prevents the default behavior of the link clicked:</p><pre>a <br>  [ href &quot;/movies/rogue-one&quot;<br>  , onClickPreventDefault (UrlChange &quot;/movies/rogue-one&quot;)<br>  ]<br>  [ text &quot;movie details&quot; ]<br>  <br>---<br>onClickPreventDefault : msg -&gt; Attribute msg<br>onClickPreventDefault msg =<br>  onWithOptions<br>    &quot;click&quot;<br>    { preventDefault = True<br>    , stopPropagation = False<br>    }<br>    (Json.Decode.succeed msg)</pre><p>You could also import the onClickPreventDefault from the <a href="http://package.elm-lang.org/packages/elm-community/html-extra/latest/Html-Events-Extra#onClickPreventDefault">Html.Events.Extra package</a>.</p><p>Whenever users type one of your hash-less URLs in the browser bar, this will always cause a page reload. The structure of Elm’s Navigation program does force you to handle an initial route, so when the page is loaded from the server, the user will end up in the right place/ on the right page. But if they were already in your app, the page will reload from server, and their local state (like scroll position, dropdowns open, and any unsaved data) will not be preserved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uo8TMg6e-zMtVhfopOcS3Q.png" /></figure><h3>Choice #2: Validate a new route before navigating to it?</h3><p>Another choice to make is whether you want to validate a new route before your app navigates to it. I talked about this in a <a href="https://medium.com/elm-shorts/more-on-spa-navigation-in-elm-31a066c6b9ae">previous post</a>. The idea is that your SPA code will validate any new route before actually navigating to it. The app stays on the current page, until the necessary data for the new page is in, and until the new route is validated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkkQpIPb6wXg-74jxv1MZg.png" /></figure><p>Loading and validating on the new page has an advantage: the user will immediately and clearly notice that the app responds to navigation. And in most cases, there will be valid content to show on the new page, right?</p><p>My personal preference is to load and validate <em>before</em> navigating to a new page. I find it more user friendly to let the user spend any waiting time on the current page, instead of on some empty new page.<br>But that’s your choice really.</p><h3>Choice #3: Only &lt;a&gt; links for navigation in your view functions?</h3><p>Another choice is whether you will only use a [ href .. ] elements in your view functions for navigation. After all, this is standard HTML for navigation links. My preference is to always use a elements in my views for navigation.</p><p>But this may not always be an option. If you are using a UI library like <a href="http://package.elm-lang.org/packages/debois/elm-mdl/latest">mdl</a> or <a href="https://github.com/gdotdesign/elm-ui">elm-ui</a>, then you may want or need to assign navigation actions to other HTML elements too.</p><p>If you do use more than just a elements for navigation, there is still a trick you can use to make any element behave like a link. Which brings us to choice #4..</p><h3>Choice# 4: Are you OK with a javascript trick for non &lt;a&gt; elements in your views?</h3><p>There is a trick you can use to make any element behave like a link. It uses the possibility to provide a one-line javascript statement to the attribute from the Html.Attributes package:</p><pre>div [ customRef &quot;/movies/maleficent&quot; ] [..]<br>  <br>-- Custom helper function<br>customRef : String -&gt; Attribute msg<br>customRef path =<br>  let<br>    javascriptCode =<br>      &quot;history.pushState({},&#39;&#39;,&#39;&quot; ++ path ++ &quot;&#39;);&quot;<br>  in<br>    attribute <br>      &quot;onclick&quot;<br>      javascriptCode</pre><p>The javascript-oneliner history.pushState() will push a new entry to the browser’s history. This will in turn fire the UrlChange message in your elm app, to handle the new route. To make this happen upon a user click, it is provided to the onclick attribute of the element.</p><p><em>So far, this is more of a proof of concept and not an approach I would recommend. The </em><em>pushState() is supposed to work in all modern browsers, but I haven’t tested. The function takes two more arguments (state and title), which are left empty in this example. I have no idea hwo that affects your browser histroy. Also, if you want this trick to play nice with navigating back and forth (user clicking back-button etc), I haven’t tested whether this will work.</em></p><h3>Impact on your code</h3><h4>🔥 The easiest path</h4><p>The easiest implementation is with the following choices:</p><ul><li><strong>choice #1: use URLs with hashes.</strong></li><li><strong>choice #2: navigate first, and then do loading and validation.</strong></li><li><strong>choice #3: only use </strong><strong>a elements in your views for navigation.</strong></li></ul><p>In that case all you need to implement is a UrlChange branch in your update. Which does:</p><ul><li>Translate the new URL to a typesafe Route (this is not really necessary, but it is a good and common practice), which could include Invalid404 or something similar to cover invalid routes.</li><li>Store the new Route in the model.</li><li>Kick off any loading of server data if necessary.</li></ul><p>Your view function should then check whether the model has a valid Route and if the data for the route is there, and render a page accordingly.</p><p>All navigation links in the view would be straightforward: a [ href somePath ] [...]. Where somePath would be a String with a hashed URL, like /#/movies/brave.</p><p>If you want instead to use hashless URLs, only the first choice would be different:</p><ul><li><strong>choice #1: use hashless URLs</strong></li></ul><p>Then the implementation is only slightly different. In that case, the link in the views would look something like this (to prevent default page reload with the hashless link):</p><pre>a <br>  [ href somePath<br>  , onClickPreventDefault (UrlChange somePath)<br>  ]<br>  [ ... ]</pre><p>But the structure of your update would be the same.</p><h4>🔥🔥 Navigation with other HTML elements</h4><p>If you want to use not only a elements in your view function, then the setup is different. Let’s say you make the following choices:</p><ul><li><strong>choice #1: hashless</strong></li><li><strong>choice #2: navigate first, then do loading and validation</strong></li><li><strong>choice #3: not just </strong><strong>a elements</strong></li><li><strong>choice #4: no javascript hack please</strong></li></ul><p>In that case, it is common practice to set up navigation in your view with Routes instead of URLs. The update function then has an extra branch, and your code would look something like this:</p><pre>type Route<br>  = Home<br>  | Movies<br>  | MovieDetail String<br>  <br>-- in view<br>button [ onClick &lt;| RouteChanged (MovieDetail &quot;species&quot;) ] [..]<br>  <br>-- in update<br>case msg of<br>  RouteChange newRoute -&gt;<br>    ( model, Navigation.newUrl &lt;| urlFor newRoute )<br>  <br>  UrlChange newLocation -&gt;<br>    let<br>      ...<br>    in<br>      (newModel, cmdToFetchData)</pre><p>The RouteChange branch leaves the model unchanged, and outputs a new URL for the browser. This will trigger another UrlChange, where the actual update of the model will take place, possibly with a command to load data from the server.</p><h4>🔥🔥🔥 Validation and loading before navigating to new page</h4><p>The combination of choices not covered yet are those where you would want to do loading and validation before going to a new page. The difference with the options above is that</p><ul><li>Inside the UrlChange or the RouteChange branch, you would include checks for whether the route is valid and the data is there, and only change the current route in your model if everything is OK.</li><li>If you do not use a RouteChange branch (if you use only a elements you do not need one), then you would need to output an additional Navigation.modifyUrl command in your UrlChange branch to revert the browser bar to the current page if your validation fails.</li></ul><h3>Further reading and credits</h3><p>This post is a follow-up to another post on navigation.</p><p><a href="https://medium.com/elm-shorts/more-on-spa-navigation-in-elm-31a066c6b9ae">More on SPA navigation in Elm</a></p><p>That post explains in some more detail how to set up navigation with the “validate before navigation” option.</p><p>In addition, a lot of the ideas and options here came from other posts and examples.</p><ul><li><a href="https://github.com/rofrol/elm-navigation-example">rofrol/elm-navigation-example</a></li><li><a href="https://github.com/knewter/time-tracker">knewter/time-tracker</a></li><li><a href="https://chriswellswood.github.io/#blog/elm-static-site-p1">Bits and Pieces and Odds and Ends</a></li><li><a href="https://medium.com/@nithstong/spa-simple-with-elm-navigation-630bdfdbef94">SPA simple with Elm Navigation</a></li><li><a href="https://medium.com/@adrian_ribao/how-to-create-a-spa-application-in-elm-0-18-from-scratch-68d25e0631f6">How to create a SPA application in Elm 0.18 (from scratch)</a></li><li><a href="https://www.linkedin.com/pulse/single-page-web-apps-elm-part-one-getting-started-new-kevin-greene">Single-Page Web Apps in Elm: Part One - Getting Started with a New Language</a></li></ul><p>These are good sources if you want to set up navigation for your own SPA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*N_6Q6YUDX8awoTIWyX9V2Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e8275f6899" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/choosing-the-right-elm-spa-architecture-d6e8275f6899">Choosing the right Elm SPA architecture</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An intro to constructors in Elm]]></title>
            <link>https://medium.com/elm-shorts/an-intro-to-constructors-in-elm-57af7a72b11e?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/57af7a72b11e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Wed, 18 Jan 2017 16:34:24 GMT</pubDate>
            <atom:updated>2017-01-19T21:58:04.564Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some of your types come with Free Functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sAyOs33aLXri0nJ9rF-dg.jpeg" /><figcaption>Construction | Image credit : <a href="https://commons.wikimedia.org/wiki/File:Building_Under_Construction_01.JPG">Haitham alfalah, via Wikimedia Commons</a></figcaption></figure><p>Consider a typical type definition of aMsg type in elm:</p><pre>type Msg <br>    = UserInput String<br>    | LoggedIn User<br>    | Guest User<br>    | ClickedLogoff</pre><p>In this definition, the types are</p><ul><li>Msg: this is the type that is being defined.</li><li>String: this is the (built-in) type we are using ‘inside’ the Msg type.</li><li>User: some custom type</li></ul><p>What about UserInput, LoggedIn, Guest and ClickedLogoff? <br>They are functions called <em>constructors</em>. You get them for free. If you define the type, you get the constructors as well.</p><h4>Constructor functions</h4><p>UserInput is a function with a capitalized name. It has the signature String -&gt; Msg. Which means it takes a String and outputs a Msg.</p><p>And it’s called a <strong><em>constructor</em></strong><em>.</em><strong><em> </em></strong>Because it constructs a Msg type. In<br>something = UserInput value, the UserInput value part constructs a Msg. So the variable something will be of the type Msg and will hold the resulting value of UserInput value.</p><p>LoggedIn is also a function, which takes a User as its argument. It outputs a Msg too. And Guest is a function too, with the exact same argument User, and the same signature.</p><p>ClickedLogoff is also a constructor, of an equally useful nature (albeit somewhat boring). It takes no arguments, and simply returns a Msg.</p><p>You typically call a function like UserInput in your view. You pass it to the onInput handler, when you render the input field:</p><pre>input [ type_ &quot;text&quot;, onInput UserInput ] ...</pre><p>The onInput handler is from the Html.Events library. It has the following type signature.</p><pre><a href="http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html-Events#onInput"><strong>onInput</strong></a> : <strong>(String -&gt; msg)</strong> -&gt; <a href="http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html#Attribute">Attribute</a> msg</pre><p>This function takes one argument, a function. It wants you to provide a function that turns a String into a msg. The msg in the signature is in lowercase. The onInput function does not care what type the msg is. That is up to you. It will simply include that type in the output of the function, in the Attribute msg. (<em>Attribute msg is the type for attributes of HTML elements. In the </em><a href="http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html-Attributes"><em>Html.Attribute</em></a><em> package there is some explanation and examples</em>)</p><p>The UserInput constructor defined earlier matches this signature and does exactly what’s needed here: it takes a String (which is whatever the user typed in the input field), and turns it into a Msg.</p><h4>Constructors in pattern matching</h4><p>You can also use these constructors to access the contents of a variable later on. Using a case .. of statement we can</p><ol><li>Find out which constructor was used.</li><li>Access the contents “behind” that constructor (if there is any).</li></ol><p>In the example, both the LoggedIn constructor and the Guest constructor carry a User. With a case statement, we can find out which constructor was used, and access the user information:</p><pre>case msg of<br>    LoggedIn normalUser -&gt;<br>        .. handle the info from the variable normalUser...<br>  <br>    Guest guestUser -&gt;<br>        .. handle info from guestUser .. </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QR38kruW0n-STWlisCnuQg.jpeg" /></figure><h4>Records come with constructors too!</h4><p>Consider this record definition in Elm:</p><pre>type alias User =<br>    { name : String<br>    , age : Int<br>    }</pre><p>By naming this record User, you also get a constructor for free. The constructor is also called User, and it has the signature (in this example) String -&gt; Int -&gt; User. This function allows you to do User &quot;Bill&quot; 42 to create a new user record.</p><p>At first, it may seem weird — maybe even conflicting — that the type and its constructor have the same name. But they will never show up in the same place in code:</p><ul><li>In <strong>type definitions</strong> of other types, it is always the <strong>type</strong>, never the constructor. In the Msg type definition, the User that shows up (twice) is the type.</li><li>When User shows up in code in <strong>type signatures</strong> like <br>setName : String -&gt; User -&gt; User, it is always the <strong>type</strong>, never the constructor.</li><li>In <strong>all other places</strong> in your code, if you encounter a User, it will be the <strong>constructor</strong>. So for example, in the line newUser = User “” 0, the User there is the constructor.</li></ul><h4>Type alias or type?</h4><p>When you make a type for the user record from the example above, you can actually do this in two ways:</p><pre>-- Option 1:<br>type alias User =<br>    { name : String<br>    , age : Int<br>    }<br>  <br>-- Option 2 (called &quot;opaque&quot;, or &quot;strong typed&quot;)<br>type User =<br>    User<br>        { name : String<br>        , age : Int<br>        }</pre><p>In option 2 you make the constructor function explicit. <br><em>I could have given the constructor any name, but if you have only 1 constructor, it is common to give it the same name as the type.</em></p><p>The compiler is much more forgiving on type aliases. You are basically saying that User is just an alias for anything that is a record with a String called name and an Int called age. So if you have some function defined as:</p><pre>hasLegalAge : User -&gt; Bool<br>hasLegalAge user =<br>    ...</pre><p>It is fine if you call it like this:</p><pre>canBuyOurStuff =<br>    hasLegalAge { name = &quot;&quot;, age = 28 }</pre><p>With a strong typed User, the compiler will not let you do that. It will complain that you passed some record to hasLegalAge, but it expected a real (strong) User type.</p><p>The real User type can be made by calling the constructor function, which is also called User, so if you change the code to this, it will compile again:</p><pre>canBuyOurStuff =<br>    hasLegalAge (User { name = &quot;&quot;, age = 28 })</pre><p>The second strong typed code looks much more complicated, so what’s the use of strong types?</p><p>For one, it makes it easier to extend the User type. If at some point you want to deal with anonymous users, you can add another constructor to your type:</p><pre>type User<br>    = User<br>        { name : String<br>        , age : Int<br>        }<br>    | Anonymous</pre><p>And the canBuyOurStuff function from above will still work (!). So less refactoring if you extend your strong type with more constructors.</p><p>Another advantage to strong types: If you are making a library, you can make more changes without breaking other code. This happens if you do <strong>not </strong>make the User constructor available to the rest of the world. If your module definition is like this</p><pre>module User exposing (User, newUser, setName, ...)</pre><p>You would expose the User type, and some custom (lowercase) functions to create or modify the User. This gives you the freedom to make changes to the inner workings of the User type, without breaking the existing functions you exposed. You could add fields for e.g address, hobbies, pets, friends etcetera to the record (and expose more functions to read and write them). <em>And you can do this without breaking the original functions</em>, so that anyone or any code that imports the original functions can still use them without refactoring.</p><h4>Further reading</h4><p>If you want to know more about types (or if my post was still not clear), here are some other good resources:</p><ul><li>The <a href="https://guide.elm-lang.org/types/">chapter on types in the official guide</a> is probably the best place to start.</li><li><a href="http://www.adamwaselnuk.com/elm/2016/05/27/understanding-the-elm-type-system.html">Understanding the Elm type system</a> goes deeper into types and how to use them in functions.</li><li><a href="https://dennisreimann.de/articles/elm-data-structures-record-tuple.html">Elm Data Structures</a> has more on type alias vs type for record.</li><li><a href="https://robots.thoughtbot.com/elms-universal-pattern">Elm’s Universal Pattern</a> has more on common and very useful functions (like map) you may need for your types too.</li><li><a href="http://package.elm-lang.org/help/design-guidelines#keep-tags-and-record-constructors-secret">Elm Design Guidelines</a>, with the official explanation on keeping tags and types hidden in libraries.</li><li>Not for the faint-hearted: An <a href="https://github.com/elm-lang/elm-compiler/blob/master/hints/recursive-alias.md">explanation on recursive types and type aliases</a>.</li></ul><blockquote>The first time I got really confused about types and constructors with the same name, was when I got started with Json decoding. Which is a mind-bender in itself. The example with the function <a href="http://package.elm-lang.org/packages/elm-lang/core/5.0.0/Json-Decode#map2">map2</a> caused a short-circuit in my brain: “Whut? What is this type doing in a function?” It took me a while to figure out that this was not the “type” that was being referenced, but the constructor for the type alias I defined. [AHA moment]<br>Hopefully this post will save you from a similar short-circuit. Happy coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57af7a72b11e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/an-intro-to-constructors-in-elm-57af7a72b11e">An intro to constructors in Elm</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More on SPA navigation in Elm]]></title>
            <link>https://medium.com/elm-shorts/more-on-spa-navigation-in-elm-31a066c6b9ae?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a066c6b9ae</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Wed, 11 Jan 2017 14:44:51 GMT</pubDate>
            <atom:updated>2017-01-11T14:44:51.345Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keep current page and browser bar in sync, and add data to routes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2O-B-yv3tJbsurN2T7q6w.jpeg" /><figcaption>Photo credit: <a href="https://pixabay.com/en/rails-railway-railroad-tracks-253134/">jingoba | pixabay</a></figcaption></figure><p>Navigation and SPA are a popular topic these days in Elm-land, with lots of good stuff, like:</p><ul><li><em>Selectors</em> as an intermediary between model (pure data) and viewModel (derived version, fit for rendering): <a href="https://medium.com/@ckoster22/upgrade-your-elm-views-with-selectors-1d8c8308b336#.3syihtgzu">Medium Post by Charlie Kosten here</a>.</li><li><em>Elm Models as Types</em>, a way structuring your model in Union Types rather than straight records, to get better readibility and improved making impossible states impossible. <a href="https://medium.com/@ckoster22/elm-models-as-types-d913002b58fb#.55bub5al2">Medium Post by Charlie Koster here</a>.</li><li><em>Taco</em>, a library to extend (view) functions to take in more than just the model, to facilitate sharing application-wide data across various modules of your SPA. <a href="https://github.com/ohanhi/elm-taco">Github repo by Ossi Hanhinen here</a>.</li></ul><p>These ideas and patterns sort of intersect with the setup I use. But on some points there are differences, so I like to share these ideas here as well.</p><p>A simple navigation structure may look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*s_rCtJdC_dr_jIadHJMRUA.png" /><figcaption>Simple app flow for the example: show details and go back</figcaption></figure><p>There’s a couple of ways you can implement navigation in Elm:</p><ol><li>The URL determines model state*.</li><li>Model state determines URL.</li><li>Keep model model state and URL in sync at all times*.</li></ol><blockquote>* If you want the URL to determine the model state, allowing users to type the URL in the browser bar, then the easiest way to do this is with a hash (like main#/movies) in the URL. Using a hash will make the browser stay on the same page, and not reload the page by making a server request. You can make it work with plain URLs (like main/movies), but then you need to <br>a) set up your server to always return the same page and <br>b) implement additional stuff to preserve your model state (reloading the page will reset your app’s model).</blockquote><p>In this post the 3rd kind is implemented.</p><p>Also, I really wanted my app to behave in a very specific (and more user-friendly) way: <br><strong>only show a route (page) if all data for that page is available</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*_5NzhRXSoqcqD9skMLkUDQ.gif" /><figcaption>Friendly list navigation : only show details page if details are there..</figcaption></figure><p>For this, I set up my navigation in a different way. The Route type is still used, but only in Msg. It is not stored in the model. Instead, a new type Page is stored in the model.</p><blockquote>The new type Page = Route with Data, essentially making impossible routes impossible.</blockquote><h3>Sync page and browser bar — the logic</h3><p>To make all this work, the app needs the following flow for dealing with a new url:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*NC7rVcUb0lqOIgrqs11GXQ.png" /><figcaption>Flow to keep browser bar and current page in sync</figcaption></figure><p>The check whether the route changed is to prevent endless circular updates.</p><p>If the data is available, the model is updated. If the data needs to be fetched from a server, you can set a loading state in the model. In that case, the users stays at the current page while the data is loading. So you need to set the url back to the url for the current page.</p><p>Later, when the data does come in, the flow is something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*KPGtvUdaUttk7wNWWtu-ig.png" /><figcaption>Flow for when the data comes in</figcaption></figure><p>If the data received belongs to the fetch request made, then the model is updated. At this time, you also need to set the url to the new route.</p><h3>In code —Routes and helpers</h3><p>To use this in my code, I define some additional types and helpers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd4ff0b36a5d0bd7518e44b5a4cc3d25/href">https://medium.com/media/fd4ff0b36a5d0bd7518e44b5a4cc3d25/href</a></iframe><h3>In code — the update function</h3><p>Below is the UrlChange branch of the update function:</p><pre>case Route.parse newLocation of<br>  Nothing -&gt;<br>    ( { model | message = &quot;invalid URL: &quot; ++ newLocation.hash }<br>    , Route.modifyUrl model.currentPage <br>    )</pre><pre>  Just validRoute -&gt;<br>    if Route.isEqual validRoute model.currentPage then<br>      ( model , Cmd.none )<br>    else<br>      case validRoute of<br>        Home -&gt;<br>          ( { model | currentPage = HomePage}<br>          , Cmd.none<br>          )<br>  <br>        Movies -&gt;<br>          ( { model <br>            | currentPage = MoviesPage (Dict.toList model.movies)<br>            }<br>          , Cmd.none<br>          )<br>  <br>        MovieDetail id -&gt;<br>          ( { model <br>            | serverRequest = Just id <br>            , message = <br>                &quot;Loading data for movie : &quot; ++ toString id<br>            } <br>          , Cmd.batch <br>              [ fetchMovieDetail id<br>              , Route.modifyUrl model.currentPage <br>              ]<br>          )</pre><h3>Better view functions</h3><p>The greatest benefit of saving the data inside the Page in the model, is that view functions will become much easier to build.</p><pre>view : Model -&gt; Html Msg<br>view model =<br>  case model.currentPage of<br>    HomePage -&gt;<br>      homeView model <br>     <br>    MoviesPage movies -&gt;<br>      moviesView model movies<br>  <br>    MovieDetailPage movieId movie -&gt;<br>      moviesDetailView model movieId movie</pre><p>You pass the data from the Page directly to the view helper for that page. The view function for a page can now rely on the fact that the data to render the page is there. No more (unnecessary) checking for Maybe data in our view functions. No more presenting users with an empty “please hold while we load your data” page. The page for movie detail data will only be displayed, and can only exist, if there is actual movie detail data to be displayed.</p><h3>Other considerations with this approach</h3><p>In a setup like this, navigation to a new URL may lead to multiple update cycles. One to process the URL, and another one as a result from keeping the browser bar in sync if the new url does not (yet) result in a new route in our model.</p><p>When the app is initialized, the init function also takes an initial location (with a URL) as a parameter. So you will also need to handle the URL in init. So what I typically do, is extract the entire branch for checking and processing a new URL into a separate function called urlUpdate (with a bit of 0.17 nostalgia). It has the following signature:</p><pre>urlUpdate : Location -&gt; Model -&gt; ( Model, Cmd Msg )</pre><p>And it is called from the init function as well as from the UrlChange branch of theupdate function.</p><p>In the view function (and helpers), I find it easiest to always use a [ href .. ] to trigger navigation actions. As a bonus, this also works somewhat better on mobile devices with accessibility options turned on.</p><p>When scaling an app like this, everything that can be viewed as a separate page, I build as a separate route following the pattern above. So these would include (for the example used here):</p><ul><li>Adding a new movie to the list.</li><li>Full-page datepicker to edit publication date.</li><li>Separate settings page.</li><li>etcetera.</li></ul><p>For any other action that is not a full page, I would include different messages (not routes) in my model, like:</p><ul><li>Opening a dropdown for e.g. movie rating.</li><li>Any other on-page editing actions.</li><li>Receiving data from server.</li><li>Deleting a movie from the list.</li></ul><p>For the last one, I have a separate Msg + a branch in my update function. This branch not only outputs the new model, but also a Route.modifyRoute Movies command, to instruct the elm runtime to go back to the overview route (of course we cannot stay at the details page of the movie we just deleted).</p><p>So far, the SPA setup outlined in this post is working pretty well for me. Hope you get some use out of it too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*N_6Q6YUDX8awoTIWyX9V2Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a066c6b9ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/more-on-spa-navigation-in-elm-31a066c6b9ae">More on SPA navigation in Elm</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to turn a Msg into a Cmd Msg in Elm?]]></title>
            <link>https://medium.com/elm-shorts/how-to-turn-a-msg-into-a-cmd-msg-in-elm-5dd095175d84?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd095175d84</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Thu, 05 Jan 2017 12:53:31 GMT</pubDate>
            <atom:updated>2017-01-15T18:05:54.221Z</atom:updated>
            <content:encoded><![CDATA[<h4>You can, but you probably shouldn’t</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*4HvFa4Ik7W1aV5ZPejgULg.jpeg" /></figure><p>A question that occasionally pops up on Elm forums is <em>“how can I create a </em><em>Cmd with only a </em><em>Msg?”</em></p><p>I had the same question at some point. What I wanted, was do an update with one kind of Msg, and then do another update of the model with another kind of Msg. But update does not output a Msg. It outputs a Cmd Msg. So my question was <em>“How can I turn a </em><em>Msg into a </em><em>Cmd Msg?&quot;</em></p><p>At the time, the helpful Elm community gave me an advice that was simply: “don’t”. And I’ve learned since that that was good advice. Here’s why.</p><h4>What does a Cmd with only a Msg do?</h4><blockquote>Usually, when someone asks for a “Cmd with only a Msg”, they mean a command <em>without side-effects</em>. (When I asked this question, that’s what I meant, but I didn’t realize it at the time). This post is about such commands without side-effects. So commands that only affect your own code in Elm. No output to the outside world, and no input from the outside world.<br>There are also functions with the signature Cmd Msg that <strong>do</strong> have side effects. This post is only about side-effectless Cmd Msg. I labeled them Cmd Msg* (with the asterisk) in the titles to denote that the side-effect-less variant is meant.</blockquote><p>Suppose you have an update function that can receive a message that a user has successfully logged in. Which adds a currentUser to your model.<br>And another branch in the update handles messages to show to the user. E.g. some popup window that displays a message for a couple of seconds.</p><pre>type Msg = <br>  ...<br>  | LoginSucceeded User<br>  | InfoMessage String</pre><pre>update : Msg -&gt; Model -&gt; (Model, Cmd Msg)<br>update msg model =<br>  case msg of<br>    ...<br>    LoginSucceeded newUser -&gt;<br>      ( { model | currentUser = newUser }<br>      , Cmd.none<br>      )</pre><pre>    InfoMessage message -&gt;<br>      ( { model | message = Just message }<br>      , Cmd.none<br>      )</pre><p>And now you want to display such a message after the user has successfully logged in. If you could make the LoginSucceeded branch include this as a command in its output, then the runtime would take care of it, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*nE7kojRpiXS4x9igIfB77Q.png" /><figcaption>How Cmd Msg could work (theoretically)</figcaption></figure><p>The command with the InfoMessage would go to the elm runtime. The runtime would send it to the update function — together with our model — and update would make a new model with the new user and the message. Which would then be passed on by the runtime to the view function.</p><p>You actually <em>can </em>do this. If you use the awesome <a href="http://klaftertief.github.io/elm-search/?q=msg+-%3E+Cmd+msg">FancySearch</a> and search for the signature msg -&gt; Cmd msg you’ll get some libraries that already have this helper function built in. You can also make your own quite easily, using functions from the Task library.</p><pre>-- in Elm 0.18<br>send : msg -&gt; Cmd msg<br>send msg =<br>  Task.succeed msg<br>  |&gt; Task.perform identity</pre><p>And it would work. But I wouldn’t recommend it. Here’s why.</p><h4>1. Cmd Msg* is inefficient</h4><p>By creating your own Cmd Msg you are making 2 trips through the elm runtime. Which is unnecessary. The command you are sending out, will end up in some other branch of our update function. Which will make some change to our model (add a message in our example). Right?</p><p>Then why don’t we simply do this change directly from inside our LoginSucceeded branch?</p><pre>-- better: recursive call to update<br>update : Msg -&gt; Model -&gt; (Model, Cmd Msg)<br>update msg model =<br>  case msg of<br>    ...<br>    LoginSucceeded newUser -&gt;<br>      { model | currentUser = newUser }<br>      |&gt; update (InfoMessage &quot;you are logged in!&quot;)<br></pre><pre>-- better: directly update in branch<br>update : Msg -&gt; Model -&gt; (Model, Cmd Msg)<br>update msg model =<br>  case msg of<br>    ...<br>    LoginSucceeded newUser -&gt;<br>      ( { model <br>        | currentUser = newUser<br>        , message &quot;you are logged in!&quot; <br>        }<br>      , Cmd.none<br>      )</pre><p>It will save us a trip through the elm runtime. By doing all changes in one update cycle.</p><p>In practice, the efficiency difference between direct updates and using your own Cmd Msg is usually tiny. The Cmd Msg is already quite fast, so fast in fact, that the intermediate model state won’t even be rendered to the screen.</p><h4>2. Cmd Msg* messes with the structure of your program</h4><p>Typically, all the messages you define in your app are for events that happen <em>outside</em> your elm app (side effects), like sending and receiving data from a server or through javascript ports, getting current time or random data, or for handling user interaction in your view (yes, these are also side-effects).</p><p>If you create your own Cmd Msg, by definition this will not have any side effects. You are in effect directly sending instructions to elm to call your update function, providing it with all the info it needs right from your code.</p><p>When you use Cmd Msg you generate or simulate these events internally in your update function. Now if you find some bug later on, and you want to trace it, it will be a lot harder to find its origin from the update function. The Msg could have come from the outside world (including user interaction in your view), but could also have been generated by another branch in the update itself. This will make debugging harder.</p><h4>3. Cmd Msg* has race conditions</h4><blockquote>Using Cmd Msg gives you NO guarantee about the model state your update will receive.</blockquote><p>In the flow pictured above, the Cmd Msg we created was sent to our update function, together with the version of the model we created at that time.</p><p>Elm however does not guarantee this. It is perfectly possible that <em>after</em> we send our Cmd Msg, but <em>before</em> the next time update is called, some other message comes in. E.g. some other update from the server.</p><p>In our example, between the LoginSucceeded call and the InfoMessage call to our update our model may have changed (!).</p><p>This opens the door to some nasty bugs, which will be very hard to trace and fix later on.</p><p>Especially if you want to be sure that the Msg you are sending is performed immediately after the update from which it is created, and you expect the model to be unchanged from the model at some time, do not use Cmd Msg.</p><blockquote>The Bottomline: You <em>can</em> produce your own side-effectless Cmd Msg in Elm, but think twice before you do. It is probably not the best solution for what you are trying to accomplish.</blockquote><p>My adventures in Elm are still early. Do you have any use cases for which a Cmd Msg is appropriate? Let me know! I’d love to learn from others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd095175d84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/how-to-turn-a-msg-into-a-cmd-msg-in-elm-5dd095175d84">How to turn a Msg into a Cmd Msg in Elm?</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elm Drag and Drop Game]]></title>
            <link>https://medium.com/elm-shorts/elm-drag-and-drop-game-630205556d2?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/630205556d2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Thu, 29 Dec 2016 17:25:47 GMT</pubDate>
            <atom:updated>2016-12-29T17:25:47.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elm Drag and Drop Game — Towers of Hanoi</h3><h4>A tutorial with HTML5 drag and drop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogtcHSos47Z-OlyRelMV5A.jpeg" /><figcaption>Photo Credit: Hanoi by Night | by pimnl | WikiMedia Commons</figcaption></figure><p>This tutorial is a follow-up to an earlier post on HTML5 Drag and Drop in Elm.</p><p><a href="https://medium.com/elm-shorts/html5-drag-and-drop-in-elm-88d149d3558f">HTML5 Drag and Drop in Elm</a></p><p>The starting point for this tutorial is an unfinished version of the game <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Towers of Hanoi</a>. The rules of this game are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*xES7o1rWYHbBnjX6qFD86g.jpeg" /><figcaption>The game, old school</figcaption></figure><ul><li>There are 3 poles</li><li>The left poles has a number of disks on it, varying in size, which the smallest size on top.</li><li>You can move disk from one pole to another pole, but only if there is no disk on the other pole, or if the top disk on the other pole is larger than the one you are moving.</li></ul><h4>Getting started</h4><p>All documents for this tutorial can be found over on github. To get started:</p><ul><li>Clone or download the <a href="https://github.com/wintvelt/elm-html5-drag-drop">elm-html5-drag-drop repository</a> over on github.</li><li>Open the folder labeledexamples.</li><li>The file tutorial-starter.elm is the starting point.</li></ul><p>If you just want to look at the finished example, check out tutorial-finished.elm in the same folder. You can read the code and run the example using elm-reactor.</p><p>The starting point for now is an unfinished version of the game <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Towers of Hanoi</a>. Specifics of the game logic are extracted into their own module Hanoi.elm.</p><p>The setup of main tutorial-starter.elm app is as follows:</p><p><strong>Model</strong></p><pre>type alias Model =<br>    { poles : Hanoi.Poles -- alias for List (List Int)<br>    , movingDisk : Maybe Hanoi.Disk<br>    }</pre><p>The model holds a list of (3) poles, and each pole has a list of up to 7 disks (sorted from small to large). Each disk is an Int, to indicate the size of the disk. In addition, the model holds an indicator if and which disk is currently being moved.</p><p><strong>Msg and update</strong></p><p>The update function to start with simply returns an unchanged model. There is 1 message placeholder NoOp, that doesn’t do anything and is never invoked. This will be filled in later.</p><p><strong>View</strong></p><p>The mainview function calls a helper functionviewPole for each pole in the model. In turn, viewPole calls viewDisk for each disk (if any) on the pole.</p><p>If you run the tutorial-starter, you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*xxnPp4DY-aOFawt2ZftDkw.png" /><figcaption>The (rather boring) starting point of the Towers of Hanoi game</figcaption></figure><p>It’s the starting setup of the game. Right now, the user cannot do anything yet. You will fix that with drag and drop 😉.</p><h4>Step 1. Make an item draggable</h4><p>Making an item draggable happens in the view function. If a disk is on top of the set on a pole and if there are other poles where the disk can move to, then the user should be able to drag them.</p><p>The code already identifies for each disk if it is on top of a pole and has valid destinations. You only need to add the attributes and events to make these disks draggable.</p><p>You will need to modify the lines below, which are in the viewDisk function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b239d18f498f86b31c50622586ba201a/href">https://medium.com/media/b239d18f498f86b31c50622586ba201a/href</a></iframe><p>idx is the index of the disk on the pole. If it is0 then this is the top disk (the only potentially moveable disk on any pole). Hanoi.canMove is a helper function that determines if any other pole can actually take the current disk (if both other poles only have smaller disks on top, it will return False).</p><p>Change the empty attribute list to this:</p><pre>[ <strong>attribute &quot;draggable&quot; &quot;true&quot;</strong> ]</pre><p>This sets the attribute (imported from Html.Attributes) draggable to true. Now, whenever a disk is draggable (and green), your code has also made it a draggable item.</p><blockquote>You can now run your code, to see that you can drag the green disk (a ghost image of the disk will appear).</blockquote><h4>Step 2. Keep track of drags</h4><p>The starting model already has a flag to keep track of moving disks. To start using it, change your Msg type, so the model can be informed that the user started dragging a disk:</p><pre>type Msg<br>    = <strong>Move Hanoi.Disk</strong></pre><p>Hanoi.Disk is an imported type alias for Int, the ID of the disk being moved (also used to determine disk size, so lower ID == smaller disk).</p><p>Then, add a (custom) event to your view function to fire whenever the user starts dragging, right below the draggable attribute you just set:</p><pre>[ attribute “draggable” “true”<br><strong>, onDragStart &lt;| Move disk</strong><br>]</pre><p>disk is the ID of the current disk being rendered in viewDisk. onDragStart is an imported custom event handler, invoked when the dragstart event fires.</p><p>When you define your own custom handler for the onDragStart event, it could look like this (using the on function from the Html.Events package):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74d817a22c0bec56b7622b44423eddf0/href">https://medium.com/media/74d817a22c0bec56b7622b44423eddf0/href</a></iframe><blockquote>The custom handlers used in this tutorial are defined in a separate module <a href="https://github.com/wintvelt/elm-html5-drag-drop/blob/master/src/DragEvents.elm">DragEvents.elm</a>. You can look at that file to see how they are defined.</blockquote><p>In Firefox, HTML5 drag and drop will only work if you directly set the data of whatever is being dragged. If you are using another browser, you can skip this part.</p><blockquote><strong>Firefox fix</strong><br>To make HTML5 drag and drop work in Firefox, you need to call event.dataTransfer.setData(), a method on the dataTransfer object, which is part of the drag event. The clean way to do this Elm is by a port, but there is also a “hack” that you can use: add a one-line javascript statement in an additional ondragstart listener.</blockquote><pre>[ attribute “draggable” “true”<br>, onDragStart &lt;| Move disk<strong><br>, attribute &quot;ondragstart&quot;<br>    &quot;event.dataTransfer.setData(\&quot;text/plain\&quot;, \&quot;dummy\&quot;)&quot;<br></strong>]</pre><blockquote>This ensures that Firefox will also fire all subsequent drag-and-drop events.</blockquote><p>Now that you have ensured that a message is triggered when the user starts dragging, you need to change the update function, to handle the message we defined.</p><pre>update : Msg -&gt; Model -&gt; Model<br>update msg model =<br>    case msg of<br><strong>        Move selectedDisk -&gt;<br>            { model | movingDisk = Just selectedDisk }</strong></pre><p>Since this is a move, instead of a copy action, it would be better if the original disk no longer shows on the pole once the user starts dragging.</p><p>You can do this in this bit of code inside your viewDisk function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec37dcb64093eb5515f199de02fdabf8/href">https://medium.com/media/ec37dcb64093eb5515f199de02fdabf8/href</a></iframe><p>These are the (currently empty) styles and attributes for the disk if it is the moving disk. Change the empty lists inside the tuple to:</p><pre>( [ <strong>(&quot;opacity&quot;,&quot;0.1&quot;)</strong> ]<br>, [ <strong>attribute &quot;draggable&quot; &quot;true&quot;</strong> ]<br>)</pre><p><em>(Your code will still work without setting the draggable attribute for the disk in moving state. But for consistency, it is probably better to put it in anyway.)</em></p><blockquote>Now if you run your code again, you should see that once you start dragging the green disk, the original disk on the pole will be almost transparent.</blockquote><p>And, now that you have wired up to change the .isMoving flag in the model, you may notice that the 2 poles on the right will change color to green (to indicate that this is were you can move the disk to).</p><p>Once you drop the green disk anywhere, the game state doesn’t change: the disk on the pole remains transparent, and the poles on the right remain green. You’ll fix that next..</p><h4>Step 3. Handle cancelations of drag</h4><p>If the user lets go of the dragged item at a random location, the model needs to switch back to the nothing-is-being-dragged mode.</p><p>You can do this by setting up a onDragEnd event listener on the item being dragged. For this, you add a message type and a branch to your update:</p><pre>type Msg<br>    = Move Hanoi.Disk<br>    | <strong>CancelMove</strong></pre><pre>update msg model =<br>    case msg of<br>        ...</pre><pre><strong>CancelMove -&gt;<br>            { model | movingDisk = Nothing }</strong></pre><p>And in your diskView function, add the (custom) handler to send the message, in the place where you set the transparency:</p><pre>( [ (&quot;opacity&quot;,&quot;0.1&quot;) ]<br>, [ attribute &quot;draggable&quot; &quot;true&quot;<br><strong>  , onDragEnd CancelMove<br></strong>  ]<br>)</pre><blockquote>Now run your code again. This time, when you let go of the green disks, the poles and all disks will go back to their non-moving state..</blockquote><p>Bonus: onDragEnd only fires if the drag ends somewhere outside an official drop zone. It does <em>not </em>fire if the user drops on a proper drop zone.</p><p>But at this point, every drop, even on a green pole, will simply cancel. The user still has no valid drop zones. That’s the final step to complete the game.</p><h4>Step 4. Enable drop-zones</h4><p>The app already identifies if a pole is ready to receive a disk being dragged. These poles are colored green when a disk is dragged. That is already wired up in the viewPole function. The final step is to set up the poles as proper drop zones.</p><p>First, add another message to handle the drop:</p><pre>type Msg<br>    = Move Hanoi.Disk<br>    | CancelMove<br>    <strong>| DropOn Hanoi.Pole</strong></pre><p>Hanoi.Pole is a type alias for Int, serving as ID for the pole where the disk is dropped.</p><p>Next, setup a drop handler to the pole. In this bit of code in the viewPole function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f544dea9edd991d149778c767793fe2d/href">https://medium.com/media/f544dea9edd991d149778c767793fe2d/href</a></iframe><p>Add this in the empty list:</p><pre>[ <strong>attribute &quot;ondragover&quot; &quot;return false&quot;</strong><br><strong>, onDrop &lt;| DropOn pole</strong><br>]</pre><p>The &quot;ondragover&quot; attribute is a bit of a hack. It is telling the browser to prevent the default drag behavior (drop is not allowed) on this element. Instead of setting a property, you provide a single line javascript statement to &quot;return false&quot;.</p><p>onDrop is a custom drop handler. This handler needs to prevent default behavior as well, and therefore should be set up with onWithOptions from the Html.Events package. E.g. like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f5c2cf1b39b8f31d58e16e46e053e1/href">https://medium.com/media/c6f5c2cf1b39b8f31d58e16e46e053e1/href</a></iframe><p>Now that your code can fire the drop message, including the pole to drop on, you finish this step by adding the branch for it in your update function:</p><pre>update msg model =<br>    case msg of<br>        ...<br>  <br>        DropOn newPole -&gt;<br>            let<br>                newPoles =<br>                    model.movingDisk<br>                    |&gt; Maybe.map <br>                        (\movingDisk -&gt; <br>                            Hanoi.moveDisk <br>                               movingDisk <br>                               newPole <br>                               model.poles<br>                        )<br>                     |&gt; Maybe.withDefault<br>                         model.poles<br>            in<br>                { model<br>                | poles = newPoles<br>                , movingDisk = Nothing<br>                }</pre><p>In this bit of code, if the model has a moving disk, you call the helper function Hanoi.moveDisk, which moves the movingDisk from wherever it happened to be, to the newPole (but only if this is a valid move). The result is stored in newPoles. Your code then updates the model with the newPoles, and also resets the moving state of the model.</p><blockquote>Congratulations!</blockquote><blockquote>You are done! Your app is finished, and you can now play a whole game.</blockquote><p>Hope you enjoyed the tutorial, and learned a bit of Html5 drag and drop along the way!</p><h4>Further exercises</h4><p>HTML5 has other drag and drop events as well. Custom elm versions are available in the <a href="https://github.com/wintvelt/elm-html5-drag-drop/blob/master/src/DragEvents.elm">DragEvents.elm</a> file. If you want more exercise, here are some ideas for further exploration:</p><ul><li>Make the receiving poles change color whenever the dragged disk hovers over it, using the onDragEnter and onDragLeave events.</li><li>Prevent the user from dragging a disk beyond the boundaries of the app’s screen, by using the onDragLeave event.</li><li>Add a counter to count the number of moves. With 7 disks, the minimum amount of moves required to move all disks from left pole to right pole is 127 (²⁷ -1)…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=630205556d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/elm-drag-and-drop-game-630205556d2">Elm Drag and Drop Game</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTML5 Drag and Drop in Elm]]></title>
            <link>https://medium.com/elm-shorts/html5-drag-and-drop-in-elm-88d149d3558f?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/88d149d3558f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Wed, 21 Dec 2016 18:26:18 GMT</pubDate>
            <atom:updated>2016-12-22T10:32:06.344Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>A mixed bag</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJ0ksuB2WbMlicN2hckbeQ.jpeg" /><figcaption>Photo credit: <a href="https://www.flickr.com/photos/royal65/2327912606">sunset roller coaster | eric lynch | Flickr</a></figcaption></figure><p>Compared to the ‘official’ <a href="http://elm-lang.org/examples/drag">drag-and-drop example</a>, one advantage of HTML5 drag and drop is that you no longer need a subscription to keep track of the dragged object’s position. Saving you a storm of Msg as well. But it is not all good news.</p><h3>The good news</h3><p>HTML5 has built-in support for drag and drop. Which comes with a bunch of goodies:</p><ul><li>You can label any DOM-element as draggable and/or as drop-zone.</li><li>The browser will show the user a nice “ghost-image” of whatever it is that they are dragging.</li><li>The browser shows the user whether or not they can drop whatever they are dragging when they hover over an element.</li><li>And to top it off, there are various events fired off around drag and drop that you can tap into, to handle the drag and drop operations in your own code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*eLaZ5LkHPG60pl04XGXKmw.png" /></figure><h3>Benefits in Elm</h3><p>In Elm there are two main advantages of HTML5 drag and drop over the “standard” subscribe-to-mouse implementation:</p><ul><li><strong>No need for subscriptions</strong>: it is enough to include an event listener on the draggable item and on the drop zone. And you can also — straight in your view — fire an event when the dragged item is entering, over, of leaving some other DOM element.</li><li>With these events, <strong>no additional state is needed to detect hover-over</strong>; to track if the dragged item over is over some other item in the DOM. Your drop zones will fire an event once the dragged item is dropped on it.</li></ul><h3>Caveats</h3><p>However, there are also a couple of peculiarities you need to consider when you implement this in Elm:</p><ul><li><strong>1. Limited styling options for ghost-image. </strong>The “ghost-image” that the users sees while dragging, is a copy of the dragged item (with the styling from the moment the dragging started). In Javascript, you can call a method <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer#setDragImage.28.29">event.dataTransfer.setDragImage()</a> to change this ghost to another image. And an image only. There is no simple way to change the ghost-image to some other HTML element. It also has the curious property that the new image will always have your cursor in the top-left corner. Also if you started your drag in the middle of the draggable item. (examples and demo <a href="http://www.kryogenix.org/code/browser/custom-drag-image.html">over at kryogenix</a>).<br>In Elm, you would always need a port to change the ghost image. (Elm cannot directly access methods on a javascript object).</li><li><strong>2. Drop-zone enablement in Elm is not entirely clean. </strong>To enable something as a valid drop-zone, you need to preventDefault() in the ondragover event. Whether or not you actually have a valid use for that event in your app. In Elm, you could include some NoOp message to handle this (to use with a custom onDragEnter function), but that does muddle your code. Another way to achieve this in Elm, is setting an attribute &quot;ondragover&quot; &quot;return false&quot; on the drop element, but this is kind of an ugly hack. The value of the attribute is not really a property, but it is a one-line piece of javascript code (ugh).</li><li><strong>3. Drop-zone enablement is <em>unsafe</em></strong>. When you enable something as a drop-zone in your app, the user can drop <strong><em>anything</em></strong> on that drop-zone. This could be an item that you made draggable and expect. (and BTW, &lt;img&gt; are draggable by default). But it could also be something completely different: some text, or files, links or images from other apps on the user’s machine. So be aware that your drop-zone is an unsafe entrance to your Elm environment, that you should guard really carefully. Javascript has some methods you can call, to inspect whatever is dropped. In Elm your options are limited (unless, again, ports).<br>The way I protect the drop-zones in Elm, is to only enable elements as a drop-zone while some other element from my Elm-app is being dragged. (by keeping track of a dragging-state in the model).<br>Oh, and it is a good idea that your custom onDrop handler has apreventDefault() as well. Otherwise your browser will open any file or image or link in a new Tab or Window once the user drops it.</li><li><strong>4. Limited access to data of dropped items</strong>. Whenever something is dropped in a drop-zone, javascript provides an event.dataTransfer object to get to the data that is being dropped. However (you may have guessed), most access is through methods, not properties. So not directly available in Elm. If the user selects some text snippet and drops it on a drop-zone, there is no property Elm can read to get find out what the snippet was. Or if the user drops files from their machine on your drop-zone, your Elm code can get to little more than the filename. So without ports, drag-and-drop-file-upload is not possible.</li><li><strong>5. Additional ports needed for Firefox</strong>. I tested in Chrome and IE (and suspect it works in Safari too). But Rohan Orton (<a href="https://medium.com/@rohan_orton/hi-wouter-d5dbde017070#.egyfnj2p1">in response here</a>) pointed out that in Firefox HTML5 drag and drop of HTML items only works if you explicitly call the event.dataTransfer.setData() function. So in Elm, you would need a port for this.</li></ul><h3>Closing thoughts</h3><p>Even with the caveats above, HTML5 drag-and-drop can still be quite useful in Elm.</p><p>If you want to implement strictly within elm — i.e. dragging elm-rendered items and dropping them on other elm-rendered items — then HTML5 is straightforward, and not having to use the subscriptions is a win.</p><p>If you are looking for more advanced stuff — e.g. let users drag images or files from the outside world onto a drop zone in your Elm app — then you will need ports and quite a bit of javascript, to access the dataTransfer object in javascript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88d149d3558f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/html5-drag-and-drop-in-elm-88d149d3558f">HTML5 Drag and Drop in Elm</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make impossible states impossible?]]></title>
            <link>https://medium.com/elm-shorts/how-to-make-impossible-states-impossible-c12a07e907b5?source=rss-df5e2683a420------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12a07e907b5</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Wouter In t Velt]]></dc:creator>
            <pubDate>Wed, 14 Dec 2016 13:12:45 GMT</pubDate>
            <atom:updated>2016-12-18T18:12:59.490Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing different approaches to cleaning your Elm code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*ehjLap4Rbts0PerwHQjBVg.jpeg" /><figcaption>Up and Down the Escher Stairs | by Shawn Clover</figcaption></figure><p>Some time ago, Richard Feldman gave an excellent talk on “<em>making impossible states impossible”.</em> It really caught on in the Elm community. The key point was more or less:</p><blockquote>If certain combinations of data are not allowed in your app, design you data model in such a way that it can only hold allowed data combinations.</blockquote><p>E.g. if an “answer” in your model can only exist if there is a corresponding “question”, then ensure that your data model can only hold an answer if the corresponding question is there too. <br><em>Be sure to check out the </em><a href="https://www.youtube.com/watch?v=IcgmSRJHu_8"><em>video</em></a><em> if you haven’t seen it yet.</em></p><p>When applying this wise lesson in my own code, I found that there are different ways to make impossible states impossible. So I tried different ones, to see how a specific data model structure would impact code elsewhere.</p><p>This article is not so much about <strong><em>why </em></strong>it is a good thing to make impossible states impossible. It is more of an exercise to find out <strong><em>how </em></strong>to do it. And compare some different ways of doing it.</p><h4>The example use case</h4><p>To compare I use an example (perhaps familiar to some), of a set of 2 dropdowns, to select a destination city.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*c0eWUUKJfsh6orQbhY8Drw.gif" /><figcaption>New and improved gif of the dropdown in action</figcaption></figure><ul><li>When there is no country selected from the dropdown, you cannot select a city; the city dropdown is disabled.</li><li>The city dropdown can be empty, when there is no city selected yet.</li><li>When you select a different country, the city dropdown will reset. If you select the same country again, any previously selected city will be preserved.</li></ul><h4>Version 1: Two Maybes — The naive data model</h4><p>My original (naive) model for this was:</p><pre>type alias Model =<br>    { country : Maybe Country<br>    , city : Maybe City<br>    }</pre><p>This data model actually allows impossible states, like:</p><pre>{ country = Nothing<br>, city = Just &quot;Paris&quot;<br>}</pre><p>Technically allowed, but it shouldn’t be possible to have a city selected without a country.</p><p>This original data model requires the update function to include checks to prevent or repair these impossible combinations:</p><pre>update : Msg -&gt; Model -&gt; Model<br>update msg model =<br>    case msg of<br>        CountryPicked pickedCountry -&gt;<br>            let<br>                newCity =<br>                    if model.country /= Just pickedCountry then<br>                        Nothing<br>                    else<br>                        model.city<br>             in<br>                { model             <br>                | country = Just pickedCountry<br>                , city = newCity<br>                }<br>     <br>        CityPicked pickedCity -&gt;<br>            { model<br>            | city = <br>                model.country<br>                |&gt; Maybe.andThen (always &lt;| Just pickedCity)<br>            }</pre><p>The branch to handle the CountryPicked (from the dropdown selection) needs to check whether model.country changed, and if it did, reset model.city to Nothing.</p><p>Fortunately this original data model is exactly what the view function needs. It passes the selected country and city to the respective dropdowns. And disables the city dropdown if there is no country selected:</p><pre>view : Model -&gt; Html Msg<br>view model =<br>    let<br>        (selectedCountry, cityDropDownDisabled) =<br>            case model.country of<br>                Just country -&gt;<br>                    (Just country, False)</pre><pre>                Nothing -&gt;<br>                    (Nothing, True)</pre><pre>        selectedCity = model.city<br>    in<br>        ...</pre><p>Nice and short and pretty readable.</p><h4>Version 2: <em>Maybe Maybe </em>— A cleaner data model, without impossible states.</h4><p>One way to clean up our data model is like this:</p><pre>type alias Model =<br>    { destination : Maybe CitySelection }</pre><pre>type alias CitySelection = <br>    { country : Country<br>    , city : Maybe City<br>    }</pre><p>The model may have a destination. And if it does — in the shape of a CitySelection — the destination must have at least a country, and may or may not have a city selected.</p><p>This makes it impossible to store a city in the data model if there is no country.</p><p>Now the update function would become something like this:</p><pre>update : Msg -&gt; Model -&gt; Model<br>update msg model =    <br>    case msg of<br>        CountryPicked newCountry -&gt;<br>            { model<br>                | destination =<br>                    case model.destination of<br>                        Just { country, city } -&gt;<br>                            if newCountry /= country then<br>                                Just <br>                                    { country = newCountry<br>                                    , city = Nothing <br>                                    }<br>                            else<br>                                Just <br>                                    { country = country<br>                                    , city = city <br>                                    }</pre><pre>                        Nothing -&gt;<br>                            Just <br>                                { country = newCountry<br>                                , city = Nothing <br>                                }<br>            }<br> <br>        CityPicked newCity -&gt;<br>            { model<br>                | destination =<br>                    case model.destination of<br>                        Just { country, city } -&gt;<br>                            Just <br>                                { country = country<br>                                , city = Just newCity <br>                                }</pre><pre>                        Nothing -&gt;<br>                            Nothing<br>            }</pre><p>Oh dear, this really makes the update function quite a bit longer. Sure, there is less room for bugs, because we can never have a selected city without a country, but it is longer. And with all the Just and Nothing branches, it hasn’t really become more readable.</p><p>Also not so attractive: this setup forces us to deal with the strange scenario that the user has selected a city from the dropdown, but there was no destination (so no country) in the model yet. In that case we simply leave the destination unchanged as Nothing. This may be useful to catch strange bugs, so I could include a Debug.crash in there. But still, feels like the update function has not really improved..</p><p>What about the view function for this data model?</p><pre>view : Model -&gt; Html Msg<br>view model =<br>    let<br>        (selectedCountry, cityDropDownDisabled, selectedCity) =<br>            case model.destination of<br>                Just { country, city } -&gt;<br>                    (Just country, False, city)<br>  <br>                Nothing -&gt;<br>                    (Nothing, True, Nothing)<br>    in<br>        ...</pre><p>Pretty short and clean, so that’s good. But is it possible to improve on our update function too?</p><h4>Version 3: Union Typed — Cleaner data model with union type</h4><p>There is another way to clean the data model: by using union types.</p><pre>type alias Model =<br>    { destination : Destination }</pre><pre>type Destination =<br>    NotChosen<br>    | ToCountry Country<br>    | ToCity Country City</pre><p>Again, it is impossible to have a city without a country. And now, the data is more readable, because the abstract Just and Nothing are replaced by more real-life terms.</p><p>The update function to deal with the dropdown selection now looks like this.</p><pre>update : Msg -&gt; Model -&gt; Model<br>update msg model =<br>    case msg of <br>        CountryPicked newCountry -&gt;<br>            { model<br>                | destination =<br>                    case model.destination of<br>                        NotChosen -&gt;<br>                            ToCountry newCountry</pre><pre>                        ToCountry oldCountry -&gt;<br>                            ToCountry newCountry<br>  <br>                        ToCity oldCountry oldCity -&gt;<br>                            if newCountry /= oldCountry then<br>                                ToCountry newCountry<br>                            else<br>                                ToCity oldCountry oldCity<br>             }</pre><pre>        CityPicked newCity -&gt;<br>            { model<br>                | destination =<br>                    case model.destination of<br>                        NotChosen -&gt;<br>                            NotChosen<br>  <br>                        ToCountry oldCountry -&gt;<br>                            ToCity oldCountry newCity<br>  <br>                        ToCity oldCountry oldCity -&gt;<br>                            ToCity oldCountry newCity<br>            }</pre><p>Somewhat more readable, but still quite verbose. Mainly because I now have to deal with all three branches of the Destination twice.</p><p>Fortunately, the view function in this variant is still quite short and sweet:</p><pre>view : Model -&gt; Html Msg<br>view model =<br>    let<br>        (selectedCountry, cityDropDownDisabled, selectedCity) =<br>            case model.destination of<br>                NotChosen -&gt;<br>                    (Nothing, True, Nothing)<br>  <br>                ToCountry country -&gt;<br>                    (Just country, False, Nothing)<br>  <br>                ToCity country city -&gt;<br>                    (Just country, False, Just city)<br>    in<br>        ...</pre><p>But still, the long update function we have is nagging.</p><h4>Version 4: Changed Msg — Change the messages too?</h4><p>One strange thing that happens in the code is that in each version, I have to handle a strange edge case, where the user submits a city to a model that does not have a country. The view does make such a user selection impossible, and the model cannot store it, but the code still has to deal with it.</p><p>It is possible to change our Msg structure too, so that the user can only submit valid destinations:</p><pre>type Msg =<br>  DestinationPicked Destination</pre><p>Now the update function would really become short and sweet:</p><pre>update : Msg -&gt; Model -&gt; Model<br>update msg model =<br>    case msg of <br>        DestinationPicked newDestination -&gt;<br>            { model<br>                | destination =<br>                    newDestination<br>            }</pre><p>But what this really does, is move the job of creating a new destination to the view function. Both dropdowns now need to send valid DestinationPicked messages whenever the user makes a selection of either a country or a city. In previous variants, the Msg could directly be passed to the dropdown.</p><pre>type Msg =<br>    CountryPicked Country      -- : Country -&gt; Msg<br>    | CityPicked City          -- : City -&gt; Msg</pre><p>But now, something way more complicated is needed in the view function to turn a selection in a dropdown to a message with a destination:</p><pre>view : Model -&gt; Html Msg<br>view model =<br>    let <br>        ...<br>        countryPickMsg : Country -&gt; Msg<br>        countryPickMsg newCountry =<br>            case model.destination of<br>                NotChosen -&gt;<br>                    ToCountry newCountry<br>  <br>                ToCountry oldCountry -&gt;<br>                    ToCountry newCountry<br>  <br>                ToCity oldCountry oldCity -&gt;<br>                    if newCountry /= oldCountry then<br>                        ToCountry newCountry<br>                    else<br>                        ToCity oldCountry oldCity<br>  <br>        cityPickMsg : City -&gt; Msg<br>        cityPickMsg newCity =<br>            case model.destination of<br>                NotChosen -&gt;<br>                    NotChosen<br>  <br>                ToCountry oldCountry -&gt;<br>                    ToCity oldCountry newCity<br>  <br>                ToCity oldCountry oldCity -&gt;<br>                    ToCity oldCountry newCity</pre><blockquote>Note: originally, I dismissed this variant for claiming the logic does not belong in the view. But <a href="https://www.reddit.com/r/elm/comments/5iwyyn/article_comparison_of_different_approaches_to/">over on Reddit</a>, NovelTie pointed out that this 4th variant actually has more merit. So I have updated my evaluation below with some new insights I learned from this reponse.</blockquote><p>One thing that is immediately obvious, is that this variant does not eliminate the complexity/ necessary logic in our code, but it moves it from the update to our view function.</p><p>The country dropdown now needs to know about the selected city, to prevent resetting the city, if the user chooses the same country.</p><p>And the city dropdown needs to know about the selected country, to be able to produce a valid new destination-type Msg.</p><p>This is not necessarily all bad news: it is the view’s “job” to deduct from the model what kind of user interaction is allowed. And for that, even a single dropdown may actually need more context than just the values it operates on.</p><h3>Favourite?</h3><p>Below is a simplified comparison of the variants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*BGPuBCVGVnr6ATjB7geOdw.png" /><figcaption>Comparison of variants of the simple example</figcaption></figure><p>The first variant is more of a baseline. It allows impossible states, which of course we want to prevent.</p><p>For now, I like the Union Type variant best. Even though the update function is longer and more verbose, I find the code easiest to read. In general: giving your Maybe- like types more explicit names makes your code easier to read. So I guess that in this case that has also helped this variant.</p><p>However, the 4th variant still has me intrigued as an interesting approach. Originally, I created it to prove that simplification of update functions can be taken too far. But it feels like another theme is emerging: <em>“make impossible updates impossible”…</em></p><h4>Better ways to make impossible states impossible?</h4><p>There are surely better ways to refactor this example and its variants. Extracting the functions from the update function (or the view function in the 4th variant) would surely help.</p><p>Responses so far have already proven that better and other variants exist, and can improve readability compared to the solutions I came up with. Feel free to let me know in the comments!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*N9CTKODv2XWVI4v9wpjvyg.png" /><figcaption>Impossible is nothing</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12a07e907b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elm-shorts/how-to-make-impossible-states-impossible-c12a07e907b5">How to make impossible states impossible?</a> was originally published in <a href="https://medium.com/elm-shorts">Elm shorts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>