<?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[Prima Engineering - Medium]]></title>
        <description><![CDATA[We are a fast growing web company based in Milan (Italy); we love functional programming and cutting-edge technologies such as AWS, Docker, RabbitMQ, Elm, React and so on. We are among the first in Italy running Elixir in production. - Medium]]></description>
        <link>https://medium.com/prima-engineering?source=rss----412da115d3a0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Prima Engineering - Medium</title>
            <link>https://medium.com/prima-engineering?source=rss----412da115d3a0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:06:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/prima-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MEGA: Maybe Maybe is not the right choice]]></title>
            <link>https://medium.com/prima-engineering/mega-maybe-maybe-is-not-the-right-choice-b1d2e966b27e?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/b1d2e966b27e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ivan Gori]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 07:18:19 GMT</pubDate>
            <atom:updated>2022-07-28T14:04:15.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="MEGA: Make Elm Great Again logo made with tangram" src="https://cdn-images-1.medium.com/max/1024/1*_MdK5g5v_-EyPlTb5VOCzQ.png" /><figcaption>MEGA: Maybe Maybe is not the right choice</figcaption></figure><h4>In this article of MEGA I’ll talk about some useful patterns and personal thought about Maybe types in Elm.</h4><h3>Introduction: What is a Maybe?</h3><figure><img alt="Question mark made with tangram pieces" src="https://cdn-images-1.medium.com/max/800/1*XuZHvD8_wdowcrkCI_gNmQ.png" /><figcaption>What is a Maybe ?</figcaption></figure><p>In Elm you don’t have the concept of undefined, you can&#39;t do things like define an optional key in a record or runtime declaration but there is the concept of null. The most common scenario can be the result of an API call that must be saved in a key inside your model but since you don&#39;t have the result at init you&#39;re forced to declare it as a Maybe and initialize your model with a Nothing until the API call will assign the proper value to it. Under the hood, a Maybe is quite different from other languages equivalents, even javascript, mainly because Elm <strong>doesn&#39;t have implicit null references</strong>.</p><blockquote><em>I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object-oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.</em></blockquote><blockquote>The inventor of null references, Tony Hoare</blockquote><p>If in the most common languages the access of a null variable is legit, with a Maybe you (always) must address the unavailability of the value.</p><h3>Avoid Maybes: how and why</h3><p>The <em>nullable</em> concept is quite common and familiar in programming but in Elm, it tends to become insidious. The enforcement to always handle the possibility that a Maybe is not valued properly tends to make your code rapidly unclear and less scalable. You should always <strong>think twice</strong> before wrapping your type inside a Maybe because it will probably hide some architectural deficiencies that can be addressed more elegantly and expressively.</p><h4>Every Maybe it’s like a spoon of baking powder in your cake</h4><p>As we said before in a common imperative language you’ll probably be able to handle your nullable with exceptions and some if and despite all you can write your code without worrying about it because you are quite sure that the value will never be null in that part of the code.</p><p>In Elm’s world every time you need to use a Maybe you <em>must</em> handle both the valued and not valued case. For each Maybe your function will become less readable stuffed of withDefault or maybeMap and it will soon rise, doubling its length for each nullable data.</p><h4>Can you build a house with Maybe bricks?</h4><figure><img alt="A house made with tangram with a missing piece" src="https://cdn-images-1.medium.com/max/580/1*gcDn_jX6kSpXYRBnXivSMg.png" /></figure><p>It probably sounds banal to say but if a Nothing means an Error or a data inconsistency then that result mustn&#39;t be a Maybe! This is a quite common scenario in your API that are written in other languages and where databases are stuffed with nullable fields due to relations with other tables or progressive entity finalization.</p><p>Let’s make an example with a native library, the side-effect function Dom.getElement that tries to find an element with a specific id in your DOM.</p><pre>getElement : String -&gt; Task Error Element<br>getElement =<br>  Elm.Kernel.Browser.getElement</pre><p>The element could not be there but it will be an error trying to find an element that is not rendered. You can notice that the result is not a Maybe Element but an Error or Element that allows you to track the error case explicitly in your update cycle.</p><p>Our API (and our decoders too) should act similarly: or our data are correctly evaluated for the purpose of the API or the whole thing must fail. You should not allow your API to emit implicitly nullable data that will make the consumption of the API impossible, it’s like hiding the dust under the carpet.</p><p>Does have any sense a nullable price into a payment page API only because the price field is nullable in the database (probably because is evaluated by a second microservice in a delayed moment)? No, not for the payment page. If the price is not available for unknown reasons the page can’t show properly so it must be broken!</p><p>👎🏻</p><pre>type alias PaymentData =<br>    { price: Maybe Float<br>    , products: List Product<br>    }</pre><p>👍🏻</p><pre>type alias PaymentData =<br>    { price: Float<br>    , products: List Product<br>    }</pre><p>In a future article, we’ll see some useful tricks to empower decoders allowing us to handle all the problematic cases of a bad structured API but is just a patch on a bigger problem. You should argue with API maintainers if something smells.</p><h4>They’re coming outta the godd** walls!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F108KUzjTMEp2gw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F108KUzjTMEp2gw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F108KUzjTMEp2gw%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/36f0fe1be7ca9d09c277c0252ed6f60a/href">https://medium.com/media/36f0fe1be7ca9d09c277c0252ed6f60a/href</a></iframe><p>Maybesw are like rabbits, they multiply and despite our efforts, there are some cases where we can’t avoid to declare some Maybe data in our model. In such cases, we should analyze the reason behind that proliferation and how to reduce it.</p><p>Often a lot of data are nullable for the same reason or “case”, in such situation it can be handy to group them all in a single nullable data that store them all in their valuated types. Some examples of that are a group of fields in a form or some data needed by an optional part of your view.</p><p>👎🏻</p><pre>type alias Gift =<br>    { hasGreetingCard: Bool<br>    , greetingCardTitle: Maybe String<br>    , greetingCardBody: Maybe String<br>    , greetingCardSignature: Maybe String<br>    --<br>    }</pre><p>👍🏻</p><pre>type alias Gift =<br>	{ greetingCard: Maybe GreetingCard<br>	--<br>	}<br><br>type alias GreetingCard =<br>	{ title: String<br>	, body: String<br>	, signature: String<br>	}</pre><p>Such an approach has different advantages:</p><ul><li>we’ve logically grouped all the fields related to GreetingCanrd in a dedicated type. This makes the model more expressive and easy to understand.</li><li>we’ve reduced the key length name and relative functions (greetingCard.name)</li><li>we can make a GreetingCard module that defines the type and stores all related functions that are based on its evaluated case</li><li>we’ve removed a redundant flag hasGreetingCard that can be replaced with a simple function that checks if greetingCard is Nothing or Just. We should always prefer functions over the stored data when it&#39;s possible. It&#39;s much more scalable and allows us to change a single point (our function) in future refactorings or when your logic changes. If the type is opaque is even better.</li></ul><h4>Maybe it’s a very private person</h4><p>In general a Maybe says a lot about how we must handle it but nothing about why it&#39;s there: <em>when, how and why that value can be null ?</em></p><p>Semantically it’s a simple union type that doesn’t make the case talkative and that’s the reason why understanding the logic behind it’s difficult. If in a common imperative language this is commonly acceptable in Elm where you can write strongly declarative types easily it’s not.</p><pre>type alias Model = <br>    { isPrivacyAccepted: Maybe Bool<br>    }</pre><p>That’s a simple example, here we know that isPrivacyAccepted flag can be Nothing Just True or Just False.</p><p>But what does a first-time programmer can imagine?</p><ul><li>Probably there is a checkbox that can’t be visible/initialized under some circumstances</li><li>Maybe it’s used to model a “tri-state” checkbox</li><li>The data comes from the backend but only in some cases</li><li>…</li></ul><p>Even with such a simple example, we can have a lot of ambiguity.</p><p>Let’s try to use a different type:</p><pre>type alias Model = <br>	{ privacyConsent: Consent<br>	}<br><br>type Consent <br>	= Assent <br>	| Denial <br>	| NotExplicitAnswered</pre><p>Now is much more clear: that key is probably an answer to a tri-state checkbox. And it makes clear that a user could also not express clearly his consent to privacy data treatment. Pay attention, this type <strong>doesn’t resolve the Maybe</strong> but includes it inside its variants.</p><h4>Important things can’t be Maybe</h4><p>Let’s go back to the Gift example</p><pre>type alias Gift =<br>	{ greetingCard: Maybe GreetingCard<br>	-- ...<br>	}<br><br>type alias GreetingCard =<br>	{ title: String<br>	, body: String<br>	, signature: String<br>	}</pre><p>Now let’s imagine that the presence or absence of a GreetingCard will change dramatically our application. A gift with a greeting card produces a dramatically different view, with specific messages, API calls, validations... As a direct result, your code will start to grow because you&#39;ll need to check on that value in a lot of different points and this will make everything less declarative, readable and difficult to maintain.</p><p>In such cases rewrite the whole Gift as an union type may be an interesting solution:</p><pre>type Gift <br>	= Simple GiftData <br>	| WithGreetingCard GiftWithGreetingCardData</pre><p>During the init there will be a creator function for the Gift type that will have the ownership to create Simple or WithGreetingCard variant based on the raw data. You&#39;ll indeed have probably a bunch of redundant functions (but they will be small and simple) but now you&#39;ve strictly enforced all your flow. Now every part of your code will have to handle in a strictly different way the two cases. You&#39;ll probably notice that isolate such logics (update/view/helpers...) in functions that work only on one type is much more convenient and you can store them in their named modules. Gift&#39;s module will take care of hiding the implementation logic working as a &quot;logic hub&quot;.</p><pre>view: Gift -&gt; Html Msg<br>view gift =<br>   case gift of<br>      Simple data -&gt; GiftData.view data<br>      WithGreetingCard data -&gt; GiftWithGreetingCard.view data</pre><p>As a final result, you’ll have 2 sub-applications smaller, simpler and more scalable.</p><p>It’s a great step forward to remove only one Maybe, isn’t it?</p><h4>Maybe’s friends</h4><p>There are some types and patterns that hide Maybe, we could call them Maybish. The Consent type seen before is an example. Collections ( List and Dict) are a common family of types that hide Maybe. We know that picker functions on these types will always return a Maybe a because collections can be legitimately empty. It would be an error to write this in Elm:</p><pre>type alias Model = <br>    { cryingList: Maybe (List (Maybe Int))<br>    }<br><br>addElement: Int -&gt; Model -&gt; Model<br>addElement el model =<br>    { model<br>        | cryingList = Maybe.map (List.append [Just el]) model.cryingList<br>    } <br><br>sumToAll : Int -&gt; Model -&gt;  Model<br>sumToAll addend model =<br>    { model<br>        | cryingList = Maybe.map (List.map (Maybe.map ((+) addend))) model.cryingList<br>    }</pre><p>So if a collection can be legitimately empty you should think carefully about using a simple List if your model or logic needs almost one element to work properly. A more safe model could be the following:</p><pre>type ValuedList a = <br>    ValuedList <br>        { first: a<br>        , remaining: List a <br>        }<br>        <br>toList: ValuedList a -&gt; List a<br>toList (ValuedList {first, remaining}) = <br>    first :: remaining<br><br>head: ValuedList a -&gt; a<br>head (ValuedList { first }) = <br>    first</pre><p>This type is able to guarantee that almost one element is present (common List.head can&#39;t).</p><h3>Don’t hide a Maybe under the carpet</h3><p>If despite all your attempts the Maybe is still there well then <strong>respect</strong> it. If you’re writing <strong>highly reusable</strong> code then try to write functions that work directly on the concrete case.</p><p>There are two main reasons behind this choice:</p><ul><li>you can’t write your logic without another Maybe or a Maybish situation</li><li>you can’t predict how the user will handle the Nothing</li></ul><p>It&#39;s much more convenient to allow the consumer of your code to handle the Nothing case by itself and don&#39;t take care of it and all your code will become much easy to write and understand.</p><p>Let&#39;s think about the ValuedList creation function:</p><p>👎🏻</p><pre>valuedList: List a -&gt; Maybe (ValuedList a)<br>valuedList list =<br>    case list of<br>        (x::xs) -&gt; Just (ValuedList { first = x, remaining = xs })<br>        <br>        _ -&gt; Nothing</pre><p>👍🏻</p><pre>valuedList: a -&gt; List a -&gt; ValuedList a<br>valuedList first rest =<br>    ValuedList { first = first, remaining = rest }<br><br>-- Helper but not the main way to consume your type<br>fromList: List a -&gt; Maybe (ValuedList a)<br>fromList list =<br>    case list of<br>        (x::xs) -&gt; Just (ValuedList { first = x, remaining = xs })<br>        <br>        _ -&gt; Nothing</pre><p>The main creation function asks explicitly for head and tail parts. The fromList is just a convenient helper for some cases.</p><h3>A case study: Form and validations</h3><p>Our forms are probably Maybe’s best friends, the whole html input logic is based on nullable values (text, input, select)</p><pre>type alias FormData = <br>    { name: Maybe String<br>    , selectedOption: Maybe Option<br>    , availableOptions: List Option<br>    , privacyConsent: Consent<br>    }</pre><p>What happens when we need to send this data through an API? What happens if we would need to validate such data to ensure that they are not empty or that they’re properly selected? The simplest approach is to create a function that can express the client-side validation</p><pre>validations: List (FormData -&gt; Bool)<br>validations =<br>    [ .name &gt;&gt; isJust<br>    , .selectedOption &gt;&gt; isJust<br>    ]<br><br>isValid: FormData -&gt; Bool<br>isValid =<br>    List.map validations<br>        |&gt; List.all identity</pre><p>In our update, we’ll probably have an if that will trigger the post only if FormData is valid</p><pre>update: Model -&gt; Msg -&gt; (Model, Cmd Msg)<br>update model msg =<br>    case msg of<br>        Submit -&gt; <br>            model<br>              |&gt; withCmds [<br>                  if FormData.isValid model.formData then<br>                      postFormData model.formData<br>                  else<br>                      Cmd.none<br>              ]</pre><p>It’s simple, but we’ve only moved the problem. In our function postFormData we&#39;ll have to handle the encoding of name and selectedOption null cases. We could use a Maybe.map2 or some empty strings/default cases. What happens if FormData will grow or become more nested? What happens if we need to make some logic that works only on validated data? Again our Maybe it&#39;s not scalable. The solution in such a case can be a type able to store both the raw and the validated version of our formData. Let&#39;s try to write an abstract component to help us:</p><pre>type Validatable raw valid<br>    = NotValidated raw<br>    | Validated valid<br><br><br>create : raw -&gt; Validatable raw valid<br>create raw =<br>    NotValidated raw<br><br><br>validate : (raw -&gt; Maybe valid) -&gt; Validatable raw valid -&gt; Validatable raw valid<br>validate validatorFunction validatable =<br>    case validatable of<br>        NotValidated raw -&gt;<br>            validatorFunction raw<br>                |&gt; Maybe.map Validated<br>                |&gt; Maybe.withDefault validatable<br><br>        validated -&gt;<br>            validated<br>            <br>update: (raw -&gt; raw) -&gt; Validatable raw valid -&gt; Validatable raw valid<br>update rawMap validatable =<br>    case validatable of<br>        NotValidated raw -&gt; NotValidated (rawMap raw)<br>        <br>        validated -&gt; validated<br>        <br><br>map : (valid -&gt; c) -&gt; Validatable raw valid -&gt; Maybe c<br>map  mapper validatable =<br>    case validatable of<br>        NotValidated _ -&gt;<br>            Nothing<br><br>        Validated valid -&gt;<br>            valid<br>                |&gt; mapper<br>                |&gt; Just<br><br>isValidated: Validatable raw valid -&gt; Bool<br>isValidated validatable =<br>    case validatable of<br>        Validated _ -&gt; True<br>        <br>        _ -&gt; False</pre><p>Now we need to define the data model of the form. Let’s make our MyForm module</p><pre>type alias MyForm = Validatable FormRaw FormValid<br><br>type alias FormRaw = <br>    { name: Maybe String<br>    , surname: Maybe String<br>    }<br><br><br>type alias FormValid =<br>    { name: String<br>    , surname: String<br>    }<br>    <br>setName: Maybe String -&gt; MyForm -&gt; MyForm<br>setName value = <br>    Validatable.update (\raw -&gt; {raw | name = value })<br><br>setSurname: Maybe String -&gt; MyForm -&gt; MyForm<br>setSurname value = <br>    Validatable.update (\raw -&gt; { raw | surname = value })</pre><p>now we’ll write the most important function: validator with the use of Maybe.Extra library. Validator is a function that will try to apply a sequence of changes to a dummy version of FormValid in order to try to create a FormValid from FormRaw.</p><pre>dummyFormValid: FormValid<br>dummyFormValid =<br>    { name = &quot;&quot;<br>    , surname = &quot;&quot;<br>    }<br><br>validator : FormRaw -&gt; Maybe FormValid<br>validator raw =<br>    Just dummyFormValid <br>        |&gt; MaybeExtra.andThen2 (\v partialValidated -&gt; Just { partialValidated | name = v }) raw.name<br>        |&gt; MaybeExtra.andThen2 (\v partialValidated -&gt; Just { partialValidated | surname = v }) raw.surname</pre><p>Some remarks:</p><ul><li>dummy is needed to don&#39;t hurt the compiler since we can&#39;t dynamically extend a record</li><li>dummyFormValid could be a little smarter and initialize also all that fields that won&#39;t be validated and can be copied directly fromFormRaw</li><li>each mapping function of andThen2 is a validator function of the single field with a type signaturefieldValidator: FieldValueType -&gt; FormData -&gt; Maybe FormData that in our case is quite simple but could eventually make some extra checks over the field and eventually returnNothing if is not passed</li><li>with a little effort we could rewrite this pipe with a fold on a list of functions as we’ve seen in the previous example</li></ul><p>Finally, we can expose this last function of MyForm</p><pre>validatedCmd: (FormValid -&gt; Cmd msg) -&gt; MyForm -&gt; Cmd msg<br>validatedCmd cmdMap =<br>    Validatable.validate validator<br>        &gt;&gt; Validatable.map cmdMap <br>        &gt;&gt; Maybe.withDefault Cmd.none</pre><p>It’s done. Now we can use our side effects that will work only on FormValid (setter/mapper functions are omitted)</p><pre>update: Model -&gt; Msg -&gt; (Model, Cmd Msg)<br>update model msg =<br>    case msg of<br>        SetName val -&gt;<br>            model<br>                |&gt; Model.updateMyForm (MyForm.setName val)<br>                |&gt; withoutCmds<br>        SetSurname val -&gt; <br>            model<br>                |&gt; Model.updateMyForm (MyForm.setSurname val)<br>                |&gt; withoutCmds<br>        Submit -&gt; <br>            model<br>                |&gt; withCmds <br>                    [ MyForm.validatedCmd postFormValid model.myForm <br>                    ]</pre><p>Some other remarks:</p><ul><li>the validated form state is not stored on the model to avoid inconsistencies. It’s not allowed the possibility to update a field once the form has been validated (you should define a function valid -&gt; raw to go back from aValidated state)</li><li>Validatable.validate always need our validator that probably will never change. Maybe it would be convenient if Validatable would be able to validate (or invalidate) by itself on each update</li><li>Validatable could include another variant to express the condition of “Not yet validated”, maybe we’ll like to show some validation messages only after a first submit attempt</li><li>How we could express the validation logic for each field if we’d like to show some messages under each form field?</li><li>validatedCmd looks like a special mapper isn’t it? Maybe we could make an abstract one for other purposes</li></ul><p>I leave all these observations without an answer hoping that your phantasy and talent will find some interesting solutions.</p><h3>Finally, the end</h3><figure><img alt="super mario dramatic end of level" src="https://cdn-images-1.medium.com/max/256/1*wNbGRV8PeXSfx1OHaUMpNg.gif" /></figure><p>I hope I’ve managed to give you a more clear vision behind the reasons to avoid Maybe abusing. Keep in mind that some data inconsistency is however inevitable but being able to reduce it will improve your code. The next time you’ll be tempted to write Maybe on your keyboard hold on for a while, think if is needed and if you can spare.</p><p><em>Originally published at </em><a href="https://prima.engineering/2021/06/14/mega-maybe-maybe-is-not-the-right-choice/"><em>https://prima.engineering</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1d2e966b27e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/mega-maybe-maybe-is-not-the-right-choice-b1d2e966b27e">MEGA: Maybe Maybe is not the right choice</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MEGA : Make Elm Great Again]]></title>
            <link>https://medium.com/prima-engineering/mega-make-elm-great-again-fd3c0c2c4704?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/fd3c0c2c4704</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm-lang]]></category>
            <dc:creator><![CDATA[Ivan Gori]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 09:50:32 GMT</pubDate>
            <atom:updated>2021-07-06T12:46:09.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="MEGA logo made with tangram" src="https://cdn-images-1.medium.com/max/1024/1*_MdK5g5v_-EyPlTb5VOCzQ.png" /><figcaption>MEGA: Make Elm Great Again</figcaption></figure><h3>MEGA : Make Elm Great Again</h3><h4>An introduction article about Elm development and MEGA series. Why we use it in Prima and why you should be interested in Elm.</h4><p>This is the introduction article of <strong><em>MEGA: Make Elm Great Again</em></strong> series in which I will try to condense some helpful patterns and techniques that I learnt during real-world frontend applications in Elm. These articles are dedicated to mid or experienced Elm and functional programming developers so if you’ve never experienced such topics before you’ll probably find it obscure and unuseful.</p><h3>Introduction to Elm</h3><p>As I said before these articles are not designed for beginners but could prove useful for everyone as a general explanation of a language that you could fairly define <strong><em>exotic</em></strong>. The purpose is just to make a summary on the technical aspects which you probably have never thought about. So if you’re just curious or you’ve never used Elm before it may help you to get a more precise idea about it.</p><p>When we say Elm we talk about two different worlds that are connected but different:</p><ul><li>TEA (<strong><em>The Elm Architecture</em></strong>) it’s the framework that implements the MVU pattern (<strong><em>Model View Update</em></strong>) that allows writing browser applications in the Elm language.</li><li>Elm, an <strong>ML</strong> family programming language. It’s a purely functional language strongly and statically typed. It supports type inference (but writing your type signatures is strongly recommended).</li></ul><p>Elm is independent from TEA but without TEA you can’t do much (well you can always try your functions in elm-repl)</p><p>But what is all this in practice?</p><h3>Elm is a compiled language</h3><p>Elm is a true language with its own compiler Elm -&gt; Javascript but there are some other projects for writing a compiler to other languages ( <a href="https://discourse.elm-lang.org/t/webassembly-compiler-update/5866">WASM</a> for example). The compiler produces javascript code that fully respects Ecma 5 standard. The final result is bundled in a whole monolithic js file that contains all your working code, barely readable and highly optimized. This bundle can be directly included in some external bundle written by you.</p><figure><img alt="An image with compiled javascript from elm code, barely readable" src="https://cdn-images-1.medium.com/max/1024/0*d75uUkvycnJMCHOh.png" /><figcaption>How compiled Elm looks like</figcaption></figure><p>The compiler can be launched directly via CLI or with a bundler (like webpack) plugin that targets <em>.elm</em> files. Using these plugins allows you to import and use your main Elm files directly in your javascript source like any other javascript module and makes your Elm program run like any other javascript object.</p><p>Third-party Elm packages cannot include javascript (since the 0.19 version). TEA and its native libraries are not based on javascript features more recent than Ecma 5. All this means that Javascript compiled by Elm <strong>doesn’t need poly-filling</strong>.</p><h3>Functions are first-class travelers</h3><p>Functions are the main skeleton and probably the only. Any nominal reference inside Elm code is a function, both when the function depends on some input (variable function) and when not (constant function). This allows us to express composition, application and partial application of functions natively, elegantly and expressively. Inside Elm a function like this</p><pre>myFunc: A -&gt; B -&gt; C</pre><p>can be evaluated differently by its use:</p><ul><li>given A and B returns C</li><li>given A returns a fuction B -&gt; C</li></ul><p>Type signatures are a read help for humans. The following is perfectly valid for the compiler (but probably deserves programmer’s hand amputation)</p><pre>evilSum: ((number) -&gt; (number -&gt; number))<br>evilSum = (+)</pre><p>Type signatures are recommended but not mandatory. The compiler is always able to infer the situation but if you use them remember that they are right associative so consider to use brackets to declare high order function types.</p><pre>-- Ok<br>sum: Int -&gt; (Int -&gt; Int)<br>sum = (+)<br><br>-- Ok but less readable<br>sum2: Int -&gt; Int -&gt; Int<br>sum2 = (+)<br><br>-- Ok - automatic type inference<br>mapNoTS mapper = mapper 5</pre><pre>-- Ok<br>map: (Int -&gt; Int) -&gt; Int<br>map mapper = mapper 5</pre><pre>-- Error<br>mapWrongTS: Int -&gt; Int -&gt; Int<br>mapWrongTS mapper = mapper 5</pre><p>Functions that are defined by you can be used only in prefix notation. Operators (eg &lt; &gt; =) are the only functions allowed to be used in prefix and infix notation (and yes like in math operators are functions too). Brackets are not used to define function input but to sort function evaluation and they are &quot;dummy&quot; alternatives to application operators|&gt; or &lt;| that are more convenient when you write your functional code as a pipeline.</p><pre>infixNotation: Int<br>infixNotation = 5 + 5<br><br>prefixNotation: Int<br>prefixNotation = (+) 5 5<br><br>orderWithBrackets: Int<br>orderWithBrackets = mul 5 (sum 3 2)<br><br>orderWithLeftApplication : Int<br>orderWithLeftApplication = mul 5 &lt;| sum 3 2<br><br>pipelineApplication: Int<br>pipelineApplication =<br>    2<br>        |&gt; sum 3<br>        |&gt; mul 5<br>    <br>composition: Int -&gt; Int -&gt; Int<br>composition =<br>    sum<br>        &gt;&gt; mul 5</pre><h3>Your code is not designed around “line number” or “step” concepts</h3><p>Classic procedural/imperative languages are designed around Turing Machine architecture, to resume it shortly:</p><ul><li>a program is a collection of instructions written on a paper roll (virtually infinite)</li><li>a “magic finger” points to/reads a line at a time on the paper roll</li><li>a memory stores data and tells the finger which is the paper row number to point on</li><li>each instruction is read, evaluated, then it changes memory and defines the next row to read</li></ul><p>A language like this can express relatively global or local memory scope. This allows changing things when something knowable at execution time only happens. Throw exceptions, jump to different “lines” of code, access/allocate/change memory, declare and init named references, add debug breakpoints. These features are useful but the compiler is unable to detect unpredictable and potentially destructive situations (runtime errors).</p><p>Well with Elm <strong>no</strong></p><ul><li><em>All</em> the effects that can be generated inside Elm code are evaluable at compile time in term of type. The roll paper can be seen and evaluated in the whole from the first line to the last and you can’t compile code that may produce an unknown result or a type inconsistency.</li><li>Whatever it’s not knowable at compile time (eg an API call or non-elm code execution) is defined as a <strong><em>“side effect”</em></strong>. Side effect production is strongly handled by the architecture</li><li>you can produce a side effect result only in precise “moments” and the result will re-enter in your code in the future, in a <strong>“state”</strong>, dedicated expressively for it.</li><li>you must handle and type properly your side effect result. You’ll have to handle and type both happy (your expected result) and unhappy (some type of error that could happen) possibilities.</li><li>The architecture is the “deus ex machina” that allows us to write something real with this paradigm. It slices your paper roll in discrete sheets (not accordingly line of code but accordingly programmer-defined states ) it evaluates the “sheet” in the whole like a huge big function, stores its result in internal memory, aligns the virtual dom (your view) and then waits quietly for the next event that will determine the next “state” and which “sheet” evaluate.</li></ul><p>Ultimately Elm guarantees that your application, once booted, would <em>never</em> reach an unknown or partially inconsistent state that is not handled. It’s not possible to introduce true runtime errors inside your application besides architecture or compiler bugs (well you could always break the application deliberately in the browser). Even unexpected results from side effect will bring your application to an error state that must be handled.</p><h3>Everything is created, nothing is transformed</h3><ul><li><strong>Pass-by value</strong> is the only admitted</li><li>Change a data structure means <strong>recreate</strong> it interely. The notation to “assign” a value to a record</li></ul><pre>setN: Int -&gt; A -&gt; A<br>setN value a = <br>    { a <br>        | kn = value <br>    }</pre><p>it’s just syntactic sugar to avoid you the boring enumeration of all record’s keys.</p><pre>setN: Int -&gt; A -&gt; A<br>setN value a =<br>    { k1 = a.k1<br>    , k2 = a.k2<br>    -- ...<br>    , kn = value<br>    -- ...<br>    }</pre><h3>The type system is lean but expressive</h3><p>Elm types are <strong>algebraic structures</strong>: a set with some operations (functions) on them. If this definition reminds you of some course of linear algebra you’re not wrong. In Elm you’ve only two ways to define your types:</p><h4>Real type aliasing:</h4><p>With the aliasing you can assign a referenced name to some other types, it allows us to do some things:</p><ul><li>Redefine type name. It can be used to shorten long signatures (like generic/high order functions), writing it once for all, or define parametric types when you’ve generics (see the following sections)</li></ul><pre>type alias MaybeInt = Maybe Int  <br><br>type alias ABToC = MaybeInt -&gt; MaybeInt -&gt; Int<br><br>type alias WithIntTuple a = (a, Int)</pre><ul><li>Define a record with a name and some named keys</li></ul><pre>type alias A = { aValue: Int }</pre><ul><li>Use record type alias named reference to build rapidly a record from arguments (the order of arguments is relative to record keys)</li></ul><pre>type alias A = { aInt: Int, aString: String }<br><br>myA : A<br>myA = A 5 &quot;Ciao&quot;</pre><p>Type aliases are <em>“only”</em> new names, useful to write shorten code but it’s only sugar syntax and it can be very misleading if used unproperly. You could think that you’re building a type-checked type but it’s not.</p><pre>type alias A = { v: String }<br><br>type alias B = { v: String }<br><br>pickV: A -&gt; String<br>pickV {v} = v <br><br>vOfA : String<br>vOfA =<br>    A &quot;Ciao A&quot; |&gt; pickV<br><br>vOfB : String<br>vOfB =<br>    B &quot;Ciao B&quot; |&gt; pickV<br><br>vOf : String<br>vOf =<br>    { v = &quot;Ciao ?&quot;} |&gt; pickV</pre><p>A, B and { v : String } are the same for the type system. The function pickV can accept a record typed A, B or even an unnamed record but formerly consistent with { v: String }.</p><p>Similarly the following situation</p><pre>myA: B<br>myA = A &quot;A&quot;<br><br>myB: A<br>myB = B &quot;B&quot;</pre><p>is still valid for the compiler.</p><p>You should try to limit (or avoid totally) the construction of a record with type alias reference: it’s misleading as we’ve seen before (it’s not clear that you’re building a record) but it’s not scalable neither. When your record has several keys your constructor will be very unreadable (you may remember perfectly the key order but a colleague probably won’t).</p><p>You should also avoid type alias concrete types when this is not giving you a real advantage to your code, the aliasing hides the real type to the reader so someone could not be aware of which types lays behind your alias and as said before it doesn’t protect you from type abusing. Let’s see an example</p><pre>type alias Id = String<br>type alias Slug = String<br>  <br>type alias MyServerData =<br>  { id: Id<br>  , slug: Slug<br>  -- ...<br>  }</pre><p>Id and Slug are not allowing to control your data (everyone can still use String), you can&#39;t express any constraint on these types or help a future developer (when does a string is a valid slug? They must be treated in some different way? Where can I find this logic eventually?). If you need to express this kind of constraints you probably need a simple concrete type.</p><h4>Concrete type:</h4><p>Concrete types, or real types, are declared slight differently: type NameAlias = ConstructorTag &lt;type1&gt; &lt;type2&gt; ... a <em>label</em> or <em>tag</em> followed, eventually, by one ore more other types (primitive or not) that are able to store your data. They can be classified in 3 groups:</p><ul><li>simple (not variant)</li></ul><pre>type RGB = RGB Int Int Int<br><br>type Id = Id String<br><br>type Data = Data Id { rgbColor: RGB, description: String }<br><br>myData: Data<br>myData =<br>    Data <br>      (Id &quot;1&quot;) <br>      { rgbColor = RGB 255 0 0<br>      , description = &quot;my data with red color&quot; <br>      }</pre><ul><li>unions (not intersecting subsets)</li></ul><pre>type Pantone<br>  = Red032C<br>  | Red485C<br><br>type ColorSchema<br>  = RGB Int Int Int<br>  | HEX String<br>  | CMYK Int Int Int Int<br><br>toRgbColorSchema: Pantone -&gt; ColorSchema<br>toRgbColorSchema pantone = <br>  case pantone of <br>      Red032C -&gt;  RGB 239 51 64<br><br>      Red485C -&gt; RGB 218 41 28</pre><ul><li>mutually recursive unions</li></ul><pre>type StringBinaryTree<br>  = Node String StringBinaryTree StringBinaryTree <br>  | Leaf String</pre><p>The <em>labels</em> are constructor functions of the type and they can be directly used only if the type is explicitly exposed by the module where you placed them (this feature allows to restrict type handling and manipulation). Real types are strictly type-checked, two types with different names are different even if they are structurally the same and cannot be used on functions that are not designed for them.</p><h3>Limited polymorphic</h3><p>The only allowed form of polymorphism is parametric polymorphism, similar to diamond &lt;T&gt; of other languages. It can be expressed with lowercase named reference in type declaration (or function signatures). Use parametric types allows reusing your code nicely.</p><pre>type BinaryTree a <br>    = Node a (BinaryTree a) (BinaryTree a) <br>    | Leaf a<br><br>type alias RecordWithA record =<br>    { record<br>        | a : String<br>    }<br>    <br>reusableView: msg -&gt; Html msg<br>reusableView onClickMsg =<br>    div [ onClick onClickMsg ] [ text &quot;Click on Me!&quot;]</pre><p>Remember that runtime evaluation is not admitted. The abstraction must be resolved at compile time to be valid. It means that the code must explicit the generic type at some point to compile.</p><pre>type alias ParentModel =<br>    { intBinaryTree: BinaryTree Int<br>    , stringBinaryTree: BinaryTree String<br>    , recordWithABC: RecordWithA { b: String, c: Int }<br>    }<br>    <br>parentView: Html Msg<br>parentView =<br>    div [] [ reusableView ParentMsg.Click ]</pre><p>Subtyping is not allowed (this is the price for type inference). Any attempt to “generify” using a parametric type, even in a safe way, will be blocked by the compiler.</p><pre>type AFamily<br>    = A (RecordWithA {})<br>    | WithB (RecordWithA { b : Int })<br><br><br>type alias RecordWithA record =<br>    { record<br>        | a : String<br>    }<br><br>-- This function will throw a compiler error because the compiler will type the function output and it will signal the discrepancy in type.<br>-- If you keep in mind that type signatures are not used by the compiler this is more understandable.<br><br>generifyAFamily : AFamily -&gt; RecordWithA record<br>generifyAFamily a =<br>    case a of<br>        A record -&gt;<br>            record<br><br>        WithB record -&gt;<br>            record<br><br><br>pickA : AFamily -&gt; String<br>pickA =<br>    generifyAFamily &gt;&gt; .a</pre><p>function overloading (Ad hoc polymorphism) is not allowed either.</p><h3>It looks like Haskell</h3><p>If you’re a Haskell developer you may think that Elm is just a Haskell dialect with a simpler syntax but it’s an error. There are a lot of differences between these two but to resume:</p><ul><li>Native types are implemented natively (in Javascript) due to performance reasons (eg. String it&#39;s not a List Char).</li><li>Polymorphism is highly limited. Typeclasses can’t be implemented outside kernel code. Accessible type-class are just a few: number, comparable and appendable and they are convenient to be used only in heavy-abstract functions.</li><li>It’s not possible (since the 0.19 release) to define or extend operators.</li><li>Elm code is not lazy evaluated by default, the way to make your function lazy is different and not easy to understand. Write recursive algorithms in Elm needs some attention.</li></ul><h3>Robust but free-form</h3><p>At the net of all these features, the code developing in Elm is fairly less opinionated.</p><p>The developer has a huge control, and responsibility, over the model architecture and code organization. Adding new features on the codebase and refactoring old parts are in general secure and relatively simple tasks. Any part of code that you may have forgotten will be noticed by the compiler.</p><p>The capability to express scalable and strongly declarative architectures is the Elm true force. The need to isolate API communication makes the isolation (or exclusion) of business logic profitable. For the same reason is much convenient to re-build your data in the form that is most suitable for the frontend (and not for the database or BE stack) and in general express your types and functions in a high-level format. Definitely, this is what makes Elm development not only educative (you won’t write procedural code in the same way) but even funny.</p><h3>Target acquired: become a Wise Architect</h3><p>Web development is not famous for the organized planning of software architecture. Services evolve rapidly following Agile’s methods, solutions and architectures tend to become rapidly non-sufficient and untidy due to overgrowing. If this is true in general it’s even more true on frontend: new flows, SEO requests, ABTesting, graphic changes, experimental UX, tracking… are all requirement that often born from non-technical teams and often developed as semi-prototypes that will last forever. It becomes important for an evergreen project to be able to develop architectures that can be <strong>flexible, scalable, clear and talkative</strong>.</p><p>Elm is a powerful tool to reach this target but it can be hard to be able to use it properly. In the next articles we’ll see how to recognize problems and anti-patterns, why we should avoid them and how to replace them with more readable and maintainable code.</p><p><em>Originally published at </em><a href="https://prima.engineering/2021/06/14/mega-make-elm-great-again/"><em>https://prima.engineering</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3c0c2c4704" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/mega-make-elm-great-again-fd3c0c2c4704">MEGA : Make Elm Great Again</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The & Operator in Elixir]]></title>
            <link>https://medium.com/prima-engineering/the-operator-in-elixir-f4af6912c3d5?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/f4af6912c3d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Amegbleame Komlanvi]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 14:34:20 GMT</pubDate>
            <atom:updated>2018-08-22T14:34:19.576Z</atom:updated>
            <content:encoded><![CDATA[<p>28 Feb 2017</p><p>Writing short helpers functions in Elixir is a natural behavior since Elixir is a functional programming language and thankfully Elixir provides a shortcut to save us time: The &amp; operator.</p><h3>Create shortcut anonymous functions</h3><p>Before we get some explanations let’s see what it looks like writing shortcuts anonymous functions.</p><pre>fn x -&gt; x + 1 end is same as &amp;(&amp;1 + 1) <br>fn x -&gt; x + x end is same as &amp;(&amp;1 + &amp;1)<br>fn x, y -&gt; x + y end is same as &amp;(&amp;1 + &amp;2)</pre><p>Now what happens is that the &amp; operator converts the expression inside the parentheses into an anonymous function where &amp;1, &amp;2 and so on correspond to the parameters given to the function. So &amp;(IO.puts &amp;1 &lt;&gt; &quot; &quot; &lt;&gt; &amp;2) is equivalent to fn hello, world -&gt; IO.puts hello &lt;&gt; &quot; &quot; &lt;&gt; world end. Look at the length of each version and judge by yourself.</p><p>A particular use case where the &amp; operator is useful is when we have to pass a function to another function (a common task in Elixir when dealing with data structures).</p><p>For example, we want to get each atom from the following list [19, :elixir, 77, :phoenix, 64, {:one, &quot;one&quot;}, :erlang] returned as a string.</p><pre>list = [19, :elixir, 77, :phoenix, 64, {:one, &quot;one&quot;}, :erlang]<br>list <br>|&gt; Enum.filter(&amp;(is_atom(&amp;1))) <br>|&gt; Enum.map(&amp;(to_string(&amp;1)))</pre><p>When run, the above code outputs: [&quot;elixir&quot;, &quot;phoenix&quot;, &quot;erlang&quot;] which is exactly what we expected.</p><h3>Capture named function</h3><p>Another feature of the &amp; operator is to capture named functions. Capturing mean &amp; can turn a named function into an anonymous function.<br> The above example could be then refactored capturing is_atom and to_string as following:</p><pre>list = [19, :elixir, 77, :phoenix, 64, {:one, &quot;one&quot;}, :erlang]<br>list <br>|&gt; Enum.filter(&amp;is_atom/1) <br>|&gt; Enum.map(&amp;to_string/1)</pre><p>And the output remains the same.<br> This is an optimization since instead of creating an anonymous function and allocating new memory, Elixir maintains a direct reference to the original function. Hope you’ll find this helpful and now that you get it go and save your precious time.</p><p><em>Originally published at </em><a href="https://prima.engineering/2017/02/28/the-&amp;-operator/"><em>prima.engineering</em></a><em> on February 28, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4af6912c3d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/the-operator-in-elixir-f4af6912c3d5">The &amp; Operator in Elixir</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</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 get started using Event Sourcing in an existing project]]></title>
            <link>https://medium.com/prima-engineering/how-to-get-started-using-event-sourcing-in-an-existing-project-f7b3083608ab?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/f7b3083608ab</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Davide Fedrigo]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 12:20:31 GMT</pubDate>
            <atom:updated>2018-08-22T13:04:41.620Z</atom:updated>
            <content:encoded><![CDATA[<p>15 Mar 2017</p><p>A while ago, we realized that Event Sourcing could perfectly fit our needs. I’m not going to write about how we came to this conclusion or what its benefits and disadvantages are. Today I’m gonna focus on how we stopped doing CRUD (and losing information) and how we got rid of a couple of our core DB tables.</p><h3>Poor practical examples</h3><p>I had never done it before, never applied these new concepts. However, I read a lot of blog posts on Event Sourcing, and I though I got (part of) the theory behind it. Unfortunately, practical examples were very difficult to find and <strong>some concepts remained a bit unclear</strong>.</p><h3>Working code that cannot be easily changed</h3><p>There were many interactions with those tables, tables full of precious and untouchable data. Even though the codebase was not that bad, it looked quite tough, or at least delicate, to even think to “move the truth” elsewhere. It was obvious <strong>it couldn’t be done all at once</strong>.</p><h3>No time</h3><p>There’s never time for refactoring or trying new ways out, but sometimes, avoiding it, could be even <strong>more costly than facing it</strong>.</p><h3>What if it could be gradually adopted?</h3><p>We defined a path and moved to the first step. The goal was to make the <em>orders</em> table a read model and be <strong>free to remove and rebuild</strong> it.</p><p><em>Yes, we’re an insurance company and there’s no “orders” table, but for the sake of simplicity I’ll use it for generic and naive examples.</em></p><p>Having a clear path to follow was very important because allowed to migrate without hurry, a little at a time.</p><h3>Define events</h3><p>First of all there was need to get a clear idea of what the meaningful events were.</p><p>We heard about <a href="https://ziobrando.blogspot.it/2013/11/introducing-event-storming.html">Event Storming</a>, a technique to explore the domain starting from domain events. We found out a lot of… “things” (there would be a lot to say), and it gave us the initial events from which we could begin.</p><p>Focusing on behaviours, the first events were modeled. They contained only data about what actually changed, in order to avoid redundant data.</p><pre>{<br>  &quot;event&quot;: &quot;order_created&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;customer_id&quot;: 2<br>}</pre><pre>{<br>  &quot;event&quot;: &quot;order_approved&quot;,<br>  &quot;order_id&quot;: 1,<br>  &quot;approved_at&quot;: &quot;2017-03-01&quot;<br>}</pre><pre>{<br>  &quot;event&quot;: &quot;order_shipped&quot;,<br>  &quot;order_id&quot;: 1,<br>  &quot;shipping_id&quot;: 3<br>}</pre><h3>Store and dispatch events</h3><p>Introducing events into the code base was the next step, and it was a pretty easy one.</p><p>In order to start populating the event store, all we got to do was dispatch and store them, <strong>no side effects</strong>. Direct insert, update and delete operations on the <em>orders</em> table were still there, unharmed, for the time being.</p><p>Everything after this point were saved in both <em>orders</em> table and event store.</p><h3>Projectors</h3><p>What’s in the event store had to become the source of truth.</p><p>Given that a projector derives current state from the stream of events, we were able to update the <em>orders</em> table based on the events recorded in the event store.</p><p>We put a listener to the <em>orderCreated</em> event and started to let it add new records to the <em>orders</em> table. At the same time, the old code that inserted new order records was removed. From now on, it’s a projector responsibility. Running the projector began to be the only way to do it.</p><h3>Past events</h3><p>The next step was to generate and store also the <em>orderCreated</em> events of each old order. They were populated using information gathered from the <em>orders</em> table. That was a one-time process that allowed to get the complete history.</p><h3>Other events</h3><p>The <em>orderCreated</em> event contained only information existing at the very first moment of an order lifecycle. Therefore not all the <em>orders</em> table fields could have been populated using data from the event store.</p><p>We had to define all other events, so that all the fields were covered.</p><p>Every time a new event was introduced, the charge of updating specific <em>orders</em> table field passed to the projector.</p><p>Only when the last field was handled, <strong>the <em>orders</em> table finally became a persistent read model</strong>.</p><h3>It’s done!</h3><p>One event at a time, we got familiar with this new approach and today we couldn’t think of other ways to handle our orders. Once you start, you’ll see events everywhere!</p><p>Of course, we started to face new needs and challenges (versioning for example).</p><p>No, we’ve never dropped the <em>orders</em> table, but the awareness of being able to do it, it’s something you got to feel!</p><p><em>Originally published at </em><a href="https://prima.engineering/2017/03/15/how-to-get-started-using-event-sourcing-in-an-existing-project/"><em>prima.engineering</em></a><em> on March 15, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7b3083608ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/how-to-get-started-using-event-sourcing-in-an-existing-project-f7b3083608ab">How to get started using Event Sourcing in an existing project</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Folding Right — a path towards functional origami]]></title>
            <link>https://medium.com/prima-engineering/folding-right-a-path-towards-functional-origami-e4cebde0226f?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4cebde0226f</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[haskell]]></category>
            <dc:creator><![CDATA[Giovanni Ornaghi]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 12:01:05 GMT</pubDate>
            <atom:updated>2018-08-22T08:45:43.975Z</atom:updated>
            <content:encoded><![CDATA[<p>11 Jan 2018</p><p>In this small article we explore what a fold is, what its properties are, and how it is the basis for all other higher order functions (HOF). At the end we’ll have a better appreciation for functions that fold as much as for those that unfold.</p><h3>What’s in a fold? Patterns of recursion</h3><p>Higher order functions abstract a common pattern of recursion. Map and filter are usually easy to understand, fold can be trickier.</p><pre>def sum([]), do: 0 <br>def sum([head|tail]), do: head + sum(tail)</pre><p>In this sum function, we’re going over a list, accumulating partial results in the stack until there’s only one element left.</p><pre>public int Length&lt;T&gt;(List&lt;T&gt; myList) {<br>	if(myList.Empty){<br>		return 0;<br>	}<br>	return 1 + Length(myList.Skip(1));<br>}</pre><p>This C# is a bit more clunky than the previous Elixir, but it shouldn’t be too hard to read. We have a base case (the list is empty) where we return 0, otherwise we sum 1 to the rest of the computation, calling Length on a shortened list (.Skip(1) is a little LINQ trick doing exactly what it says).</p><p>Both these functions evaluate according to this pattern, given a list of three elements and an infix operator “op”:</p><pre>1 `op` fun([2,3])<br>1 `op` (2 `op` fun([3]))<br>1 `op` (2 `op` (3 `op` fun([])))<br>1 `op` (2 `op` (3 `op` 0))</pre><p>Now, if we suppose that op is actually the sum operator, we can reduce the equation to:</p><pre>1 + (2 + (3 + 0))<br>1 + (2 + 3)<br>1 + (5)<br>6</pre><p>What about our length function? It looks like the operator is not binary anymore, as the second addendum is 1, but look closer!</p><pre>1 + (fun[2, 3])<br>1 + (1 + fun[3])<br>1 + (1 + (1 + fun([])))<br>1 + (1 + (1 + 0))<br>1 + (1 + 1)<br>1 + (2)<br>3</pre><p>If you consider the actual implementation, the operator must be binary, in fact, it’s equivalent to the following function:</p><pre>(fn _el acc -&gt; 1 + acc end)</pre><p>One of the arguments is simply ignored.</p><p>The distinguishing elements of fold that we’ve seen so far are:</p><ul><li>the inner function is binary</li><li>one argument of the inner function is an element of a data structure (for simplicity, the article will only feature recursion on lists)</li><li>the other argument of the inner function is the result of the computation so far</li><li>there is a “seed” element representing the value at the base case</li></ul><p>If we consider map or filter in their most common API, we can see that their inner function is unary, i.e., it simply accepts the current element. Does that make you think of something tricky we can do with fold?</p><p>What we showed in the previous example is not a very efficient fold for large lists. You might have heard of tail-recursive functions, which are actually your more common for loops in disguise. The issue we’re now facing is that the stack of operations could get very large, producing an infamous Stackoverflow error in our code. We don’t want that. We can rewrite our functions like so:</p><pre>def sum([], acc), do: acc<br>def sum([head|tail], acc), do: sum(tail, head + acc)</pre><p>Look at the evaluation tree now:</p><pre>fun([1,2,3], 0)<br>fun([2,3], 1)<br>fun([3], 3)<br>fun([], 6)<br>6</pre><p>This is a function you must have written hundreds of times, the “max” variable acts as our accumulator:</p><pre>public int GetMax(List&lt;int&gt; myList){<br>	var max = 0;<br>	foreach(el in myList){<br>		if(el &gt; max){<br>			max = el;<br>		}<br>	}<br>	return max;<br>}</pre><p>For now, you should notice that the only thing differing in the folds we’ve seen, besides the little aside on tail-recursion, is the binary operator. We’re ready to implement the fold function itself:</p><pre>def reduce(f, [], acc), do: acc<br>def reduce(f, [head|tail], acc), do: reduce(f, tail, f(head, acc))</pre><h3>Go right, go left</h3><p>Warning: this section contains some Haskell code since there’s no right vs left fold in Elixir. Don’t panic! I promise I won’t talk about monads. Some familiarity with reading type signatures however would greatly increase your understanding.</p><p>Folds are commonly classified in “right fold” and “left fold”. Right folds are right associative, left folds are left associative.</p><p>Let’s see some code:</p><pre>foldr (+) 0 [1, 2, 3]<br>6</pre><p>The function is called “foldr”, or fold right. (+) is our binary inner function. 0 is our seed value, this is what we will pass as output once the data structure is at its end. [1, 2, 3] is the data structure we’re folding over.</p><p>What happens under the hood is our familiar deconstruction:</p><pre>1+(2+(3+0))<br>1+(2+(3))<br>1+(5)<br>6</pre><p>You should notice that parentheses are on the right, in this sense we say “right associative” and that’s the mystery behind the term “foldr”. By contrast, let’s see a left fold:</p><pre>foldl (+) 0 [1, 2, 3]<br>6</pre><p>The result is identical, but what’s happening is slightly different:</p><pre>((0+1)+2)+3<br>((1)+2)+3<br>(3)+3<br>6</pre><p>While the number of steps is the same, the process is not. You might recall from grade school that addition is associative, so what’s the big deal? Well, if you’re working in a context where you have lazy evaluation, since associativity is on the left, in order to return any result, fold left needs to go through the whole structure, it cannot pass intermediate results. This is a bit of a bummer if you’re working with infinite lists!</p><p>Take this example:</p><pre>head&#39; xs = foldr const 0 xs</pre><p>(const given two arguments returns the first). You might be thinking that to write “last” in terms of fold, you only need to use foldl, and to a point, you’re correct:</p><pre>last&#39; xs = foldl (flip const) 0 xs</pre><p>(flip inverts the order of the arguments, we’ll see why we need this when we consider the different type signatures of foldr and foldl).</p><p>But if you’re working with infinite lists, the matter complicates quite a lot. Take the function below. In the case of a finite list, it would return the seed value, but since the list is infinite, it will never return!</p><pre>foldl (const) 0 (repeat 3)</pre><p>However, we can take the head of an infinite list with foldr:</p><pre>foldr (const) 0 (repeat 3) <br>3</pre><p>How does it work? Consider the first evaluation step for foldr:</p><pre>3 const fun(const, repeat(3))</pre><p>const has type: a -&gt; b -&gt; a. Due to equational transparency, a=3, b=repeat 3. Since Haskell is lazy, we don’t need to evaluate b and simply return a.</p><p>But don’t dismiss foldl just yet, it can be used to code neat tricks like:</p><pre>reverse = foldl (flip (:)) []</pre><p>This example allows us to introduce the structure of the inner binary operator. At each step, we apply the function we passed to fold which takes the next element in the structure and the accumulator. But which is which? In Haskell, that’s easy to answer:</p><pre>foldr :: Foldable t =&gt; (a -&gt; b -&gt; b) -&gt; b -&gt; t a -&gt; b<br>foldl :: Foldable t =&gt; (b -&gt; a -&gt; b) -&gt; b -&gt; t a -&gt; b</pre><p>Don’t mind the Foldable typeclass. The inner function of fold right takes an element (a) and the accumulator (b) in this order, while fold left works in the exact opposite fashion. So could we reverse a list with fold right? what’s so special with fold left? We can, but it’s a bit uglier:</p><pre>reverse xs = foldr (\a b -&gt; b ++ [a]) [] xs</pre><p>which is equivalent to this beauty:</p><pre>reverse = foldr (flip (++) . (:[])) []</pre><p>There’s three main points to take home when talking about right and left folds:</p><ul><li>associativity: the order of computation is different</li><li>inner function: the different association is reflected in the order in which the arguments are passed to the inner binary function</li><li>when dealing with infinite lists, fold left is not really an option, use with caution</li></ul><h3>Properties of fold</h3><p>Warning: this section is a bit math heavy, give it your best or safely skip ahead if it’s not your cup of tea.</p><p>Did you know that any recursive function can be expressed in terms of fold? Let’s see some examples applied on lists. You might want to experiment on your own before you read further.</p><p>Map</p><pre>map f = foldr (\a b -&gt; f a : b) []</pre><p>Filter</p><pre>filter p = foldr (\a -&gt; if p a then (a:) else id) []</pre><p>In the past century, some clever folks started studying what’s called “recursion theory” and found some fascinating properties of fold. I’ll list some of them and provide reference for the more inquisitive reader. All examples and definitions below are from <a href="http://www.cs.nott.ac.uk/~pszgmh/fold.pdf">Hutton, 1999</a>.</p><p><strong>Universal property</strong></p><p>Any recursive function can be expressed in terms of fold.</p><p>If:</p><pre>g _ [] = v <br>g (x:xs) = f x (g xs)</pre><p>Then:</p><pre>g = fold f v</pre><p>Wait, what does this mean? The first equation simply says: there’s a seed value v. The second equation describes how the function works otherwise: g recurses over a list, f is applied to each element and the accumulator. When these two equations stand, we have a fold. Let’s take a familiar function as an example:</p><pre>sum [] = 0 <br>sum (x:xs) = x + sum xs</pre><p>It’s easy to see how v = 0 and f = (+), then:</p><pre>sum = fold (+) 0</pre><p><strong>Fusion property</strong></p><p>The composition of an arbitrary function and a fold can be fused together to give a single fold.</p><p>As you can imagine, the universal property is at play here! You can read the proof in the Hutton paper, the result is:</p><p>If:</p><pre>h w = v <br>h (g x y) = f x (h y)</pre><p>Then:</p><pre>h . fold g w = fold f v</pre><p>Which, in more layman terms can be exemplified to:</p><pre>(+1) . fold (+) 0 = fold (+) 1</pre><p>Follow the previous line of thought with this example in mind to convince yourself it is true. Personally, I find the fusion property the most useful thing to remember for beginner origami students. So many times we waste resources writing stuff like:</p><pre>[1,2,3] <br>|&gt; Enum.map(&amp;(&amp;1 + 1)) <br>|&gt; Enum.map(&amp;(&amp;1 * 2))</pre><p>When the following would give an equal result without enumerating twice:</p><pre>[1,2,3] <br>|&gt; Enum.map(&amp;((&amp;1 + 1)*2))</pre><p>(Alternatively, Stream acts like a fusion since we’re passing each element through instead of iterating n times). As a specific case of fusion using map and fold, it should be easy to see that:</p><pre>fold f w $ map g xs = fold (f . g) w xs</pre><p>Lastly, fun fact: did you know that Elixir’s famous |&gt; operator is implemented in terms of fold?</p><h3>Unfold your potential</h3><p>There’s a little known fact among beginner functional programmers: what one can fold, one can unfold! If that just sounds like a stupid play on words, see the following example from the Elixir docs:</p><pre>Enum.scan(1..5, &amp;(&amp;1 + &amp;2)) <br>[1, 3, 6, 10, 15]</pre><p>I wonder what will happen if I do</p><pre>scanl (+) 0 [1,0,1,1,2,3]</pre><p>In this last section we’ll quickly go over:</p><ul><li>the scan pattern of recursion</li><li>the difference between scanl and scanr</li><li>a little application of the universal property</li></ul><p>If we take the previous Elixir function, we can imagine it does something like this:</p><pre>(1 + 0)<br>: (1 + 0 + 2)<br>: (1 + 0 + 2 + 3)<br>: (1 + 0 + 2 + 3 + 4)<br>: (1+  0 + 2 + 3 + 4 + 5)<br>: []</pre><p>The pattern of recursion then is similar to that of fold, except we want to keep intermediate results. If we take our more analytical description of the characteristic of fold, we see that they all apply to unfold. In fact both fold and unfold have an inner binary function taking an element and the accumulator, and both have a seed value. What’s different then is how scan operates after applying the inner function. Recall that we wrote fold as:</p><pre>def reduce(f, [], acc), do: acc <br>def reduce(f, [head|tail], acc), do: reduce(f, tail, f(head, acc))</pre><p>scan could then be:</p><pre>def scan(f, [], acc), do: reverse(acc) <br>def scan(f, [head|tail], acc = [ha|_]), do scan(f, tail, [f(head, ha) | acc])</pre><p>Coming to the question of left and right, we’re in a bit of a dilemma. We have an intuition that the two directions indicate associativity once again, but of what operation? Is it of the inner function or the list accumulation (read : or | as cons)? Well, if you think about it, it wouldn’t make much sense to put parenthesis differently around cons. Previously we showed the example of “const” where left and right associativity had very different outcomes, but since in any scan we’ll have the same cons behavior, what’s left is the inner function.</p><p>If you managed to read the previous section on the properties of fold, you know that any recursive function can be written in terms of fold. Scan is a recursive function, so how can we rewrite it?</p><p>Our previous Elixir implementation of scan doesn’t give much of a hint, that’s because we didn’t emphasize the cons operator. Remember that by the fusion property</p><pre>h . fold g w = fold f v</pre><p>We can imagine h being cons and g being our inner function. It doesn’t really work, but it’s an intuition. All we need to do then is to extract the cons from our previous pattern of recursion. The Haskell Prelude implementation of scanr is pretty easy to read:</p><pre>scanr                   :: (a -&gt; b -&gt; b) -&gt; b -&gt; [a] -&gt; [b]<br>scanr _ q0 []           =  [q0]<br>scanr f q0 (x:xs)       =  f x q : qs<br>                           where qs@(q:_) = scanr f q0 xs</pre><p>We apply scanr recursively. Scanr by itself applies the inner function (f x q) and cons to the rest (:qs = scanr on the tail!). So where is the fold? That’s exactly the f x q part in disguise, equivalent to our f(head, a) in the Elixir implementation. Can you see why? q is in fact the result of scanr on the tail, which is itself an application of f x q. That means that q is an accumulator of sorts on which we apply f x.</p><p>At this point you might be thinking: OK, I have a better understanding of fold, I can appreciate its power, but unfold? Really? Have you ever actually used it? That’s the problem with self-contained examples, sometimes it’s hard to see beyond them. So here’s a couple of code snippets from production©.</p><p>Here’s my solution to the second part of <a href="https://adventofcode.com/2017/day/11">day 11 of 2017 Advent of Code</a>, the infamous Hexagon Manhattan distance problem.</p><pre>move :: String -&gt; (Int, Int, Int)<br>move &quot;n&quot; = (0, 1, -1)<br>move &quot;ne&quot; = (1, 0, -1)<br>move &quot;nw&quot; = (-1, 1, 0)<br>move &quot;s&quot; = (0, -1, 1)<br>move &quot;se&quot; = (1, -1, 0)<br>move &quot;sw&quot; = (-1, 0, 1)<br><br>transform :: [String] -&gt; [(Int, Int, Int)]<br>transform = map move<br><br>-- oh my, I could have put the coordinates in lists and used zipWith (+) a b!<br>sumTwoCoords :: (Int, Int, Int) -&gt; (Int, Int, Int) -&gt; (Int, Int, Int)<br>sumTwoCoords (a, b, c) (x, y, z) = (a+x, b+y, c+z)<br><br>distance :: (Int, Int, Int) -&gt; Int<br>distance (x, y, z) = maximum [abs(x), abs(y), abs(z)]<br><br>solve2 :: [String] -&gt; Int<br>solve2 a = maximum $ map distance $ scanl sumTwoCoords (0, 0, 0) $ transform a</pre><p>so what the scanl does here is it creates a series of coordinates given a series of moves. The input is a series of moves (n = go north, sw = go south west) and it asks to return the maximum distance from the origin ever encountered. What we do is simply apply the movement to the previous coordinate. If that’s not production© enough for you, here’s a snippet from our own codebase. It’s not a straight-out scan since we don’t recurse over a given list, but the pattern is quite similar:</p><pre>def unfold_substitutions(nil, acc), do: acc<br>def unfold_substitutions(%Quote{substitution_insurance_id: nil}, acc), do: acc<br>def unfold_substitutions(%Quote{substitution_insurance_id: insurance_id}, acc) do<br>prev = %{save: %{quote: kuote}} =<br>Insurance<br>|&gt; Insurance.by_insurance_id(insurance_id)<br>|&gt; Insurance.preload_save_quote()<br>|&gt; Repo.one()<br><br>unfold_substitutions(kuote, acc ++ [prev])<br>end</pre><p>Oh my, acc ++ [prev]? Who wrote this garbage?! (surprise! It was me!). What this function does is simply list all the predecessors of a particular insurance. An insurance policy can be changed while still active, spawning a second insurance. This process is commonly called “substitution” of an insurance. The id of the previous insurance is stored on the quote object related to the insurance. The funny spelling kuote is so it doesn’t clash with the Elixir reserved quote keyword.</p><h3>Conclusion</h3><p>In this short article we went over a lot of material, starting from the basics of fold to its most esoteric properties. If you were uneasy about this peculiar recursion pattern, I hope you feel a bit more comfortable. The getaway points should be:</p><ul><li>each HOF is really a particular recursion scheme</li><li>fold holds a special place among them because everything can be written in terms of fold</li><li>fold has an interesting opposite: scan!</li></ul><p>Next time you’re doing some data transformation, remember your friends fold and scan, they can turn an ugly mess into beautiful origami!</p><p><em>Originally published at </em><a href="https://prima.engineering/2018/01/11/folding-right/"><em>prima.engineering</em></a><em> on January 11, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4cebde0226f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/folding-right-a-path-towards-functional-origami-e4cebde0226f">Folding Right — a path towards functional origami</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing combinatorial cases with Elixir macros]]></title>
            <link>https://medium.com/prima-engineering/testing-combinatorial-cases-with-elixir-macros-4987f5d2448d?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/4987f5d2448d</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <dc:creator><![CDATA[Giovanni Ornaghi]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 11:59:18 GMT</pubDate>
            <atom:updated>2018-08-22T08:37:06.276Z</atom:updated>
            <content:encoded><![CDATA[<p>13 Feb 2017</p><p>In this short article we’ll see how to leverage Elixir macros, and a little ExUnit trick, to easily and safely test our application. This method is especially useful when we have a set of cases that can be combined in different orders or groups. What I usually see happening is that the developer will write a couple of tests for a few simple cases and call it a day. Sometimes this is good enough, sometimes it can lead to trouble down the road.</p><h3>From a true story…</h3><p>I had been tasked to update our interface to a business-critical third-party service. While under normal circumstances this would mean reading the new docs, checking that the integration tests are still green, having QA test for non-regression, these were not normal circumstances. <br> All we knew about the new API was that the WSDL of their SOAP service changed, some endpoints instead of being called “abc” were now called “abcv2”. Some redundant parameters were also removed from the requests. The last docs they issued were from 2 years ago and they didn’t have a reliable testing environment. Luckily all the changes were on GET endpoints.</p><p>After making the appropriate changes in the code, what surprised me the most was that all the tests were still green. I had to dig deeper. I decided to make a list of all the calls and diff the responses from the new and old endpoints. The new API had an extra field and another one was missing, that was all.</p><h3>Testing karma</h3><p>Checking manually was too cumbersome: the order of the fields in the respective responses was different, and the new responses had a new field we couldn’t care less about. Clearly there was an easy way to automate this process and leave a little gift to my colleagues in the form of a test (or 400!).</p><p>My idea was to loop through all the calls and parameters, call the old and new API, decode the responses in a %Map and assert their equivalence. Decoding the responses to a Map would solve the issue with the order and the extra field: ExUnit shows you a green\red diff in the terminal. I was OK with a few failing asserts since the new API has a new field and the service I’m calling is far from deterministic.</p><p>Property-based testing wasn’t good enough for a few reasons. First of all, I’m not testing for a property of a function, this is an integration test. Secondly, the space of all possible cases is small enough to be tested exhaustively. Lastly, some tests will fail and I’m OK with that, as long as I can see how.</p><h3>Macros to the rescue</h3><p>At this point I knew that macros were the tool I needed. I had read <a href="https://pragprog.com/book/cmelixir/metaprogramming-elixir">a little book on Elixir macros</a> a few months prior, but I was hardly confident with them. After a few hours of tinkering and googling I had an almost working macro. The remaining piece of the puzzle was having ExUnit register an appropriately named test for each function the macro was generating. Luckily I had the chance to use a <a href="https://github.com/matteosister/quick_chex">property-based testing library</a> written by a colleague, so I knew this was possible. More studying, more tinkering, eventually this is what I came up with:</p><p><em>test/support/my_macro.ex</em></p><pre>defmodule Service.Support.MyMacro do<br><br>  @relative_urls [&quot;:param/abc&quot;, &quot;:param/def&quot;]<br>  @params [&quot;one&quot;, &quot;two&quot;]<br><br>  defmacro non_regression_test do<br>    for url &lt;- @relative_urls, param &lt;- @params do<br>      stub = String.replace(url, &quot;:param&quot;, param)<br>      quote bind_quoted: [stub: stub] do<br>        test_func_name = ExUnit.Case.register_test(__ENV__, :test, stub, [[args: stub]])<br>        def unquote(test_func_name)(%{args: stub}) do<br>          assert call_local(stub) == call_remote(stub)<br>        end<br>      end<br>    end<br>  end<br>end</pre><p><em>test/non_regression_test.exs</em></p><pre>defmodule Service.NonRegressionTest do<br><br>  use Service.ConnCase<br>  import Service.Support.MyMacro<br><br>  non_regression_test()<br><br>  def call_local(call) do<br>    ...<br>  end<br><br>  def call_remote(call) do<br>    ...<br>  end<br>end</pre><p>This simple macro will:</p><ul><li>loop through all the combinations of relative urls and params</li><li>ask ExUnit to register a function as a test</li><li>generate such function</li></ul><p>Consider @relative_urls to be the list of endpoints under test and @params a list of arguments for said calls. The initial for will loop through all the parameters for each URL. The macro magic starts from quote. For the uninitiated, quote will take some Elixir code and transform it into an AST (Abstract Syntax Tree), which is the underlying structure that the interpreter will eventually evaluate for every Elixir program. <a href="https://hexdocs.pm/elixir/Kernel.SpecialForms.html#quote/2-options">bind_quoted</a> will make sure that the arguments will be unquoted only once, but please do check the link for a more throughout explanation. <br> ExUnit provides a way to register a function as a test via <a href="https://hexdocs.pm/ex_unit/ExUnit.Case.html#register_test/4">register_test</a>. It needs a context (__ENV__), what kind of test we want to register (:test, :property…), the name (which in this case corresponds to the endpoint URL), and a list of arguments. <br> Finally unquote will allow us to inject values in an AST. In this case, we’re creating a function named after the value of test_func_name with arguments stub, which we registered one line above.</p><h3>Conclusion</h3><p>Metaprogramming is a powerful tool, but with great power comes great responsibility. We must consider the tradeoff between the complexity a macro introduces and the benefit it gives us. I believe that that macro was simple enough to be in a test environment, and what’s better is it gave me a new method I can use in the future to test my code exhaustively. A few more examples that I’ve seen in the wild that could benefit from this method include:</p><ul><li>an event-based application where the order in which the events are processed cannot be predicted</li><li>a patch\diff algorithm: in cases where applying the diffs in different order shouldn’t change the end result</li><li>an expression calculator: combining different commutative zero-sum expressions shouldn’t change the result</li><li>… more?</li></ul><p><em>Originally published at </em><a href="https://prima.engineering/2017/02/13/generate-tests-with-macros/"><em>prima.engineering</em></a><em> on February 13, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4987f5d2448d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/testing-combinatorial-cases-with-elixir-macros-4987f5d2448d">Testing combinatorial cases with Elixir macros</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The advantages of functional programming]]></title>
            <link>https://medium.com/prima-engineering/the-advantages-of-functional-programming-3fc5ec479f91?source=rss----412da115d3a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/3fc5ec479f91</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <dc:creator><![CDATA[Giovanni Ornaghi]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 08:22:33 GMT</pubDate>
            <atom:updated>2018-08-22T08:19:41.787Z</atom:updated>
            <content:encoded><![CDATA[<p>27 Jan 2017</p><p>In the past few years functional programming has caught the attention of industry programmers once again. Among such developers is the team I’m working with at Prima.it. While some of us had short stints of F#, Haskell, or LISP, for most of the team higher-order functions, pure functions, and immutability were concepts that were learned, and tested, after many years of object-oriented programming. <br> The reasons that lead us to move from a PHP monolith to Elixir microservices are the topic of another article. Presently I’d like to focus on what we believe are the advantages of programming in a functional style. Hopefully, at the end you’ll see why we still believe that <a href="http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html">functional programming matters</a>.</p><h3>How do we define functional programming?</h3><p>It seems that every developer has her own vague definition of what functional programming (FP) represents. I’ll claim that this is not due to ignorance, but rather due to the fact that most developers see it as a language feature rather than a way to write and structure their code. Of course some languages won’t offer tail-call optimization, higher-kinded types or currying, but these are hardly what makes some code “functional”, in fact, Elixir fails on the last two examples.</p><p>The difference is in the way the programmer thinks and structures her code: from methods to functions, from classes to modules. We won’t care about the behavior of an object, its methods, focusing instead on the functions related to a particular data structure. Here methods and functions cannot be used interchangeably: methods are related to the instance of a class, they change its internal state while representing a particular behavior; functions, on the other hand, are transformations from input to output. Ideally functions are “pure”, that is, they don’t alter anything outside their scope. <br> From a design point of view, having modules instead of classes makes all the difference. Instead of composing classes, one composes functions. Instead of trying to model the business around objects and their state, the developer can focus on the input-output pipeline where each function is a step of the transformation. Instead of trying to map the complexity, we could scale it down by putting each part in a module, may it be an actual Module construct or a function. At the same time, one can see how many SOLID principles such as Single Responsibility still apply: functions related to a particular step of the computation would go inside the same module, which needs to be bound and named sensibly. Through the use of closures we can then achieve Inversion of Control, while Immutability often comes with the territory.</p><p>That said, for the FP examples we’ll use Elixir, the language we use and love, since it implements many concepts out of the box. That’s not to say that you cannot do FP in C#, Javascript or even PHP, it just needs a bit more work. I’ll present two interesting features (higher-order functions, immutability) that I consider among the pillars of FP. The last part of the article is about pattern matching, an interesting language feature shared by many functionally oriented idioms.</p><h3>A new way of thinking: from how, to what</h3><p>The most staggering difference that FP presents, compared to other mainstream programming paradigms, is the different focus required from the developer. Some simple patterns of computation are abstracted in favor of more terse, and yet more expressive, code. This is often the case with higher-order functions (HOF). HOFs are functions that accept another function as an argument, making them effectively a function upon another, thus higher-order.</p><p>The most basic examples come from the realm of iteration and recursion. One hardly needs to explain this Elixir code:</p><pre>&gt; Enum.map([1,2,3,4], fn n -&gt; n * 2 end) <br>&gt; [2,4,6,8]</pre><p>Here [1,2,3,4] is a list we’re iterating, while the second argument is a function that takes a number and outputs its double. Other examples of HOFs are fold (aka reduce), filter, and their combination. Reduce abstracts the concept of accumulation, for example summing over a list of numbers:</p><pre>Enum.reduce([1,2,3,4], 0, fn n, acc -&gt; n + acc end)</pre><p>The second argument, 0, is commonly called the “seed” and represents the neutral element of the computation. The third argument is once again a function, this time taking two arguments: the current element and the result of the computation up to that point. In a future article we’ll explore fold in more depth, explaining the difference between a left and right fold. We’ll also see that fold has a very special role among HOFs. <br> The same way functions can be composed, so can HOFs. In Elixir the chaining (mathematically speaking, this is not exactly the same as composition, but for our purposes it will do), is achieved with the |&gt; (pipe) operator. Take this example from our codebase, while the syntax could be a bit obscure, you should be able to get the gist:</p><pre>prices <br>|&gt; Enum.zip(Enum.map(prices, &amp;guess_price(&amp;1, quote_data))) <br>|&gt; Enum.reject(&amp;match?({_price, {:error, _msg}}, &amp;1)) <br>|&gt; Enum.map(fn {price, {:ok, val}} -&gt; {price, val} <br>                       {price, _}  -&gt; {price, :error} <br>end)</pre><p>The pipe has nothing magical about it. In fact, in the Elixir Core code, it’s implemented as a fold, applying one function on top of the other.</p><p>When we write our usual foreach, what we really want to do is to iterate over a collection of elements. But even in a foreach, the amount of symbols we need to keep track of is often distracting. Take this imperative any as an example (in pseudo-code):</p><pre>var counter = 0; <br>foreach(x in [1,2,3,4]) { <br>    if (x % 2 == 0) { <br>        counter++; <br>    } <br>} <br>var has_any = counter &gt; 0;</pre><p>The point is not to write less code, be faster, and make management happy. Instead, FP claims that these abstractions help the developer focus on what’s important: the general algorithm, not the details of variable tracking and the exact order in which they’re instantiated and mutated. You don’t need to tell the computer how to iterate, just tell it what you expect as a result! Personally, I got enamored with Haskell the moment I realized that I could solve this Project Euler problem as a one liner, which expressed exactly the complicated 3-way-for-nesting operation I had in mind, but was too bored to write:</p><pre>Problem: find a Pythagorean triplet for which a + b + c = 1000. </pre><pre>Solution: <br>&gt; hd [(a, b, c) | c&lt;-[1..500], b&lt;-[1..c], a&lt;-[1..c], a^2+b^2 == c^2, a+b+c == 1000] <br>&gt; (375, 200, 425)</pre><h3>Immutability: a peek into what makes FP tick</h3><p>Immutability helps immensely in reducing the complexity of a piece of software. By never being able of mutating an input, the amount of information you have to keep track of in your head shrinks considerably. <br> Here is an example of what kind of complexities await in the good old imperative world. This code was written by my girlfriend for her Arduino project:</p><pre>... <br>char letter = message[j]; <br>int sequence[] = {0, 0, 0, 0}; <br>recognize(letter, sequence); <br>... <br>void recognize(char letter, int sequence[]) { <br>    if (letter == &#39;a&#39;) { <br>        sequence[0] = 1;<br>        sequence[1] = 2; <br>        sequence[2] = 0; <br>        sequence[3] = 0; <br>    } <br>... <br>}</pre><p>The values of the sequence array are changed inside another function, recognize, that as far as we know could be in another file or even part of a third-party library. The array serves two contradictory purposes: it’s both input and output. This is far from an academic critique, because as much as this example is contrived, you might be mutating the value of a variable without thinking too much on how it’s used in the caller’s function. It is not a case against pass-by-reference schemes either, we could make an analogous point about reinstatiating the same variable twice in the same scope: put some ifs, some for loops, and it’s already a mess.</p><p>Immutability is closely related to another important FP concept: referential transparency, by which we mean that for any given function with this property one could substitute the input value for its argument without noticing any change. As an example take the function sum defined as:</p><pre>def sum(a, b), do: a + b</pre><p>Calling sum(3, 4) would be the same as writing:</p><pre>def sum(3, 4), do: 3 + 4</pre><p>We’re substituting 3 for a and 4 for b. This property however is not shared by every function, namely impure functions. In fact, referential transparency doesn’t hold for functions like this:</p><pre>var i = 0; <br>function funny_sum(a, b) { <br>   i += 1; <br>   return a + b + i; <br>}</pre><p>Another important point for immutability is parallel processing. By having immutable pointers one cannot accidentally mutate another process’ values. Thread-safety is then guaranteed and the performance gains come for very little expenses in terms of complexity and brain power. Languages like Elixir and F# make running parallel processes a breeze by providing strong abstractions. Here’s an example from our codebase:</p><pre>[:a, :b, :c] <br>|&gt; Enum.map(fn(name) -&gt; <br>   Task.async(fn -&gt; {name, apply(data, String.to_atom(&quot;get_#{name}&quot;), [all_params])} end) <br>end) <br>|&gt; Task.yield_many(5_000)</pre><p>For each element in the initial array we generate an async task, then we yield them, giving a timeout of 5 seconds.</p><p>Lastly, immutability makes testing much easier. There’s no more need to mock complex chains of objects and, in our experience, the arguments being passed from one function to another tend to be quite small. Instead of passing a model for a complex real-world entity, often all we need is a couple of strings. <br> One needs not to worry about some methods changing a field of an object somewhere, and since every function needs to return something, every function is technically testable. Our codebase crawls with short but helpful inline tests, such as:</p><pre>@doc &quot;&quot;&quot; <br>iex&gt; Service.Posizionale.Creator.plateNumber(&quot;LO006302&quot;) &quot;LO006302&quot; <br>iex&gt; Service.Posizionale.Creator.plateNumber(&quot;PC068741&quot;) &quot;PC068741&quot; <br>iex&gt; Service.Posizionale.Creator.plateNumber(&quot;RC04D121&quot;) &quot;RC04D121&quot; <br>iex&gt; Service.Posizionale.Creator.plateNumber(&quot;RM9H1764&quot;) &quot;RM9H1764&quot; &quot;&quot;&quot; <br>def plateNumber(t = &lt;&lt;head::bytes-size(2)&gt;&gt; &lt;&gt; &lt;&lt;number::bytes-size(5)&gt;&gt;) do <br>   case head in @provinces &amp;&amp; is_integer(number) do <br>      true -&gt; t <br>      _ -&gt; &quot;*&quot; &lt;&gt; t<br>   end <br>end <br>def plateNumber(t) when byte_size(t) &lt; 7 do<br>   &quot;*&quot; &lt;&gt; t <br>end <br>def plateNumber(t), do: t</pre><p>This function is responsible for formatting a plate number according to a third-party service specification. In this case specs and functions live on the same page.</p><p>A common feature of languages geared towards FP is pattern matching. In Elixir this aspect is particularly advanced, making the code more pleasant to both read and write. The main idea is to have a way to branch your code according to the input. A kind of polymorphism applied on the values themselves, instead of a simple type declaration. <br> Let’s consider this famous algorithm: starting from a positive integer number n, if n is odd, multiply it by 3 and add 1, if it is even, halve it. Continue until you reach 1. Instead of a messy junction of if-else statements, carefully vetted for their order and correctness, we can simply write:</p><pre>def collatz(1), do: 1 <br>def collatz(n) when n % 2 == 0 do <br>   collatz(n / 2) <br>end <br>def collatz(n), do: collatz(3*n + 1)</pre><p>Pattern matching happens in the first variant of collatz, when we want to output 1 if the input is 1. In the second variant we added a when statement, also called a guard, to check the value of n. Lastly, for any remaining input we perform the appropriate operations. Having matched all other cases, n must be odd and different from 1. As a more interesting example, we can pattern-match by destructuring our input. Take this snippet from our codebase:</p><pre>defp return_or_retry({_, %{status_code: 500}}, envelope, call_name, all_params) do <br>   Process.sleep(200) <br>   Service.Logger.retry_on_500(call_name) <br>   do_call(:ok, envelope, call_name, all_params) <br>end <br>defp return_or_retry(res, _, _, _), do: res</pre><p>Here we’re validating the result of an HTTP call. First is the “unhappy” path: a 500 status code. Pattern matching is done on a structure inside another structure, namely, an Elixir map (the %{} part) inside a tuple ({}). As long as the map has a status_code key, it’s game. At the end is the “happy” path, everything is fine and we simply return the result. You could see pattern matching as glorified if-else, and you wouldn’t be too far off; the advantage however is in the way it allows us to isolate its different branches in different functions altogether, each with its own scope, easily and making each decision as clear as one can get.</p><h3>Conclusion</h3><p>In this article we simply dipped our toes in the vast sea of functional programming. FP offers great advantages and it’s a joy to use, but it also has a learning curve. Besides studying the more abstract concepts (lambda calculus, referential transparency, equational reasoning, currying…) you might want to get your hands dirty by using an FP-friendly language in your next pet project. You might start feeling like a beginner once again, having trouble with the most simple algorithm, looking about wondering what is everyone talking about. Stick with it! Our industry shifts from one technology to the next extremely fast, after a while it all becomes a blur and one wonders if we’re moving at all. FP is not a technology, it’s a whole programming paradigm, it’s a set of concepts and skills that you can take with you whatever the latest trendy framework.</p><p>The exciting Haskell you write at night will eventually leak into the boring C# you write by day, showing you that programming goes beyond syntax and tools, it starts from your brain and ends at your fingertips.</p><p><em>Originally published at </em><a href="https://prima.engineering/2017/01/27/advantages-of-functional-programming/"><em>prima.engineering</em></a><em> on January 27, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fc5ec479f91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/the-advantages-of-functional-programming-3fc5ec479f91">The advantages of functional programming</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>