<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergio Ordine on Medium]]></title>
        <description><![CDATA[Stories by Sergio Ordine on Medium]]></description>
        <link>https://medium.com/@sergioordine?source=rss-3a619bb5d25d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7yv1DJJqG3V6SkifozcApw.jpeg</url>
            <title>Stories by Sergio Ordine on Medium</title>
            <link>https://medium.com/@sergioordine?source=rss-3a619bb5d25d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:42:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergioordine/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Result Builders]]></title>
            <link>https://medium.com/academy-eldoradocps/result-builders-3bdfc350d419?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bdfc350d419</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[result-builder]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 17:45:15 GMT</pubDate>
            <atom:updated>2021-09-16T17:49:23.079Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create your own Swift-based, SwiftUI-like, descriptive domain specific languages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-xm_0b0e6aYrnjtLfQRlOw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glen Carrie</a> on <a href="https://unsplash.com/s/photos/lego?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The first thing that draw my attention when studying SwiftUI is its descriptive nature to define views:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa7d2cfc6fcec928225f464512eece6/href">https://medium.com/media/8fa7d2cfc6fcec928225f464512eece6/href</a></iframe><p>The view structure is somehow clear even to people that does not know deeply Swift or even programming: it is a view composed by a vertical stack that holds a label text and another stack, horizontal this time, that holds two other text labels.</p><p>So it generates a visual element that has a <strong>Text</strong> field &quot;<strong><em>A Text</em></strong>&quot; over &quot;<strong><em>Second Text…</em></strong>&quot; and &quot;<strong><em>and another one…</em></strong>&quot; fields side-by-side.</p><p>One thing that draws the attention is that body property definition as well as <strong>VStack</strong> and <strong>HStack</strong> subelements are just listed sequentially. This characteristics makes the visual hierarchy defined more readable and, thus, easy to understand.</p><p>But this is not a structure we are used in Swift. So the first question that arises is: is it a SwiftUI specific structure or can I use it somehow to create our own descriptive structures?</p><p>To answer this question we can analyze the SwiftUI View structure in order to get some hints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d967ae67aaa56ed7196dfeb841700f91/href">https://medium.com/media/d967ae67aaa56ed7196dfeb841700f91/href</a></iframe><p>The <strong>@ViewBuilder </strong>option<strong> </strong>that we see in both cases seems to do the job of creating this view composition in a descriptive way, almost creating a view construction language within Swift itself.</p><p>Those languages are called DSL (Domain Specific Language): a simple language tailored to work on a single, specific domain. In this case: a visual components hierarchy building.</p><p>DSLs could apply to several domains: a language to define rules from salary calculation, to define a web page structure, to define rules for billing a kind of service and so on. Those languages can make easier translate domain rules into code.</p><p>The ViewBuilder construction is preceded by an <strong>@</strong> sign. Those constructions of Swift language are called<strong> property wrappers</strong>. Similar features are sometimes called <strong>annotations</strong> in other languages.</p><p>A property wrapper is, above all, a type. It encapsulates another type in other to add functionalities and processing to it.</p><p>Considering it is not the focus of this article, I’ll briefly give an example from <a href="https://www.swiftbysundell.com/articles/property-wrappers-in-swift/">this article</a>, that also has further information about these types and how work of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b41719ddd950251cda7531990900399b/href">https://medium.com/media/b41719ddd950251cda7531990900399b/href</a></iframe><p>The property wrapper <strong>@Capitalized</strong> wraps a String to make it capitalized. It can be used in a transparent way, so <strong>User</strong>’s <strong><em>firstName</em></strong> and <strong><em>lastName</em></strong> properties, whenever defined or changed, are always capitalized.</p><p>View Builder is also a<strong> property wrapper</strong> of an special type, called <strong>result builders</strong><em> (</em>prior<em> </em>called<strong> funcion builder</strong><em>)</em>, that was created to support the definition of DSL-like languages within Swift.</p><p>So we got our first answer that leads to a second one: how to use it for my specific purposes?</p><p>A result builder is a property wrapper that can be applied to a functions, computed properties or function parameters that basically concatenates the result of each line of code that defines these and returns a single result. As an example, using the HStack we called before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da103b7d056d8232d59337350a0fa0a2/href">https://medium.com/media/da103b7d056d8232d59337350a0fa0a2/href</a></iframe><p><strong>HStack</strong> <strong>initializer</strong> has a content parameter that is a closure with no parameters that returns a Content. This content is created by encapsulating the result of each line of code, in this case, two <strong>Text</strong> fields. Those text fields are concatenated as the content of this <strong>HStack</strong>. We could have components that can embody even other components (as another stack), creating a hierarchy.</p><p>We could do that without adding each constituent component as a subview, appending them into a data structure or adding any other control code. Basically we define what is contained in that stack instead of how we compose it. That is one of the main characteristics of this DSLs: being a declarative language.</p><p>The result builders are property wrappers, therefore a class or structure, annotated as such with the <strong>@resultBuilder</strong> property wrapper. Its required method is <strong><em>buildBlock</em></strong>, that has a variadic list of homogeneous parameters (a Swift function can have variable number of arguments defining them as <strong>Type…</strong>) and compose them into a single result value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7408154252c0207597f38d19c043bfa6/href">https://medium.com/media/7408154252c0207597f38d19c043bfa6/href</a></iframe><p>When a function, computed property or a funciton parameter is annotated as <strong>@AResultBuilder</strong> the function body expects that each line result in a element of <strong>Type</strong>. When all of them are executed, each one of them are used to create a single element of <strong>ResultType</strong> by the <strong><em>buildBlock</em></strong> function.</p><p>It answers, in theory, how to implement a structure like SwiftUI declarative view system. But some more practical examples could come in handy.</p><p>In the<a href="https://sergioordine.medium.com/result-builders-189f3bfc3aa3"> next part of this article</a>, a practical example will be presented as well as the basic usage of result builders.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bdfc350d419" width="1" height="1" alt=""><hr><p><a href="https://medium.com/academy-eldoradocps/result-builders-3bdfc350d419">Result Builders</a> was originally published in <a href="https://medium.com/academy-eldoradocps">Academy@EldoradoCPS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collection View improvements]]></title>
            <link>https://medium.com/academy-eldoradocps/collection-view-improvements-f85fb7edb4e2?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85fb7edb4e2</guid>
            <category><![CDATA[collectionview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 11:36:17 GMT</pubDate>
            <atom:updated>2021-09-03T11:26:04.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQFh-yx0nwQsgXW7YFQ8nQ.jpeg" /><figcaption>Photo adapted from <a href="https://unsplash.com/photos/KFIjzXYg1RM">Jeremy Bishop</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Since WWDC 2019 Apple make several improvements on collection views, specially on data management and layout. These improvements make easier to use and update those visual elements that are so important in all Apple platforms.</p><p>We are going to focus the examples on iOS apps here. This <a href="https://github.com/sjordine/doglist">repository</a> has a sample app that uses <a href="https://thedogapi.com/">The Dog API</a> to present information about different dog breeds and, through this practical example, show how to use the new structure and features of collection views. If you want to use this code, please request an API key and update the code as indicated in the <a href="https://github.com/sjordine/doglist/blob/main/README.md">README.md</a> file.</p><h3>Concepts</h3><p>Collection view architecture uses separation of concerns to implement it in a more composable and maintainable way. There are three main elements: data, layout and presentation.</p><ul><li><strong>Data</strong> — it represents <strong>what</strong> must be presented: the information itself. The Diffable Data Source APIs, introduced in iOS 13, allows creating uniquely identified sections and cells, using the <a href="https://developer.apple.com/documentation/swift/hashable"><strong>Hashable</strong></a> protocols. As those pieces of data are uniquely identified, any change in their state can be managed by the collection view with no need of an explicit batch update, what removes a lot of boilerplate code and complexity. Also, iOS 14 introduces section snapshots, that makes easier manage data per section basis, making composition easier as well as some common features, are collapsible/expandable elements.</li><li><strong>Layout</strong> — it represents <strong>where</strong> a piece of data shall be presented. The compositional layout API allows declaratively defining simple layout elements that can be composed to create more complex ones. It also allows scroll sections orthogonally to the collection view scroll direction, a feature that is becoming very common. The list configuration also creates a way to make a section, or even the whole collection view, behave as a table view.</li><li><strong>Cell</strong> — Cells present the data elements within a given layout. The cell registration process was simplified with the new collection view API as well as its population, that is now less coupled with the index path information. List cells can be used to mock the basic table view cell layouts and view configuration allows an easier way to manage cells data and state dependent elements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*H9LxPPn1kWUImrEWgqNBlg.png" /><figcaption>Fig. 1 — Collection view general architecture</figcaption></figure><p>This architecture redesign improves the separation of concerns and makes it easier to work with collection views, specially with complex layouts and data hierarchy. In the other hand it introduces new concepts and a new way of dealing with both data and layouts, thus, there is a learning curve to use this new approach even for developers who are already used to collection views.</p><h4>Article Structure</h4><p>This article is composed by several parts to address specific topics on this subject. Here, the main concepts associated with the architectural model change were discussed.</p><p>Then, a discussion about how those concepts and elements work together is important. In this <a href="https://sergioordine.medium.com/modern-ios-collection-views-ab66aefd3591">article</a> (and its complementary parts) it will be discussed further, presenting the execution flow.</p><p>After this conceptual part, it will be presented one of the predefined layouts made available that make collection view sections looks and behaves like table views with a practical example. This is presented in <a href="https://sergioordine.medium.com/collection-view-lists-c4f26b73721f">this article</a> and its related parts.</p><p>Using this example, we can discuss the modern cell configuration approach, that isolates cell population from its visual components. <a href="https://sergioordine.medium.com/collection-view-lists-a565fe746bcb">This article</a> address such functionality.</p><p>Another useful layout is sections that run orthogonally to the collection view scroll direction, such as carousels. The compositional layout makes very easy to implements it and also allows discussing the compositional layout concepts and how to provide a layout for each collection view section. This is the main subject, with a practical example, of this <a href="https://sergioordine.medium.com/collection-view-carousels-cc1e2939c95">article</a>.</p><p>In the <a href="https://sergioordine.medium.com/modern-ios-collection-views-ab66aefd3591">next article</a>, as mentioned before, it will be discussed how these concepts are tight together and an overview on how to setup both the collection layout and its data.</p><h4>References</h4><p>This series of articles was strongly based on the following references. Those are great sources of additional information:</p><p><a href="https://developer.apple.com/videos/play/wwdc2019/220/"><strong>Advances in UI data sources </strong></a>— This session from WWDC 2019 presents the diffable data sources</p><p><a href="https://developer.apple.com/videos/play/wwdc2019/215/"><strong>Advances in collection view layout</strong></a> — This session, also from WWDC 2019, presents the compositional layout mechanism and associated concepts.</p><p><a href="https://developer.apple.com/videos/play/wwdc2020/10027/"><strong>Modern cell configuration</strong></a> — This session from WWDC 2020 presents a mechanism to isolate cell population from its visual components, improving code decoupling and maintenability.</p><p><a href="https://developer.apple.com/videos/play/wwdc2020/10045/"><strong>Advances in diffable data sources</strong></a> — This WWDC 2020 session presents diffable data sources improvements, specially to create hierarchical data.</p><p><a href="https://developer.apple.com/videos/play/wwdc2020/10097/"><strong>Advances in UICollectionView</strong></a> — This session, also from WWDC 2020, presents some predefined collection view session layouts that allows creating expandable sessions and tableview-like sessions.</p><p><a href="https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/implementing_modern_collection_views"><strong>Implementing Modern Collection Views</strong></a> — This source code presents a lot of samples on how to use the new collection view features and its potential. It is a great reference for starting developing using this new architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85fb7edb4e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/academy-eldoradocps/collection-view-improvements-f85fb7edb4e2">Collection View improvements</a> was originally published in <a href="https://medium.com/academy-eldoradocps">Academy@EldoradoCPS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript and Swift]]></title>
            <link>https://medium.com/academy-eldoradocps/javascript-and-swift-66c59bf2317e?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c59bf2317e</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[javascriptcore]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Sun, 08 Nov 2020 20:51:37 GMT</pubDate>
            <atom:updated>2020-11-09T14:38:33.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to enhance your apps with scripting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8A0wQmNaXcqN5OU50am4A.jpeg" /></figure><p>The iOS platform provides, since iOS7, the <strong>JavaScriptCore</strong> framework, a way to use the WebKit javascript engine embedded on our apps. You can use it independently of a web view, what makes it a useful component when you new to flexibilize a feature or set of features.</p><p><strong>Note</strong>: All code presented here was run in a Swift Playground (XCode 12.1).</p><h3>The Basics</h3><p>Let&#39;s start with the basics given through the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17e50f36c31f981409c0433697b63e21/href">https://medium.com/media/17e50f36c31f981409c0433697b63e21/href</a></iframe><p>We need do import the <strong>JavaScriptCore</strong> framework in order to use it. This framework provides an environment, given by the class <a href="https://developer.apple.com/documentation/javascriptcore/jscontext"><strong>JSContext</strong></a>, that is to run the scripts (using the <a href="https://developer.apple.com/documentation/javascriptcore/jscontext/1451350-evaluatescript"><strong>evaluateScript</strong></a> function).</p><p>The script is passed to the function as a regular <strong>String</strong>. So it can be defined on code, get from a file or even from internet (from a remote source as a server-side application).</p><p>The last result from the script is returned by <strong>evaluateScript</strong> as a <strong>JSValue </strong>(it is important to notice that it could be also an <em>undefined</em> value).</p><p>The JSValue provides a set of functions to convert a javascript value to a Swift/Objective-C value (<strong>toInt32</strong>, <strong>toString</strong>, <strong>toDate</strong>, <strong>toArray</strong> between others), as well as functions to check the type returned (<strong>isNumber</strong>, <strong>isInt32</strong>, <strong>isString</strong>, <strong>isNull</strong>, <strong>isUndefined</strong> etc.). Using this set of tools you can both check what was returned as well as unwrap this value to use it on your Swift code.</p><h3>Passing Data Back and Forth</h3><p>Is it possible also to store Swift values into javascript variables and get javascript variables values to use on Swift Code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647128d672b4fded7bec503d5e64686c/href">https://medium.com/media/647128d672b4fded7bec503d5e64686c/href</a></iframe><p>using the <a href="https://developer.apple.com/documentation/javascriptcore/jscontext/1451416-setobject"><strong>setObject</strong></a> function we can get a Swift value and store it as a JavaScript variable (named according the <strong><em>forKeyedSubscript</em></strong> parameter — notice that the name shall be casted as a <strong>NSString</strong>). This value can than be addressed as a javascript variable, as we can see on the <strong>evaluateScript</strong>.</p><p>On the opposite way, we can retrieve a javascript value (as a <strong>JSValue</strong> type) to use it on Swift using the <a href="https://developer.apple.com/documentation/javascriptcore/jscontext/1451771-objectforkeyedsubscript"><strong>objectForKeyedSubscript</strong></a> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22cfd01d1c79f1e4ff65e3d94e19d4c1/href">https://medium.com/media/22cfd01d1c79f1e4ff65e3d94e19d4c1/href</a></iframe><h3>Functions</h3><p>In this article we check how to set the javascript environment, execute a script and pass from Swift to JavaScript and vice-versa. The <a href="https://medium.com/@sergioordine/javascript-and-swift-6c4c7ca43acf">next article</a> will talk about how to bridge Swift functions to be used within javascript and also how to call javascript functions from Swift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c59bf2317e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/academy-eldoradocps/javascript-and-swift-66c59bf2317e">Javascript and Swift</a> was originally published in <a href="https://medium.com/academy-eldoradocps">Academy@EldoradoCPS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Keras to CoreML]]></title>
            <link>https://medium.com/academy-eldoradocps/from-keras-to-coreml-eda99d6936be?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda99d6936be</guid>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 12:17:54 GMT</pubDate>
            <atom:updated>2020-08-06T18:33:04.418Z</atom:updated>
            <content:encoded><![CDATA[<h4>The journey of a Feed Forward Network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoJAFB4mDXMgNII96GfTFg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thematthoward?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Howard</a> on <a href="https://unsplash.com/s/photos/journey?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote><strong>&quot;Every mushrooms is edible, but some only once&quot; </strong>— Czech saying</blockquote><p>There are a lot of tutorials about how to create Feed Forward Networks in Keras, there are also a lot of tutorials on how to use convert an Image Classifier using convolutional network from Keras to CoreML using <a href="https://github.com/apple/coremltools">coremltools</a>. But unfortunately when trying to create a Feed Forward Network on Keras, convert it to CoreML and then use the resulting model on an iOS application I could not find a good reference. After gathering parts from here and there, it was possible to make it work. It was not difficult, but take a lot of effort to understand the steps and prepare the data properly on each step.</p><p>So, I thought it was a nice opportunity to share the experience and maybe remove some obstacles when someone needs to do the same with this tutorial.</p><p>We are going to use for this example a <a href="https://archive.ics.uci.edu/ml/datasets/Mushroom">mushroom identification dataset</a> to identify whether a given mushroom is edible or not based on 22 features.</p><p>This tutorial will be split into three main parts: how to create and train the model using Keras (and some supporting libraries to pre-process data), how to convert this to a CoreML model and finally how to import and use it on XCode to create an iOS app. Also, its code is available on <a href="https://github.com/sjordine/mushrooms">github</a>.</p><p>Let&#39;s <a href="https://medium.com/p/a9099585591a">start</a> by creating our FFN model using Keras.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda99d6936be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/academy-eldoradocps/from-keras-to-coreml-eda99d6936be">From Keras to CoreML</a> was originally published in <a href="https://medium.com/academy-eldoradocps">Academy@EldoradoCPS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PromiseKit]]></title>
            <link>https://medium.com/academy-eldoradocps/promisekit-2c8ca87fbcf9?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8ca87fbcf9</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[promisekit]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 20:52:23 GMT</pubDate>
            <atom:updated>2019-01-27T20:52:23.659Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make cleaner and clearer asynchronous code in Swift</h4><p>Promises are data structures that promise you a value of a given type <strong>when</strong> it is ready and let you handle this result. It makes easy to handle success and error as well as chaining and synchronizing asynchronous processes.</p><p>This is not a recent concept, as <em>promises</em> were proposed in 1976 by Daniel P. Friedman and David Wise. Similar concepts as <em>eventual</em> and <em>future</em> were proposed by Peter Hibbard also in 1976 and Henry Baker and Carl Hewitt in 1977. This concept is used in several concurrent programming languages.</p><p>There is a framework for promises in iOS called <a href="https://github.com/mxcl/PromiseKit">PromiseKit</a> that is very active and being developed since 2014.</p><h3>Why?</h3><p>Let&#39;s make a function that gets a single fact about cats using the <a href="https://catfact.ninja/">Cat Facts API</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/217390d25ce812ee74a4787d9610629c/href">https://medium.com/media/217390d25ce812ee74a4787d9610629c/href</a></iframe><p>And the call to this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/461c7d411f7a9f6705e7bcee8970d3e3/href">https://medium.com/media/461c7d411f7a9f6705e7bcee8970d3e3/href</a></iframe><p>We can see that there is a lot of error handling code mixed with our application logic (in this case, just parse the JSON) in the <strong><em>catFact</em></strong> function. The completion block also makes us deal with optional values for both the result and error and handle them with additional code in our control flow (the <strong><em>if-let</em></strong> statements). It generates many nested levels of code that makes hard to maintain and understand, what makes it sometimes be called &quot;pyramids of doom&quot;.</p><p>Let&#39;s check how the same code would be using PromiseKit (and a promise extension, that is part of PromiseKit, for <strong>URLSession</strong>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23f59523a464a13b2e325df3b3b497ae/href">https://medium.com/media/23f59523a464a13b2e325df3b3b497ae/href</a></iframe><p>And its is called as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20964b14f2f9c2583020a9f2edacb1fe/href">https://medium.com/media/20964b14f2f9c2583020a9f2edacb1fe/href</a></iframe><p>Comparing both codes we can see that the promise based code is shorter and has less error handling statements. It happens because errors are passed down the promise chain without the need of explicit code (as we did in the first example). Check also that we handle just <strong><em>data</em></strong> and <strong><em>response</em></strong> coming from the dataTask, not <strong><em>error</em></strong>.</p><p>Comparing also the call to catFact, we can see that the completion for success (under the <strong><em>done</em></strong> function) is logically separated from the error handling (under the <strong><em>catch</em></strong> function). It is said that when a promise finish executing (that is called as <em>resolved</em>), it can either success (when it is said that the promise is <em>fulfilled</em>) or being erred (when it is said that the promise was <em>rejected</em>).</p><p>A list of advantages of using promises is:</p><ul><li>It is easier and cleaner to chain asynchronous calls and its results;</li><li>Error handling is logically separated from the success data flow;</li><li>There is not need for <strong>Optionals</strong> to handle errors and values just because they could not be defined (due to the same flow handling error and success);</li><li>The characteristics above make us write less boilerplate code;</li><li>It usually generates a more concise, readable and clean code.</li></ul><p>In the <a href="https://medium.com/@sergioordine/promisekit-579bf51e67d2">next part of this article</a>, I will show how to create promises using PromiseKit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8ca87fbcf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/academy-eldoradocps/promisekit-2c8ca87fbcf9">PromiseKit</a> was originally published in <a href="https://medium.com/academy-eldoradocps">Academy@EldoradoCPS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monads]]></title>
            <link>https://sergioordine.medium.com/monads-3173aa57a2e1?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3173aa57a2e1</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Wed, 25 Jul 2018 14:39:05 GMT</pubDate>
            <atom:updated>2018-07-25T14:40:16.657Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical example</h4><p>To conclude my <a href="https://medium.com/@sergioordine/yet-another-monad-tutorial-b8b0d0b207df">monad series</a> of posts, here is a practical example that I hope helps to make thinks clearer. If you have not seen this post you can check it <a href="https://medium.com/@sergioordine/yet-another-monad-tutorial-b8b0d0b207df">here</a> and <a href="https://medium.com/@sergioordine/monads-examples-and-definitions-66906001c6f3">here</a>, or start by a specific post <a href="https://medium.com/@sergioordine/monads-da881e288eb9">here</a>.</p><p>The basic examples of monads in Swift are usually <a href="https://developer.apple.com/documentation/swift/array"><strong>Arrays</strong></a> and <a href="https://developer.apple.com/documentation/swift/optional"><strong>Optionals</strong></a>. I thought about using a different one: a way to isolate the boilerplate code we use for asynchronous calls in Swift, that I check after its development that are very close to the concept of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong>Promises</strong></a>…</p><p>A promise represents an eventual completion, or error, of an asynchronous operation. It represents exactly a promise of a value that does not exists or that has not been computed yet.</p><h3>Rationale</h3><p>The concepts used to implement it started thinking about the way we generally start an asynchronous call in Swift and how we handle it :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c64634a0bb3a2b7fa1a0dd7dd943f2/href">https://medium.com/media/71c64634a0bb3a2b7fa1a0dd7dd943f2/href</a></iframe><p>I just eliminated the error handling part of the code to make it more simple and focus on the idea, not the implementation.</p><p>We can think on a asynchronous call as a boilerplate code that starts another thread (using in this case the <a href="https://developer.apple.com/documentation/dispatch/dispatchqueue?changes=_1"><strong>DispatchQueue</strong></a> class), execute a lonk term task (<strong>doSomething</strong>) that returns a value. This value is delivered to the caller though a callback function (<strong>completionHandler</strong>). We can think on a generic type associated to a type <strong>T</strong> to handle this structure, with two functions: <strong>doSomething() → T</strong> and <strong>completionHandler(T)</strong>. Let&#39;s call this type <strong>Promise&lt;T&gt;, </strong>a promise to the calling code that a value of type<strong> T</strong> will be delivered to it, eventually, in the future.</p><p>This concept could be expanded to get the asynchronous return value and transform to something else before returning it. It could be used to reuse this code in a similar, but different context:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63be9a5b7ce35bf1822a0e9593fcb9de/href">https://medium.com/media/63be9a5b7ce35bf1822a0e9593fcb9de/href</a></iframe><p>We could think on a way to expand our generic type that would execute things asynchronously to transform a value and return a different type <strong>U</strong>. It is a strong candidate to have a <strong>map</strong> function <strong>map(T → U) → Promise&lt;U&gt;</strong>. We can think on making our <strong>Promise</strong> not just a generic type, but also a <a href="https://medium.com/@sergioordine/functors-d96f6b51594e"><em>Functor</em></a>!</p><p>More than that, we can execute an asynchronous code and, based on this result start another asynchronous call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903ae9150e593a4085c5e46f71c9a525/href">https://medium.com/media/903ae9150e593a4085c5e46f71c9a525/href</a></iframe><p>This code executes a long duration task on <strong>doSomethingAsynchronously</strong>, that returns a value o type <strong>T</strong>. Based on this value, the function <strong>transformToAsynchronous</strong> returns a new task function that can be executed on another asynchronous context (I used <strong>global</strong> on both just for simplicity). We can think on this function as something that converts <strong>T</strong> to a function with no parameters that returns something of type U: <strong>() → U</strong>. We could consider embedding this function into a <strong>Promise</strong>, as we did with <strong>doSomethingAsynchronously </strong>in the previous examples<strong>. </strong>So we can think on a function <strong>T → Promise&lt;U&gt;</strong> and a function that make this second <strong>Promise</strong> run as a result from the first one. This is a strong candidate for a function <strong>flatMap(T → Promise&lt;U&gt;) → Promise&lt;U&gt;</strong>. The <strong>Promise</strong> can be implemented as a <em>Monad</em> in this case!</p><h3>Implementation</h3><p>The first step is creating a class that holds the asynchronous call, the base code for <strong>Promise&lt;T&gt;</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfe5fb5438a6a10b9740ce03e32def74/href">https://medium.com/media/bfe5fb5438a6a10b9740ce03e32def74/href</a></iframe><p>The <strong>doSomething</strong> function was renamed to <strong>task</strong>, the long duration computation that will be executed asynchronously. It is a function with no parameters that returns a value of type <strong>T</strong>. The <strong>onCompletion</strong> function defines what should be executed when this computation finishes (the <strong>completionHandler</strong> function that receives this value <strong>T, </strong>and uses its).</p><p>The <strong>onCompletion</strong> is responsible for start the new thread, using the <strong>DispatchQueue.global</strong> queue, execute the <strong>task</strong> and returns its value to the <strong>completionHandler</strong> logic.</p><p>There are two initializers: one that receives the <strong>task</strong> to be executed and keeps it, and another that gets a <strong>value</strong> and just creates a <strong>task</strong> that returns it. This second initializer can be seen as &quot;puting the value into another thread&quot; and was implemented to represent the monad <strong>a → M(a)</strong> , the <a href="https://medium.com/@sergioordine/monoids-f2d1fdd86fe1">monoid &quot;identity/neutral&quot; element</a>.</p><p>The next step is creating the map function, to make <strong>Promise</strong> a <a href="https://medium.com/@sergioordine/monoids-f2d1fdd86fe1"><em>functor</em></a>. We must remember that on the Promise context, the value is not yet presented when we call the map function, so we need to postpone the transformation to the moment when the <strong>onCompletion</strong> function is called. In a similar way that RxSwift works, let’s create another object Promise to keep the original task and transform it when the value is received:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/759876fea3d5cdd71d20396453a52c8c/href">https://medium.com/media/759876fea3d5cdd71d20396453a52c8c/href</a></iframe><p>This <strong>PromiseMap</strong> is a class inherited from <strong>Promise&lt;Destination&gt;</strong> type that holds the original promise and the transformation to be performed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc16ad58b7c25def8c13055e5667f791/href">https://medium.com/media/dc16ad58b7c25def8c13055e5667f791/href</a></iframe><p>The override function <strong>onCompletion</strong> of this promise calls the original one and passes to that original promise a <strong>completionHandler</strong> that transforms its returned value into a new one (of <strong>Destination</strong> type), using the <strong>transform</strong> function and then, calls the <strong>completionHandler</strong>.</p><p>As the map function returns a new Promise object, we can think as the original promise <strong>onCompletion</strong> is not exposed anymore to the calling code (just the onCompletion of the mapped one):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ed755c5a5a7482e62b646b03bfb273/href">https://medium.com/media/48ed755c5a5a7482e62b646b03bfb273/href</a></iframe><p>That is why we can &quot;hijack&quot; the original promise <strong>onCompletion</strong> and create an internal <strong>completionHandler</strong> as we did. It fires the original task into a new thread and, in that same thread transform the object and returns it to the exposed <strong>completionHandler</strong>(of the second promise)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*p4UU5pczXUUDTsevBY3htg.jpeg" /><figcaption>Diagram of PromiseMap</figcaption></figure><p>Finally, we need to implement the flat map method, that will chain two distinct Promises:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63151d580d2b90f3f3cc0682ba9582c4/href">https://medium.com/media/63151d580d2b90f3f3cc0682ba9582c4/href</a></iframe><p>This function transform the original promise into a promise of type <strong>Promise&lt;Promise&lt;Destination&gt;&gt;</strong>, using the <strong>map</strong> function. We need to &quot;<a href="https://medium.com/@sergioordine/flat-it-f7ac62d439a9">flat</a>&quot; it in order to make it just a<strong> Promise&lt;Destination&gt;</strong>. In a similar way we did with map we also need to postpone this, because the inner <strong>Promise&lt;Destination&gt;</strong> will be available just after the original promise executes and the transformation is performed. <em>Flat</em> in this case means wait the execution of the first promise, create a new <strong>Promise&lt;Destination&gt;</strong> from its result and call <strong>asynchronously</strong> it. That flattening will be performed by the <strong>NestedPromise</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd2fcdeb5a315073e6af8314b9eff0a/href">https://medium.com/media/9bd2fcdeb5a315073e6af8314b9eff0a/href</a></iframe><p>This class keeps the nested promises when <strong>flatMap</strong> is called over the mapped one (<strong>Promise&lt;Promise&lt;T&gt;&gt;</strong>). When its <strong>onCompletion</strong> is called, it calls the mapped promise <strong>onCompletion</strong> (it hijacks it, in the same way the <strong>PromiseMap</strong> did with the original Promise). The completion handler receive the <strong>Promise&lt;T&gt; </strong>created from the original result. We can then pass the <strong>completionHandler</strong> the external code send to <strong>NestedPromise</strong> to this &quot;inner&quot; promise as both handles a value of type <strong>T</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*DMlYl73fopNGbGzRMNcbKw.jpeg" /><figcaption>Diagram of NestedPromise</figcaption></figure><h3><strong>Using Promise</strong></h3><p>The following sample present the usage of <strong>Promise</strong> and its <strong>map</strong> and <strong>flatMap</strong> functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acd3a9650fb5943fa0a367db89ef3a7c/href">https://medium.com/media/acd3a9650fb5943fa0a367db89ef3a7c/href</a></iframe><p>We start by a Promise (<strong>nasaURL</strong>) that just put a string, representing and URL of a REST API, into a asynchronous thread. This API returns information about a astronomy related photo from NASA that changes on a daily basis.</p><p>The <strong>nasaURL</strong> promise calls it <strong>map</strong> function, passing the <strong>imageURL</strong> function. The <strong>imageURL</strong> function accesses the API, parses the returned JSON and gets an specific data within it (<strong>hdurl </strong>field) that represents another URL, from a high definition image itself.</p><p>This image is then recovered asynchronously by the promise created by <strong>downloadImage</strong> function. This function is chained to the previous one using the <strong>flatMap</strong>. The onCompletion block that follow is executed after all this steps: recovering the JSON, parsing it and retrieving the image.</p><p>Notice that all code that handles the asynchronous calls is hidden on this code, as it is all handled by the promises. So, this technicality is not presented on this code, making the application logic (that is: retrieve the image) more evident.</p><p>We could even create custom operators to make the chain more explicit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7101376f5dcf21fe3ab8ef1a501159/href">https://medium.com/media/3e7101376f5dcf21fe3ab8ef1a501159/href</a></iframe><p>Using those operators, the application logic could be represented as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81752268a362b0eefe80058e9a44b2de/href">https://medium.com/media/81752268a362b0eefe80058e9a44b2de/href</a></iframe><p>This tutorial is an example on how we can isolate boilerplate code using generics, and its specialization as functors and monads for chaining functions hiding some of the computational and technological complexity not directly related to the logic we are implementing.</p><p><strong>PS</strong>: This is a very basic implementation of a <strong>Promise</strong>, made just for exemplify a monad different from the usual ones in Swift. It does not handle errors, allows choosing the queue or thread where the task is performed (and we need at least to run it on the <strong>main</strong> thread for UI tasks) between other limitations. Those features should be implemented in order to make it useful in a real world project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3173aa57a2e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monads]]></title>
            <link>https://sergioordine.medium.com/monads-da881e288eb9?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/da881e288eb9</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Mon, 23 Jul 2018 22:00:49 GMT</pubDate>
            <atom:updated>2018-07-23T22:03:49.903Z</atom:updated>
            <content:encoded><![CDATA[<h4>Table of Contents</h4><h4><strong>Introduction</strong></h4><p><a href="https://medium.com/@sergioordine/yet-another-monad-tutorial-b8b0d0b207df">Yet another Monad tutorial — for Swift programmers</a></p><p><a href="https://medium.com/@sergioordine/monads-examples-and-definitions-66906001c6f3">Monads — Example and Definitions</a></p><h4>Introduction to Category Theory</h4><p><a href="https://medium.com/@sergioordine/category-bd96f6efa0e5">Category</a></p><p><a href="https://medium.com/@sergioordine/when-types-are-not-enough-e66078f45c15">When types are not enough</a></p><h4>Functors</h4><p><a href="https://medium.com/@sergioordine/functors-d96f6b51594e">Functors</a></p><p><a href="https://medium.com/@sergioordine/x-raying-the-map-1e22c3b7ca6f">X-raying the map</a></p><p><a href="https://medium.com/@sergioordine/functors-usage-and-limitations-7a1d6416bdd0">Functors — usage and limitations</a></p><h4>Monoids</h4><p><a href="https://medium.com/@sergioordine/monoids-f2d1fdd86fe1">Monoids</a></p><h4>Endofunctors</h4><p><a href="https://medium.com/@sergioordine/endofunctors-dcfe5ee06d2b">Endofunctors</a></p><p><a href="https://medium.com/@sergioordine/natural-transformations-9b7a1ab6c35b">Natural transformations</a></p><h4>Concepts about Monads</h4><p><a href="https://medium.com/@sergioordine/putting-the-pieces-together-7b93a23438c9">Putting the pieces together</a></p><p><a href="https://medium.com/p/b9d8858eaf38/edit">X-raying flat map</a></p><p><a href="https://medium.com/@sergioordine/flat-it-f7ac62d439a9">Flat it!</a></p><p><a href="https://medium.com/p/f9471563b315/edit">Flat</a></p><h4>Conclusion</h4><p><a href="https://medium.com/@sergioordine/a-discussion-about-monads-d58826600433">A discussion about monads</a></p><p><a href="https://medium.com/@sergioordine/monads-in-the-wild-9365036dfa9e">Monads in the wild</a></p><p><a href="https://medium.com/@sergioordine/monads-as-programmable-semicolons-7318f6974a51">Monads as &quot;programmable semicolons&quot;</a></p><p><a href="https://medium.com/@sergioordine/monads-conclusion-1c41d34e63a3">Monads — Conclusion</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da881e288eb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monads — Examples and Definitions]]></title>
            <link>https://sergioordine.medium.com/monads-examples-and-definitions-66906001c6f3?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/66906001c6f3</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Tue, 10 Jul 2018 18:42:13 GMT</pubDate>
            <atom:updated>2018-07-23T22:13:23.659Z</atom:updated>
            <content:encoded><![CDATA[<h4>Examples</h4><p>We, Swift programmers, are in touch and use some monads without even know that they are classified as such: <a href="https://developer.apple.com/documentation/swift/array">Arrays</a> (as well as all other <a href="https://developer.apple.com/documentation/swift/sequence">Sequences</a>) and <a href="https://developer.apple.com/documentation/swift/optional">Optionals</a> are both valid examples for this statement.</p><p>There are also frameworks that implement other monads: <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a>, a reactive programming framework implements <a href="http://reactivex.io/documentation/subject.html">Subjects</a> (objects that can be observed and observe at the same time) as those.</p><p>They are even more useful in pure functional languages in order to deal specially with controlled side-effects. Chris Smith in this <a href="https://cdsmith.wordpress.com/2012/04/18/why-do-monads-matter/">post</a> describe four very important of them, the &quot;Four Horsemen of Catapocalypse&quot;:</p><ul><li><strong>Failure</strong> — a function can result in an error due to lack of memory, an invalid human input, a network interruption etc.;</li><li><strong>Dependence</strong> — from one function call to the next one, as stateful operations;</li><li><strong>Uncertainty</strong> — different results from the same parameters;</li><li><strong>Destruction</strong> — actions that have permanent effects on the world, such as I/O.</li></ul><p>We can find <a href="http://adit.io/posts/2013-06-10-three-useful-monads.html">other monads</a> in those languages to control State, Logging (the Writer monad), IO and others effects.</p><p>The metaphor of monads as containers/boxes becomes harder to fit when considering those examples. I think it brings a implicit notion of structure that kind of encompasses Arrays and Optionals very well, but needs to be stretched and revisited in order to hold the other ones.</p><p>Looking the examples and start from it seemed to me something that confuses the learner into building the concept (and even the purpose) of monads. On the other hand, it is very important to understand one of its major usages: define a common way to handle additional computations and side-effects in a uniform and controlled manner.</p><h4>Purpose</h4><p>I think it is important, before jump to the definitions and concepts, to say that the purpose of monads on the functional programming is to allow composing functions that have a return value type to another function that expect a different type as parameter. Nevertheless, it is not intended to match every return to any parameter type: monads work over <strong>some</strong> generic types returned by a function to compose them with functions that expect its associated type as a parameter (ex: to connect an <strong>Array&lt;Int&gt;</strong> returned by a function to function that expects an integer, like <strong>f(Int)</strong>).</p><p>Monads have several uses, but their general purpose (at least from a programming point of view) is to connect things.</p><h4>Definitions</h4><p>As examples just partially support the concept understanding, let&#39;s move to another approach: from the definition point of view on.</p><p>Monads, on programming language are generic types (e.g: Array&lt;T&gt;) what means it is associated to any type T (like <strong>Int</strong>, <strong>String</strong> etc.) or at least to a set of types with some constraints (like <a href="https://developer.apple.com/documentation/swift/dictionary"><strong>Dictionaries</strong></a>, that holds key-value pairs: they can hold any type as values, but keys are constrained to types that conforms to the <a href="https://developer.apple.com/documentation/swift/hashable"><strong>Hashable</strong></a> protocol).</p><p>Besides being a generic type, monads should implement two functionalities:</p><ul><li><strong>An unit function</strong> — a <em>type constructor</em> for the monad type <em>M</em> that receives a value from the associated type <em>a</em> and turn it into the generic type with a minimum context <em>M(a)</em> — What &quot;being in the minimum context&quot; means depends on the type itself. For an array, receiving a value, like the integer <strong>1</strong>, it should be creating an integer array with just one element <strong>[1]</strong>; for an optional, receiving a string <strong>&quot;Hello!&quot;</strong> should be creating an <strong>Optional&lt;String&gt;</strong> with value <strong>.some(&quot;Hello!&quot;)</strong>. This could be extended to any other monad type.</li><li><strong>A flat map function</strong> — this function is a high-order function (meaning: it receives another function as a parameter) implemented for every instance of the monad <em>M</em> with associated type <em>a.</em> It receives as a parameter a function that converts a value of type a to another monad of the same type <em>M</em>, but that can have <strong>another</strong> associated type <em>b</em>. The flat map function shall return a monad of type <em>M(b)</em>. We can define this function as <strong>M(a).flatMap(a → M(b)) → M(b) </strong>or <strong>flatMap(M(a)</strong>, <strong>a → M(b)) → M(b) </strong>(choose the one that is clearer to you)<strong>. </strong>The flat map function is also called <strong>bind function</strong> in some programming languages (such as Haskell).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Q5TXD_yBPSNPu8Ii1fpXLw.png" /><figcaption>Schematic representation of a monad type <em>M</em></figcaption></figure><p>The definition is, as discussed before, simple (not a complex one), but not bring much more information to understand monads.</p><p>As the next step I&#39;ll try is use a more &quot;formal&quot; definition of monads:</p><blockquote>&quot;<strong>Monads are monoids in the category of endofunctors</strong>&quot;.</blockquote><p>What?!!?!?! 😮😧😱</p><p>As akward as it can be, this definition was fundamental to help me understand the concept. So, my next posts will break down the concepts present on this obscure definition and try to show how they are used, whenever possible, within our code. They will not be precise, mathematically speaking (as I lack the background to do so and maybe for us developers it would not add much support), but I hope they at least take you a step further on understanding monads from a programming point of view.</p><p>Let&#39;s start with the <a href="https://medium.com/@sergioordine/category-bd96f6efa0e5">category</a> part of “Monads are monoids in the <a href="https://medium.com/@sergioordine/category-bd96f6efa0e5">category</a> of endofunctors”.</p><p><strong>Note:</strong> If you want to navigate to a specific post, <a href="https://medium.com/@sergioordine/monads-da881e288eb9">here</a> is a list of all monad <a href="https://medium.com/@sergioordine/monads-da881e288eb9">related ones</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66906001c6f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yet another Monad tutorial]]></title>
            <link>https://medium.com/academy-eldoradocps/yet-another-monad-tutorial-b8b0d0b207df?source=rss-3a619bb5d25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b0d0b207df</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sergio Ordine]]></dc:creator>
            <pubDate>Tue, 10 Jul 2018 18:41:06 GMT</pubDate>
            <atom:updated>2019-08-20T16:47:44.190Z</atom:updated>
            <content:encoded><![CDATA[<h4>for Swift programmers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pJh7hL9lUfBUW6Dr2YKSjg.jpeg" /><figcaption>Photo by <a href="https://www.flickr.com/photos/peptic_ulcer/8005951331">Jeff</a> — CC BY-SA 2.0</figcaption></figure><h4>Introduction</h4><p>Functors and monads are concepts that everyone who starts studying functional programming, sooner or later, gets in touch and usually has a hard time struggling with them.</p><p>Monad is a simple concept: it has a concise and direct definition. On the other hand, this definition is based on several layers of abstraction, what makes it hard to grasp. We can consider that monads are simple (in contrast to complex), but learning monads is usually difficult (in contrast to easy) for most people. To understand its full application and generality is one of the most hard things about it.</p><p>This could be a possible explanation why there is a myriad of monad tutorials around. After building a mental model to deal with these abstractions and get a good understanding about the concept itself, usually people try to make the process more palatable to newcomers, making writing a tutorial almost a cathartic &quot;rite of passage&quot;.</p><p>I think it could not be different to me, so here we go. My focus on the series of post that follows is to write thinking on the pitfalls I found along the way. I hope it will make this tutorial different from, at least, some of the ones already in the available in the following terms:</p><ul><li>I&#39;ll try to make the tutorial as practical as possible, exploring the concepts but trying to bring it to some practical (understand it as: code). Bringing it to this realm, that is more clear to us as programmers, helped me and I also hope that can help others.</li><li>Several monad explanations try to use metaphors to make it less abstract. On those metaphors the monad is represented as a design pattern, a container or box, a <a href="https://blog.plover.com/prog/burritos.html">burrito</a>, a duck tape or a &quot;<a href="https://zacharyvoase.com/2014/04/30/monads/">programmable semicolon</a>&quot;. Although all of them can model parts of what a monad is, there is a lot of concepts and abstractions that do not fit or demands some kind of adjustment in order to hold. That&#39;s why James Iry says that monads are like <a href="http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html">elephants</a> (using the parable of the blind men and the elephant): you can have some intuition or understand parts of the concept but seeing just the details make you miss the whole picture. Somehow, I agree with <a href="https://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/">Brent Yorgey</a> about that there is a fallacy on trying to fit the concept into metaphors, as it minimizes that the struggle with the abstraction is part of the understanding process. Therefore I&#39;ll try to focus on the concepts and not on the metaphors, but I will try to use them to point out some of the pitfalls on my learning process related to this metaphors (the points I consider they made more difficult to me to generalize the concept).</li><li>This tutorial is split into (a lot of!) small posts according to concepts and examples. I hope it makes it easy to follow and also to skip parts that are already known.</li><li>The vast majority of monad tutorials use Haskell to exemplify things. Haskell is a pure functional language with a very distinct syntax from the imperative and OO languages most programmers are used to. So trying to read them make two challenges instead of one: understand the concept and the language itself. It was fundamental for my studies to have found this <a href="https://w.pitula.me/2016/monad-proof/">Scala tutorial</a>. Scala is a multi-paradigm language that, although having powerfull constructs, is easier to be read than Haskell (at least for me). I will use Swift, also a multi-paradigm language, for this tutorial but I think it could be easily translated to other multi-paradigm languages as well.</li></ul><h4>What do I need to bring?</h4><p>I&#39;ll focus on the monad concept and the building blocks for its understanding. There are some former knowledge that I&#39;ll not focus but are extremelly important:</p><ul><li><strong>Swift</strong> — The code samples were made using the <a href="https://swift.org/">Swift</a> language, so the knowledge of this language is important, although I think it could be easily mapped to other programming languages as C#, Java, Kotlin etc.</li><li><strong>Generics</strong> — Generic types are the base for monads. It is important to understand both the concept and its syntax in order to understand the examples and code on this tutorial.</li><li><strong>Functional Programming</strong> — Monads are constructions associated with the functional programming paradigm, so it is important to understand it to get the purpose of the monad and its usage. There are two concepts that are central to this tutorial: function composition and that functions are &quot;first class citizens&quot; on functional programming (they are types and they are like any other type being possible to attributed them to a variable, to pass them as parameters to another function or being returned as a result for a function call).</li></ul><p>All it said, and hoping I could at least in part get rid of the &quot;monad curse&quot; (when someone is finally able to understand it, he becomes unable to explain it to any other person 😀), let&#39;s get <a href="https://medium.com/@sergioordine/monads-examples-and-definitions-66906001c6f3">started here</a>. If you want to go to a specific post, <a href="https://medium.com/@sergioordine/monads-da881e288eb9">here</a> is a list of all monad <a href="https://medium.com/@sergioordine/monads-da881e288eb9">related ones</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b0d0b207df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/academy-eldoradocps/yet-another-monad-tutorial-b8b0d0b207df">Yet another Monad tutorial</a> was originally published in <a href="https://medium.com/academy-eldoradocps">Academy@EldoradoCPS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>