<?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 Tyrone Michael Avnit on Medium]]></title>
        <description><![CDATA[Stories by Tyrone Michael Avnit on Medium]]></description>
        <link>https://medium.com/@tyronemichael?source=rss-b8d3b73a33bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qDpJVBCiv60xb3FSSUE7Yw.jpeg</url>
            <title>Stories by Tyrone Michael Avnit on Medium</title>
            <link>https://medium.com/@tyronemichael?source=rss-b8d3b73a33bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:51:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tyronemichael/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[Implementing Foldable, Map and FlatMap]]></title>
            <link>https://medium.com/@tyronemichael/foldable-map-and-flatmap-416dbd5ace36?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/416dbd5ace36</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 15:08:10 GMT</pubDate>
            <atom:updated>2019-12-30T00:10:56.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-SSuz0qwgdHBrEJIZwtng.png" /><figcaption>Thanks to <a href="https://lukaszadam.com/illustrations">Lukas</a> for the illustration</figcaption></figure><p>I have been spending a good portion of my time studying <a href="https://en.wikipedia.org/wiki/Structure_and_Interpretation_of_Computer_Programs">SICP</a>. SICP avoids focusing on the terms such as Functor (<strong>Map</strong>) and Monad (<strong>FlatMap</strong>) and instead focuses solely on their implementations and the power they provide us.</p><p>You can find all the code below in the following playground:</p><p><a href="https://github.com/TYRONEMICHAEL/foldableMapFlatMap">TYRONEMICHAEL/foldableMapFlatMap</a></p><p>The implementations are surprisingly simple. Look at the implementation of Optional’s <strong>Map</strong> in Swift’s very own source code.</p><pre>public func map&lt;U&gt;(<br>    _ transform: (Wrapped) throws -&gt; U) rethrows -&gt; U? {    <br>    switch self {    <br>    case .some(let y):      <br>        return .some(try transform(y))    <br>    case .none:      <br>        return .none    <br>    }  <br>}</pre><p>Most developers I know make heavy use of <strong>Map</strong> and <strong>FlatMap</strong>. I do think it is of utmost importance to understand their implementations in order to understand how they actually work across different Types. <em>As an exercise try code Array’s implementation of </em><strong><em>Map</em></strong><em> and </em><strong><em>FlatMap</em></strong><em> before reading further.</em></p><p>In order to implement <strong>FlatMap</strong>, we will use two functions as building blocks, reduce (sometimes referred to as <strong>Accumulate</strong> or <strong>FoldRight</strong>) and <strong>Map</strong>. So let’s implement reduce first.</p><pre>func reduce&lt;A, B&gt;(<br>    _ fn: (A, B) -&gt; B, _ initial: B, _ list: [A]) -&gt; B {<br>    guard let value = list.first else {<br>       return initial<br>    }<br>    <br>    return fn(value, reduce(fn, initial, Array(list.dropFirst(1))))<br>}</pre><p>The above function is recursive. It executes in the following way:</p><pre>let sum: (Int, Int) -&gt; Int = { a, b in a + b }<br>reduce(sum, 0, [1, 2, 3])</pre><pre>// return fn(value, reduce(fn, initial, Array(list.dropFirst(1))))<br>// fn(1, fn(2, fn(3, 0)))<br>// fn(1, fn(2, 3))<br>// fn(1, 5)<br>// 6</pre><p>Now you can see why it is sometimes referred to as <strong>FoldRight. </strong>It executes from right to left. If we want to write an implementation for <strong>FoldLeft, </strong>we can write the same function iteratively.</p><pre>func foldLeft&lt;A, B&gt;(<br>    _ fn: (A, B) -&gt; B, _ initial: B, _ list: [A]) -&gt; B {<br>    <br>    func iter(_ fn: (A, B) -&gt; B, _ result: B, _ list: [A]) -&gt; B {<br>        guard let value = list.first else {<br>           return result<br>        }</pre><pre>        return iter(fn, fn(value, result), Array(list.dropFirst(1)))<br>    }<br>    <br>    return iter(fn, initial, list)<br>}</pre><p>Now let’s implement <strong>Map</strong>.</p><pre>func map&lt;A, B&gt;(_ fn: (A) -&gt; B, _ list: [A]) -&gt; [B] {<br>    guard let value = list.first else {<br>        return []<br>    }<br>    <br>    return [fn(value)] + map(fn, dropFirst(list))<br>}</pre><p>Pretty simple. Do you see the correlation between Optional’s implementation and the Array’s implementation? Both unwrap the value and pass it to the function, take the result produced by the function, and finally wrap the altered value back up in its corresponding type: <strong>.some(fn(value))</strong> &amp; <strong>[fn(value)]</strong>. If you look at any other Type’s implementation of <strong>Map</strong>, you will find the exact same thing <strong>SomeType(fn(value))</strong>.</p><p>Now let’s implement the final function, <strong>FlatMap</strong>. The simplest of the three, but the most dense.</p><pre>func flatMap&lt;A, B&gt;(_ fn: (A) -&gt; [B], _ list: [A]) -&gt; [B] {<br>    return foldRight(+, [], map(fn, list))<br>}</pre><pre>let square: (Int) -&gt; [Int] = { x in [x * x] } </pre><pre>map(square, [1, 2, 3]) // [[1], [4], [9]]<br>flatMap(square, [1, 2, 3]) // [1, 4, 9]</pre><p>Spend time thinking about how the above using both <strong>FoldRight</strong> (the reduce method we implemented in the beginning) and <strong>Map</strong> produces the correct result.</p><p>The above is exactly why functional programming, to me, is so powerful. The combination of <strong>FoldRight</strong> and <strong>Map</strong> to produce <strong>FlatMap</strong> is pure elegance.</p><p><strong>FlatMap</strong> just takes the value and unlike <strong>Map</strong>, does not re-wrap the value in its corresponding type. That’s it. So if you have a nested type you solve it with the following use of <strong>FlatMap:</strong></p><pre>let value = Optional.some(Optional.some(5))<br>print(value.flatMap { $0 }) // Optional.some(5)</pre><p>The main inspiration for the article came from the following problem introduced to me in SICP, and is a fitting conclusion:</p><blockquote>Suppose we wish to generate all the permutations of a set S; that is, all the ways of ordering the items in the set. For instance, the permutations [1, 2, 3] are [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3 1], [3, 1, 2], [3, 2, 1].</blockquote><p>We can solve the problem using only <strong>FlatMap</strong> and <strong>Map</strong> (no loops or assignment). Something that took me quite some time to wrap my head around and I hope that it inspires you the same way it did me.</p><pre>func remove&lt;A: Equatable&gt;(_ a: A, _ arr: [A]) -&gt; [A] {<br>    return arr.filter { x in a != x }<br>}</pre><pre>func permutations(_ list: [Int]) -&gt; [[Int]] {<br>    if list.isEmpty {<br>        return [[]]<br>    }</pre><pre>    return flatMap({ x in<br>        return map({ y in<br>            [x] + y<br>        }, permutations(remove(x, list)))<br>    }, list)<br>}</pre><pre>permutations([1, 2, 3])<br>// <strong>[<br>//  [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]<br>// ]</strong></pre><p>If you enjoyed this article, please get in touch with me below:</p><p><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></p><p>All the code above can be found here:</p><p><a href="https://github.com/TYRONEMICHAEL/foldableMapFlatMap">TYRONEMICHAEL/foldableMapFlatMap</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=416dbd5ace36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containing side-effects with the IO Functor]]></title>
            <link>https://medium.com/swlh/containing-side-effects-with-the-io-functor-4013f34c8123?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4013f34c8123</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Fri, 14 Jun 2019 12:22:34 GMT</pubDate>
            <atom:updated>2019-06-25T05:07:56.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkArXaFlk94cAlO3DUNZ3g.jpeg" /></figure><h3>Containing side-effects with the IO functor</h3><p>I have been reading <a href="https://github.com/MostlyAdequate/mostly-adequate-guide">Professor Frisby’s Mostly adequate guide to Functional Programming</a>. A great read, and a book I would certainly recommend. One issue the author highlights is how do we deal with side-effects effectively. Most software engineers are familiar with functors such as <a href="https://medium.com/javascript-scene/functors-categories-61e031bac53f">Arrays, Optionals, Results, and Promises</a>. There exists another type designed with the intent to deal with side effects. This is the IO type.</p><p>You can find all the code for the article in the following playground file.</p><p><a href="https://github.com/TYRONEMICHAEL/io-type-swift">TYRONEMICHAEL/io-type-swift</a></p><p>First let’s take a look at an example of an impure function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Moy03CmXAHVOtIzHRkijjQ.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><p>Nothing in the function signature indicates that this is indeed a function which has a side-effect. But we can make the function pure by simply making a minor change to the function signature, (Int) -&gt; () -&gt; String?, and updating the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeU4GArzLE2auHRRwoz6cA.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><p>Had we not surrounded the the function in a closure, getFromStorage’s output would be dependant on external circumstances. The very definition of a non-pure function. With the closure in place, we will always get the same output based on our input (another function that accepts an <strong>Int</strong> and returns a <strong>String</strong>).</p><p>That solves one issue, but is still not very useful to us. This, however, is where we can make use of the IO type. Below is a simple implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxYOHLgsU2I44Ojy37Pv6w.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><p>And our implementation of compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEAMk1WAbXxlHh2jO9iwwA.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><blockquote>“IO differs from the previous functors in that the <strong>value</strong> is always a function. We don’t think of its <strong>value</strong> as a function, however — that is an implementation detail and we best ignore it. What is happening is exactly what we saw with the getFromStorage example: IO delays the impure action by capturing it in a function wrapper. As such, we think of IO as containing the return value of the wrapped action and not the wrapper itself.” Excerpt From: Mostly Adequate. “mostly-adequate-guide”. Apple Books.</blockquote><p>I think this is best demonstrated with examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szuEKeV8AEifjhmtP_oZig.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><p>We just defined our in-memory storage and some pure functions that will be used to manipulate our stored value. Our storage can easily be changed to an external storage as long as the function has the same signature. Did someone ever say <a href="https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a">mocks are code smell</a>? No need to define complicated interfaces. Our function signature is our interface. If you would like to know more, I would suggest the <a href="https://www.youtube.com/watch?v=srQt1NAHYC0">following video</a> on functional design patterns. However, now let’s construct our IO type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ey8XWKSQ1dmy1FaJCZbLBw.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><p>Now our IO type has the signature () -&gt; String which means we have not done any of the transformations yet. We have taken the following:</p><pre>(Int) -&gt; (String?) -&gt; (String?) -&gt; (String?) -&gt; (String?) -&gt; String?</pre><p>And compressed it into:</p><pre>() -&gt; String?</pre><p>Once we call the execute method on the IO type, we compute the result by actually executing the side-effect and all the transformations finally take place. Think of it like pulling the pin from a grenade.</p><blockquote>“Our mapped functions do not run, they get tacked on the end of a computation we’re building up, function by function, like carefully placing dominoes that we don’t dare tip over. The result is reminiscent of Gang of Four’s command pattern or a queue.” Excerpt From: Mostly Adequate. “mostly-adequate-guide”. Apple Books.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8q4SxiMnLlCPYOYXCBn5CA.png" /><figcaption><a href="https://github.com/TYRONEMICHAEL/io-type-swift">https://github.com/TYRONEMICHAEL/io-type-swift</a></figcaption></figure><p><strong>So like the guys at Point Free like to say “What is the Point”?</strong></p><p>Before we answer the question above, lets have a look at the types we are familiar with and the purposes they serve:</p><p><strong>Optional Type</strong></p><blockquote>In programming languages (more so functional programming languages) and <strong>type</strong>theory, an <strong>option type</strong> or maybe <strong>type</strong> is a polymorphic <strong>type</strong> that represents encapsulation of an <strong>optional</strong> value; e.g., it is used as the return <strong>type</strong> of functions which may or may not return a meaningful value when they are applied. <a href="https://en.wikipedia.org/wiki/Option_type">https://en.wikipedia.org/wiki/Option_type</a></blockquote><p><strong>Result Type</strong></p><blockquote>Provides an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the programmer is forced to consider success or failure paths, before getting access to the expected result; this eliminates the possibility of an erroneous programmer assumption. <a href="https://en.wikipedia.org/wiki/Result_type">https://en.wikipedia.org/wiki/Result_type</a></blockquote><p><strong>Promise Type</strong></p><blockquote>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, <strong>future</strong>, <strong>promise</strong>, <strong>delay</strong>, and <strong>deferred</strong> refer to constructs used for <a href="https://en.wikipedia.org/wiki/Synchronization_(computer_science)">synchronizing</a> program <a href="https://en.wikipedia.org/wiki/Execution_(computing)">execution</a> in some <a href="https://en.wikipedia.org/wiki/Concurrent_programming_language">concurrent programming languages</a>. They describe an object that acts as a proxy for a result that is initially unknown, usually because the <a href="https://en.wikipedia.org/wiki/Computation">computation</a> of its value is not yet complete. <a href="https://en.wikipedia.org/wiki/Futures_and_promises">https://en.wikipedia.org/wiki/Futures_and_promises</a></blockquote><p><strong>IO Type</strong></p><p>Finally our IO type is indicative of a contained side-effect. Since we cannot safely assume a function has a side-effect by just looking at the function signature, we absolutely know by the type being returned. This helps us write more maintainable code with code that is easier to test. We can also identify and push our side-effects to the end of our architectural boundaries.</p><blockquote>“At any rate, we can finally play with impure values without sacrificing our precious purity.” Excerpt From: Mostly Adequate. “mostly-adequate-guide”. Apple Books.</blockquote><p>You can find the implementation of the above in the following playground file:</p><p><a href="https://github.com/TYRONEMICHAEL/io-type-swift">TYRONEMICHAEL/io-type-swift</a></p><p>If you enjoyed the article tweet to me please as it encourages me to write more.</p><p><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4013f34c8123" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/containing-side-effects-with-the-io-functor-4013f34c8123">Containing side-effects with the IO Functor</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending your modules using a plugin architecture]]></title>
            <link>https://medium.com/@tyronemichael/extending-your-modules-using-a-plugin-architecture-c1972735d728?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1972735d728</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Sat, 12 May 2018 12:40:52 GMT</pubDate>
            <atom:updated>2018-05-31T22:52:26.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTw2EgvXDUnkibHBC1kduw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/sBvK15KlpYk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Genessa Panainte</a> — What comes to mind when thinking of the <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe pattern</a></figcaption></figure><p>Breaking your app up into modules has many benefits and it is extremely easy to achieve with Xcode using workspaces or Cocoapods. Whether you are working with feature teams or you have a set of reusable modules shared between different applications, one of the design decisions you will need to make is how to communicate between the various modules.</p><p>I have never been a fan of using a <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe pattern</a> because <a href="https://objcsharp.wordpress.com/2013/08/28/why-nsnotificationcenter-is-bad/">completely decoupled events are harder to trace, debug, and maintain</a>. When our architect suggested using a plugin architecture and having worked with Wordpress earlier in my career, I became quite excited. <a href="https://developer.wordpress.org/plugins/intro/">Wordpress</a> uses a plugin architecture successfully, which allows for extending functionality of Wordpress without touching the Wordpress core itself.</p><p>As an example, Wordpress allows you to hook into the &lt;head&gt;&lt;/head&gt; section of a HTML document using the <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head">wp_head()</a> hook. This allows any Wordpress plugin or theme to insert their own custom Javascript or CSS. We can take inspiration from this and extend our own modules using a similar philosophy.</p><p>This architecture is extremely easy to implement and I have developed a Playground example in the following repository:</p><p><a href="https://github.com/TYRONEMICHAEL/plugin-architecture-swift">TYRONEMICHAEL/plugin-architecture-swift</a></p><h3>An overview</h3><p>A typical application might be broken down into the following modules depending on the different domains:</p><ul><li>Login module</li><li>User profile module</li><li>Data storage module</li><li>User feed module</li><li>and so forth…</li></ul><p>Separating an app into modules allows for different teams to work in isolation. You might even have a set of modules you would like to reuse between your various applications that can expose functionality so your other modules can hook into, extend, or react to certain conditions.</p><p>A simple example might be to fetch the user’s profile, store the data returned during a login, and fetch the user’s feed. We can do that as soon as the user logs in by fetching all the data we need up front. We will develop and extend a Login module to allow other modules to plug into it as soon as there has been a successful or failed login. We can take inspiration from the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*Y8wcATWoh1gnk0xPRvCpFQ.png" /></figure><h3>Creating the Login Module</h3><p>After creating the Login Module inside of our workspace, we will create a very <em>useful </em>class that lets us authenticate successfully and authenticate unsuccessfully.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21c784997edd3b65d36d0c9abdd44eb3/href">https://medium.com/media/21c784997edd3b65d36d0c9abdd44eb3/href</a></iframe><p>Now let’s create two public interfaces that any of our modules can conform to in order to plug into our Login Module. We will start off by first creating the protocol for a successful login.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe0d55677bcd8395ec0e24aa7eec93f1/href">https://medium.com/media/fe0d55677bcd8395ec0e24aa7eec93f1/href</a></iframe><p>And then for an unsuccessful login.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76d2fcc0a595e616f75cf5bd8d1c818b/href">https://medium.com/media/76d2fcc0a595e616f75cf5bd8d1c818b/href</a></iframe><p>It’s better to separate the interfaces so the corresponding modules can either conform to one, or both, depending on their needs. Some modules may only be interested in a successful login, while others might be interested in both a successul and unsuccessful login. By grouping the interfaces into one, the interested modules would have to cater for both instances. Separating the interfaces gives us more flexibility.</p><p>Now we need some sort of plugin registry. This is where the interested modules will register their implementations against the plugin interfaces we defined above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de1059c4e4bc259e4bfafcd5a4c5c7d/href">https://medium.com/media/9de1059c4e4bc259e4bfafcd5a4c5c7d/href</a></iframe><p>Here we create a login container singleton that lets interested modules register their implementations. We explicitly declare our public and internal methods, which is very important. We don’t want other modules to accidentally resolve for the Login Module’s plugins. You might laugh, but I have seen stranger things done before.</p><p>Finally we can update our very <em>useful </em>Authenticator class to resolve for its plugins.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/243f4db4f6cef6c97c5af4fd688a07fd/href">https://medium.com/media/243f4db4f6cef6c97c5af4fd688a07fd/href</a></iframe><h3>Creating Plugins</h3><p>Now we can create our implementations that conform to the appropriate plugins.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a52b35dc1d04471b1a993a128343e052/href">https://medium.com/media/a52b35dc1d04471b1a993a128343e052/href</a></iframe><p>Now all we need to do is register with the login container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1acc7520166d452c0628e51ff5de5de9/href">https://medium.com/media/1acc7520166d452c0628e51ff5de5de9/href</a></iframe><p>Finally we can test with the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27ab3770947982a6db25cd5b6a2d724d/href">https://medium.com/media/27ab3770947982a6db25cd5b6a2d724d/href</a></iframe><p>And we will get the following response.</p><pre><strong>Logging in...</strong></pre><pre><strong>Logged in successfully...</strong></pre><pre><strong>Fetching user profile with id 1234...</strong></pre><pre><strong>Fetching user feed with id 1234...</strong></pre><pre><strong>Storing user with id 1234...</strong></pre><h3>Conclusion</h3><p>We successfully implemented this technique for displaying tabs inside a UITabbar. Each module can register as a plugin and therefore the Tabbar Module will display each of the plugins registered inside the UITabbar as a UITabbarItem. The Tab Module is only responsible for the look and feel and displaying each of the plugins registered against it.</p><p>Special thanks to <a href="https://medium.com/u/8dc9607a9e87">Justin Guedes</a> for the login container implementation, and our software architect, Leo.</p><p>All code can be found in the following repository:</p><p><a href="https://github.com/TYRONEMICHAEL/plugin-architecture-swift">TYRONEMICHAEL/plugin-architecture-swift</a></p><p>Follow me on twitter, where I regularly like to tweet about fun topics like this.</p><p><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></p><h4>More where this came from</h4><p>This story is published in <a href="http://blog.usejournal.com/">Noteworthy</a>, where thousands come every day to learn about the people &amp; ideas shaping the products we love.</p><p>Follow our publication to see more product &amp; design stories featured by the <a href="https://usejournal.com/?/utm_source=usejournal.com&amp;utm_medium=blog&amp;utm_campaign=guest_post">Journal</a> team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1972735d728" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving ambiguity and increasing performance with the Promise Type]]></title>
            <link>https://medium.com/@tyronemichael/solving-ambiguity-and-increasing-performance-with-the-promise-type-8dcb9b2465f1?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dcb9b2465f1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 12:59:45 GMT</pubDate>
            <atom:updated>2018-03-29T13:01:37.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzszqcNOQz3JCI_rLoGRYQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/fcZIyU-nbFE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Anderson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We recently ran into an issue at <a href="https://medium.com/u/f2c63b4fb45a">Standard Bank Engineering</a> where we were running the same service calls concurrently. With a large number of users using the app at any given time, any expensive and unnecessary service calls can put tremendous pressure on your backend systems as well as giving the perception of the app being slow.</p><p>As always you can follow along with the following playground file provided:</p><p><a href="https://github.com/TYRONEMICHAEL/cached-promises">TYRONEMICHAEL/cached-promises</a></p><h3>Describing the initial problem</h3><p>We have a number of different feature teams. If we need data or functionality from a specific team, the team provides a public facing interface. Other feature teams who consume the interface don’t care about the implementation. Let’s take a look at simple example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcf2812c5ccce36e4eace5308da5c57d/href">https://medium.com/media/fcf2812c5ccce36e4eace5308da5c57d/href</a></iframe><p>And this would be an example of a public facing interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/198aac7b47e5337f6d17b58e81ff716b/href">https://medium.com/media/198aac7b47e5337f6d17b58e81ff716b/href</a></iframe><p>Now all service calls should be cached, so let us write a quick interface and implementation for caching a user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31dfd913763e8c9c28cf0ee333a45df9/href">https://medium.com/media/31dfd913763e8c9c28cf0ee333a45df9/href</a></iframe><p>And finally the private implementation for the repository implementing the public interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5374c7ba6c568b9fdfadc4031b90f9f9/href">https://medium.com/media/5374c7ba6c568b9fdfadc4031b90f9f9/href</a></iframe><p>Let’s step back and explain the above in more detail.</p><ul><li>The implementation checks the cache to see if we have a current user, if a user is found the user is returned.</li><li>If the user is not found, we trigger a service call to fetch the user. We do all service calls on the background thread, preventing anyone from locking the main thread. If a service call is done on the main thread, we throw a fatal runtime error.</li><li>Once a user has been fetched, we populate the cache.</li></ul><p>You can test the above with the following snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d30b121a3cc618afcd0f1c1f8b1d20b/href">https://medium.com/media/1d30b121a3cc618afcd0f1c1f8b1d20b/href</a></iframe><p>Now there are three major problems with this approach:</p><ul><li>There is no way to determine if a service call has been triggered and has not yet returned. Therefore, we can have multiple service calls happening before the cache has been populated.</li><li>If we look at the interface, we have no idea that we have to run the function on the background thread. Yes the app will throw a fatal error at runtime, but we also shouldn’t have to look at the implementation.</li><li>Finally we might accidentally call getCurrentUser() on the main thread and not crash, because the cache has already been populated.</li></ul><p>These are three significant problems that we need to solve for.</p><h3>Solving the problem by using a Promise</h3><p>Before we start with our solution, it is important to mention the <a href="https://github.com/antitypical/Result">Result Type</a>. I mention it in quite a few of my articles, but basically an app can be in one of two states, either a <strong>success state</strong> or in a <strong>failure state</strong>. <a href="https://en.wikipedia.org/wiki/Result_type">Wikipedia</a> sums it up quite nicely.</p><blockquote>Result Type provides an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the programmer is forced to consider success or failure paths, before getting access to the expected result; this eliminates the possibility of an erroneous programmer assumption.</blockquote><p>Now there is another state a program can be in. And this is where the <a href="https://en.wikipedia.org/wiki/Futures_and_promises">Promise Type</a> comes in. Wikipedia, once again, sums up Futures and Promises quite nicely.</p><blockquote>Promise and Futures describe an object that acts as a proxy for a result that is initially unknown, usually because the <a href="https://en.wikipedia.org/wiki/Computation">computation</a> of its value is yet incomplete.</blockquote><p>Basically you can think of a Promise as a <strong>Future Result</strong>. So correcting my previous statement, a program can actually be in one of three states:</p><ul><li>Success state</li><li>Failure state</li><li>Waiting / Unknown state</li></ul><p>There are quite a few frameworks and libraries that have impemented the Promise or Future Type, but I am specifically using <a href="https://github.com/google/promises">Google’s</a>. By updating our interface from:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/198aac7b47e5337f6d17b58e81ff716b/href">https://medium.com/media/198aac7b47e5337f6d17b58e81ff716b/href</a></iframe><p>To:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18f46a7a2b5167f23a8549226e66195e/href">https://medium.com/media/18f46a7a2b5167f23a8549226e66195e/href</a></iframe><p>We remove all ambiguity. We longer need to look at the implementation to determine if we have to run the function on the background thread. We have a <strong>promise</strong> that we will <em>eventually</em> get a value. The contract states explicitly: do what you need to do in the meantime while we try to fulfil your request. If we cannot fulfil your request, we will let you know why so you can handle accordingly. Otherwise your result will arrive sometime in the future.</p><h3>Refactoring our previous implementation</h3><p>We can update our implementation for getting a current user to the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d560170d43e257fd5117ffaa39d49d00/href">https://medium.com/media/d560170d43e257fd5117ffaa39d49d00/href</a></iframe><p>But we still need to cache our results.</p><p>But instead of caching our results, can’t we simply cache the <strong>Promise? </strong>By updating our cache protocol and implementation with the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d39171d701ec25c1c75ed191c2913fae/href">https://medium.com/media/d39171d701ec25c1c75ed191c2913fae/href</a></iframe><p>We can now update our repository to cache our <strong>Promise </strong>and prevent unnecessary service calls being triggered without using anything fancy or complicated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da42e74a32d5630c8a3c6830f05cde34/href">https://medium.com/media/da42e74a32d5630c8a3c6830f05cde34/href</a></iframe><p>Finally if the <strong>Promise </strong>fails we catch it and clear the cache.</p><p>I have set up a little playground, to illustrate visually what we have achieved. We have two tabs, independent of each other, that require the same set of data. Both tabs are using the same interface to call the same function at the same time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fx47jaz0s7TMaB3BwvL%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fx47jaz0s7TMaB3BwvL&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fx47jaz0s7TMaB3BwvL%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="276" frameborder="0" scrolling="no"><a href="https://medium.com/media/916c5dcf421f6b1f401a8281b4180410/href">https://medium.com/media/916c5dcf421f6b1f401a8281b4180410/href</a></iframe><p>And if the service call fails, we get the following.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkgT9GkkRX9S23AQMyh%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FkgT9GkkRX9S23AQMyh&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkgT9GkkRX9S23AQMyh%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="276" frameborder="0" scrolling="no"><a href="https://medium.com/media/249ca0a94a064253eecce8b47020c8a9/href">https://medium.com/media/249ca0a94a064253eecce8b47020c8a9/href</a></iframe><p>Test the above out with all the code using the following playground file:</p><p><a href="https://github.com/TYRONEMICHAEL/cached-promises">TYRONEMICHAEL/cached-promises</a></p><h3>Promise is a Functor and a Monad</h3><p>Google has an excellent <a href="https://github.com/google/promises">Swift Promise Framework</a> that is compatible with Swift and Objective C. It is the same library I use in my playground example. So if you are comfortable using flatmap and map with Arrays, Optionals, and / or the Result Type, you will be happy to know that the Promise Type follows the same laws allowing you compose functions just as you were previously. Let’s talk more about that next time though.</p><p>Follow me on twitter, where I regularly like to tweet about fun topics like this.</p><p><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dcb9b2465f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing declarative code using Result Extensions]]></title>
            <link>https://medium.com/@tyronemichael/writing-declarative-code-using-result-extensions-1ec45474101f?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec45474101f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Sat, 27 Jan 2018 05:37:29 GMT</pubDate>
            <atom:updated>2018-01-27T05:38:44.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOduoy87Euj3qumnB7-ovA.jpeg" /></figure><p>I recently read an excellent <a href="https://appventure.me/2018/01/10/optional-extensions/">post</a> by <a href="https://medium.com/u/8384439cc09b">Benedikt Terhechte</a> where he extends the API of optionals. At <a href="https://medium.com/@glynnallen17">Standard Bank</a>, we use the <a href="https://github.com/antitypical/Result">Result Type</a> quite extensively, so I took the same ideas and applied it to the Result Type. After this post we will end up with composable code and a declarative API, something akin to the below snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abc2d9506139f99ec9068d746f85c5f2/href">https://medium.com/media/abc2d9506139f99ec9068d746f85c5f2/href</a></iframe><p>You can follow with a working example in the following playground file.</p><p><a href="https://github.com/TYRONEMICHAEL/result-extensions">TYRONEMICHAEL/result-extensions</a></p><h3>A fictional brief</h3><p>Let’s pretend we are building a simple app for a client. After sitting with the domain expert, he informs us that anyone can browse the app, but to become a registered user you need to fulfil the following requirements:</p><ul><li>A registered user must have a <strong>valid</strong> <strong>identifier</strong>.</li><li>A registered user needs to have a <strong>valid email </strong>address and the email address must be a <strong>gmail</strong> address.</li><li>A registered user must be either a <strong>Millennial</strong> or a <strong>Generation X</strong>.</li><li>We need to show to the user why they <strong>cannot be registered</strong> after trying.</li></ul><h4>Extending the Result Type with an applicative</h4><p>One of the requirements is to show the user why they cannot become a registered user. By using an applicative, we can achieve this quite beautifully.</p><p>Before writing our applicative we need to define a protocol called a semigroup. <a href="https://medium.com/u/6c5f26546203">Brandon Williams</a> has an excellent <a href="http://www.fewbutripe.com/swift/math/algebra/2015/02/17/algebraic-structure-and-protocols.html">explanation</a> on what a semigroup is and why we would want to use it. For the purpose of this post, we will only need anArray to conform to the protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4bb72fcf5573dbbf34eeafa31b4297/href">https://medium.com/media/dd4bb72fcf5573dbbf34eeafa31b4297/href</a></iframe><p>We can now write our applicative extending the Result Type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98bdfa95b5b4bee13752ed482f057a8d/href">https://medium.com/media/98bdfa95b5b4bee13752ed482f057a8d/href</a></iframe><p>This allows for the following code to be written.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bb27c041a9eca998b63f7fab2adcd02/href">https://medium.com/media/9bb27c041a9eca998b63f7fab2adcd02/href</a></iframe><p>If you print the contents of the user object above, you will get the following:</p><pre><strong>failure: 3 elements</strong></pre><pre><strong>- &quot;invalid id&quot;</strong></pre><pre><strong>- &quot;invalid email&quot;</strong></pre><pre><strong>- &quot;invalid millennial&quot;</strong></pre><p><a href="https://medium.com/u/36377060ece2">Stephen Celis</a> has an excellent video detailing the above called <a href="https://www.youtube.com/watch?v=Awva79gjoHY">Applicatives and Swift</a>. A great watch.</p><h4>Extending the Result Type with AND</h4><p>One of the requirements is for a user to have both a valid email address and a valid gmail address. Let’s extend the Result Type with the following code for and.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdc790ccf082590db101890693b21a75/href">https://medium.com/media/bdc790ccf082590db101890693b21a75/href</a></iframe><p>Now we can do the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/042207b185dc1807cd75fe9ba8a1a685/href">https://medium.com/media/042207b185dc1807cd75fe9ba8a1a685/href</a></iframe><p>If you print the result you will get the following output.</p><pre><strong>failure: 1 element</strong></pre><pre><strong>- &quot;invalid gmail address&quot;</strong></pre><h4>Extending the Result Type with OR</h4><p>The last requirement is for a user to be either a Millennial or Generation X. We can fulfil this requirement by extending the Result Type with or.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27b0fb65cde8f4ea9d48d95b25da9507/href">https://medium.com/media/27b0fb65cde8f4ea9d48d95b25da9507/href</a></iframe><p>Now we have the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e082028c638c7c23795a37687d7cad/href">https://medium.com/media/08e082028c638c7c23795a37687d7cad/href</a></iframe><p>If you print the result you will get the following output.</p><pre><strong>failure: 2 elements</strong></pre><pre><strong>- &quot;invalid millennial&quot;</strong></pre><pre><strong>- &quot;invalid gen x&quot;</strong></pre><h4>Putting everything together</h4><p>The below snippet satisfies all of our requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ba5f65ec5d003843be63cc0e301dffd/href">https://medium.com/media/3ba5f65ec5d003843be63cc0e301dffd/href</a></iframe><p>If you print the registeredUser, you will either get a successful result depending on our inputs or an output detailing reasons why the user could not be registered. In the case above, the result will print the following.</p><pre><strong>failure: 4 elements</strong></pre><pre><strong>- &quot;invalid id&quot;</strong></pre><pre><strong>- &quot;invalid gmail address&quot;</strong></pre><pre><strong>- &quot;invalid millennial&quot;</strong></pre><pre><strong>- &quot;invalid gen x&quot;</strong></pre><h3>BONUS</h3><p>Let’s extend the Result Type with custom operators for and and or.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4849616aa53a130c5723c96dcc67f75/href">https://medium.com/media/d4849616aa53a130c5723c96dcc67f75/href</a></iframe><p>We can now update our RegisteredUser.create method to the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab12783581159607b3669280253f2cc2/href">https://medium.com/media/ab12783581159607b3669280253f2cc2/href</a></iframe><h3>Conclusion</h3><p>You can achieve a high level of flexibility by having small functions that are easily composed. In the end you have code that is easier to maintain, easier to read, and easier to test.</p><p>You can find a working example in the following playground file.</p><p><a href="https://github.com/TYRONEMICHAEL/result-extensions">TYRONEMICHAEL/result-extensions</a></p><p>Follow me on twitter, where I regularly like to tweet about fun topics like this.</p><p><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec45474101f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Result Oriented Programming: building a result incrementally using an applicative functor]]></title>
            <link>https://medium.com/@tyronemichael/result-oriented-programming-building-a-result-incrementally-using-an-applicative-functor-b3d6ceb423e7?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3d6ceb423e7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Tue, 05 Dec 2017 14:13:20 GMT</pubDate>
            <atom:updated>2018-03-21T17:56:27.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8jylI6XKGyeERwzCEVvCQ.jpeg" /></figure><p>In my <a href="https://medium.com/@tyronemichael/result-oriented-programming-building-a-result-incrementally-using-function-composition-8a71875633d0">previous story</a>, we looked at how we could build a Result incrementally using function composition. We built three variations of the function applyResult. Composing applyResult with flatMap allowed us to take the following piece of code:</p><pre>func getTweetDetails(for userId: String) <br>-&gt; Result&lt;TweetDetails, EmojiErr&gt; {<br>    var user: User!<br>    var tweet: Tweet!<br>    <br>    return getUser(with: userId)<br>        .flatMap { userData -&gt; Result&lt;Tweet, EmojiErr&gt; in<br>            user = userData<br>            return getLatestTweet(for: userData)<br>        }.flatMap { <br>           tweetData -&gt; Result&lt;TweetSentiment, EmojiErr&gt; in<br>           tweet = tweetData<br>           return getTweetSentiment(for: tweetData)<br>        }.flatMap { sentimentData in<br>           .success(TweetDetails(user, tweet, sentimentData))<br>    }<br>}</pre><p>and improve it in the following way:</p><pre>func getTweetDetails(for userId: String) -&gt; Result&lt;TweetDetails, EmojiError&gt; {<br>    let tweetDetails = curry(TweetDetails.init)<br>    return applyResult(of: getUser(), to: tweetDetails)<br>        .flatMap(applyResult(of: getLatestTweet))<br>        .flatMap(applyResult(of: getTweetSentiment))<br>}</pre><p>A good friend and an exceptional engineer recently watched a video by <a href="https://medium.com/u/36377060ece2">Stephen Celis</a> called <a href="https://www.youtube.com/watch?v=Awva79gjoHY"><strong>Applicatives and Swift</strong></a>. After reading my previous article, he suggested I watch the video. By using an applicative functor, he believed, the solution could be simplified even further.</p><p>I must admit, I had to watch the video a few times before fully grasping the concept. It is an excellent video and one I would highly recommend, even if for only watching <a href="https://medium.com/u/36377060ece2">Stephen Celis</a> live code the entire thing.</p><p>After experimenting in Playgrounds, I was able to simplify the above into something quite elegant:</p><pre>func getTweetDetails(for userId: String) -&gt; Result&lt;TweetDetails, EmojiError&gt; {<br>    return pure(createTweetDetails) <br>        &lt;*&gt; getUser() <br>        &lt;*&gt; pure(getLatestTweet) <br>        &lt;*&gt; pure(getTweetSentiment)<br>}</pre><p>This post will detail just how I was able to achieve the above using an applicative functor.</p><h3>Where does the applicative functor fit in?</h3><p>Before we begin, let’s first discuss applicatives. If we look at the signature of map(functor), and flatmap(monad) implemented in the Result Type, we have the following:</p><pre>((A -&gt; B),  Result&lt;A, Error&gt;) -&gt; Result&lt;B, Error&gt;<br>((A -&gt; Result&lt;B, Error&gt;), Result&lt;A, Error&gt;) -&gt; Result&lt;B, Error&gt;</pre><p>I am not going to discuss functors or monads, because <a href="http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/">this article</a> does a tremendous job doing just that. But an applicative functor just extends a functor by now wrapping our functions in context as well. This leaves us with the following signature for an applicative functor:</p><pre>(Result&lt;(A -&gt; B), Error&gt;, Result&lt;A, Error&gt;) -&gt; Result&lt;B, Error&gt;</pre><p>At first glance that might not seem the most useful, but let us first implement the applicative then use it to show its usefulness.</p><h3>Building the Applicative Functor</h3><p>We will start by first creating our operator:</p><pre>precedencegroup LeftAssociativity {<br>    associativity: left<br>}</pre><pre>infix operator &lt;*&gt;: LeftAssociativity</pre><p>Now let us create a simple function called pure. This function will take a value and wrap it in a Result.</p><pre>func pure&lt;A&gt;(_ x: A) -&gt; Result&lt;A, EmojiError&gt; {<br>    return .success(x)<br>}</pre><p>And now for the actual applicative implementation:</p><pre>func &lt;*&gt; &lt;A, B, E&gt;(f: Result&lt;(A) -&gt; B, E&gt;, x: Result&lt;A, E&gt;) -&gt; Result&lt;B, E&gt; {<br>    return f.flatMap(x.map)<br>}</pre><p>Let us take the above for a test run by creating the following struct:</p><pre>struct Tweet {<br>    let id: Int?<br>    let tweet: String<br>}</pre><p>Now let us create a simple curried function that builds a Tweet incrementally:</p><pre>let createTweet = { id in { tweet in return Tweet(id: id, tweet: tweet) } }</pre><p>Last step is to create two simple validating functions for our inputs:</p><pre>func validateId(_ id: Int) -&gt; Result&lt;Int, EmojiError&gt; {<br>    return id &gt; 0 <br>        ? pure(id) <br>        : .failure(.😩(&quot;invalid id&quot;))<br>}</pre><pre>func validateTweet(_ tweet: String) -&gt; Result&lt;String, EmojiError&gt; {<br>    return tweet.characters.count &lt; 140 <br>        ? pure(tweet) <br>        : .failure(.😩(&quot;tweet too long&quot;))<br>}</pre><p>Finally we end up with the following functionality:</p><pre>let tweet = pure(createTweet) <br>    &lt;*&gt; validateId(1) <br>    &lt;*&gt; validateTweet(&quot;Hello Twitter&quot;)</pre><p>Awesome.</p><p>Try passing in an invalid id or a tweet that is longer than 140 characters. We get a failable initializer for free. Hopefully that gives you some idea of why an applicative can be so useful.</p><h3>Back to the “real-world” example</h3><p>If you would like to follow with a working solution, please view the following playground file.</p><p><a href="https://github.com/TYRONEMICHAEL/rop-functional-composition">TYRONEMICHAEL/rop-functional-composition</a></p><p>Let us look at the following piece of code and determine how we are going to fufill the criteria:</p><pre>let createTweetDetails = {<br>    user in {<br>       tweet in {<br>          sentiment in<br>          TweetDetails(<br>               user: user, <br>               tweet: tweet, <br>               sentiment: sentiment<br>          )<br>       }<br>    }<br>}</pre><p>So we need to first execute a function by fetching <em>the current user</em>. We would then use the the <strong><em>user’s data</em></strong><em> to get their latest tweet</em>. Finally we would use the <strong><em>tweet’s data</em></strong><em> to get the </em><strong><em>tweet’s sentiment</em></strong>. We do this while still preserving the <strong>Railway Oriented Programming</strong> pattern. If any of the previous functions were to fail, the error falls through and the following functions will not be executed.</p><p>So unfortunately if we have the following function signatures:</p><pre>func getUser() -&gt; Result&lt;User, EmojiError&gt;<br>func getLatestTweet(for user: User?) -&gt; Result&lt;Tweet, EmojiError&gt;<br>func getTweetSentiment(for tweet: Tweet?) -&gt; Result&lt;TweetSentiment, EmojiError&gt;</pre><p>Our previous applicative implementation requires the following:</p><pre>let user: Result&lt;TweetDetails, EmojiError&gt; =<br>    pure(createTweetDetails)<br>    &lt;*&gt; getUser()<br>    &lt;*&gt; getLatestTweet(for: User)<br>    &lt;*&gt; getTweetSentiment(for: Tweet)</pre><p>Changing the function signatures is not an option, so just like we created different variations of applyResult we can create different variations of our applicatives. Stay with me because this can get a little confusing at first.</p><h4>So what do we need to do?</h4><p>Let’s break it down:</p><ul><li>We need to initially wrap our creating function in a Result.</li><li>We then execute a function which returns us a Result.</li><li>Our applicative will then unwrap the Result to determine if it is of type .success or .failure. If it is the latter, we do nothing and the error is passed through. If it is a successful Result, we take the unwrapped value and pass it into our creating function building it incrementally.</li><li>We finally take the unwrapped value and pass it into the next function doing the previous steps again until we have a completed model.</li><li>Remember if at any stage we get a .failure the following functions will not be exectuted, and we get passed the point of failure.</li></ul><p>Whoa. That sounds like a lot. But it’s just like putting a puzzle together. Because Swift is a static language we have the compiler to help us. We simply cannot put the wrong puzzle pieces together.</p><p>Carrying on. Let’s look at the current implementation of our applicative:</p><pre>func &lt;*&gt;&lt;A, B&gt;(f: Result&lt;(A) -&gt; B, EmojiError&gt;, x: Result&lt;A, EmojiError&gt;) -&gt; Result&lt;B, EmojiError&gt; {<br>    switch (f, x) {<br>    case let (.success(f), _): return x.map(f)<br>    case let (.failure(e), .success): return .failure(e)<br>    case let (.failure(_), .failure(e)): return .failure(e)<br>    }<br>}</pre><p>Now look at the following piece of code:</p><pre>let result: Result&lt;(Tweet) -&gt; (TweetSentiment) -&gt; TweetDetails, EmojiError&gt; = pure(createTweetDetails) &lt;*&gt; repo.getUser()</pre><p>Our createTweetDetails requires a Tweet. Executing getLatestTweet() will return back a Tweet. Unfortunately, getLatestTweet, which is the next function we need to exectute, requires a User as well. We can achieve this by taking a tuple and wrapping it in a Result:</p><pre>let result: Result&lt;(<br>(Tweet) -&gt; (TweetSentiment) -&gt; TweetDetails, User), EmojiError&gt; = pure(createTweetDetails) &lt;*&gt; repo.getUser()</pre><p>We can then pass the previous functions returned value into the next function we want to execute. We do this with another implementation of our applicative:</p><pre>func &lt;*&gt;&lt;A, B&gt;(f: Result&lt;(A) -&gt; B, EmojiError&gt;, x: Result&lt;A, EmojiError&gt;) -&gt; Result&lt;(B, A), EmojiError&gt; {<br>    switch (f, x) {<br>    case let (.success(r1), .success(r2)): <br>        return x.map { v in (r1(v), r2) }<br>    case let (.failure(e), .success): <br>        return .failure(e)<br>    case let (_, .failure(e)): <br>        return .failure(e)<br>    }<br>}</pre><p>We finally need to create another implentation for our applicative that will accept a function that returns a result. The applicative will unwrap the tuple and pass the second value into the function. Finally unwrapping the result of the function and passing it into createTweetDetails.</p><pre>func &lt;*&gt;&lt;A, B, C&gt;(f: Result&lt;((B) -&gt; C, A), EmojiError&gt;, x:  Result&lt;(A) -&gt; Result&lt;B, EmojiError&gt;, EmojiError&gt;) -&gt; Result&lt;(C, B), EmojiError&gt; {<br>    switch (f, x) {<br>    case let (.success(r1), .success(r2)): <br>        return r2(r1.1).map { v in (r1.0(v), v) }<br>    case let (.failure(e), .success):<br>        return .failure(e)<br>    case let (_, .failure(e)): <br>        return .failure(e)<br>    }<br>}</pre><p>We want to return a Result without the previous value passing into the next function, because our TweetDetails model would be complete. This is simply the above without returning a tuple:</p><pre>func &lt;*&gt;&lt;A, B, C&gt;(f: Result&lt;((B) -&gt; C, A), EmojiError&gt;, x:  Result&lt;(A) -&gt; Result&lt;B, EmojiError&gt;, EmojiError&gt;) -&gt; Result&lt;(C, B), EmojiError&gt; {<br>    switch (f, x) {<br>    case let (.success(r1), .success(r2)): <br>        return r2(r1.1).map { v in r1.0(v) }<br>    case let (.failure(e), .success):<br>        return .failure(e)<br>    case let (_, .failure(e)): <br>        return .failure(e)<br>    }<br>}</pre><p>Finally we end up with:</p><pre>func getTweetDetails(for userId: String) -&gt; Result&lt;TweetDetails, EmojiError&gt; {<br>    return pure(createTweetDetails) <br>        &lt;*&gt; getUser() <br>        &lt;*&gt; pure(getLatestTweet) <br>        &lt;*&gt; pure(getTweetSentiment)<br>}</pre><h3>Conclusion</h3><p>I know the above can be quite a lot to wrap your head around. But it gets easier and easier. The above example may seem a little trivial, but it perfectly demonstrates how we can obey the <strong>Railway Oriented Programming</strong> pattern while using an applicative.</p><p><a href="https://medium.com/u/36377060ece2">Stephen Celis</a> was kind enough to give my article a read. He pointed out the following:</p><blockquote>The main thing I eventually learned was that applicatives shine when the values sent to the function are all independent. In your example, we need the result of the user request before we can make the tweet requests, so we can’t run them in parallel.</blockquote><p>In other words an applicative is not the best choice for the above implementation. An applicative shines when you accumulate errors. Monads have restrictions that applicatives don’t: namely they’re railroad-oriented and when a monad switches tracks to the error case, they’re done.</p><p>The experimentation is fun though and it helps to have the veterans help you along the way.</p><p>You can find all the working code in the following repository. It will be easier to follow than the snippets above.</p><ul><li><a href="https://github.com/TYRONEMICHAEL/rop-functional-composition">TYRONEMICHAEL/rop-functional-composition</a></li><li><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3d6ceb423e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Result Oriented Programming: building a result incrementally using function composition]]></title>
            <link>https://medium.com/@tyronemichael/result-oriented-programming-building-a-result-incrementally-using-function-composition-8a71875633d0?source=rss-b8d3b73a33bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a71875633d0</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Tyrone Michael Avnit]]></dc:creator>
            <pubDate>Sun, 11 Jun 2017 15:32:47 GMT</pubDate>
            <atom:updated>2018-03-21T17:47:47.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qP6HY_CzGbKinGDjY3vp1Q.jpeg" /></figure><p>At <a href="https://medium.com/@glynnallen17">Standard Bank</a>, we use the <a href="https://github.com/antitypical/Result"><strong>Result type</strong></a>. We use a rather simple implementation, which can be digested quite easily:</p><pre>enum Result&lt;T, Error: Swift.Error&gt; {<br>    case success(T)<br>    case failure(Error)</pre><pre>    func map&lt;U&gt;(_ transform: (T) -&gt; U) -&gt; Result&lt;U, Error&gt; {<br>        return flatMap { .success(transform($0)) }<br>    }</pre><pre>    func flatMap&lt;U&gt;(_ transform: (T) -&gt; Result&lt;U, Error&gt;)<br>    -&gt; Result&lt;U, Error&gt; {<br>        switch self {<br>        case let .success(value): return transform(value)<br>        case let .failure(error): return .failure(error)<br>        }<br>    }<br>}</pre><p>This allows us to adopt the <strong>Railway Oriented Programming</strong> pattern by piping functions together in the following way:</p><pre>let result = getUser()<br>    .flatmap(getLatestTweet)<br>    .flatmap(getTweetSentiment)</pre><p><strong>Result Oriented Programming</strong> \ <strong>Railway Oriented Programming</strong> is a powerful functional pattern that can truly simplify the way you write code. If you are unfamiliar with the pattern, I would strongly suggest you watch the videos below first:</p><ul><li><a href="https://vimeo.com/97344498"><strong>Railway Oriented Programming</strong></a></li><li><a href="https://news.realm.io/news/tryswift-saul-mora-result-oriented-development/"><strong>Result Oriented Programming</strong></a></li></ul><h3>Describing the problem</h3><p>Imagine we have the following function signature:</p><pre>(A) -&gt; (B) -&gt; (C) -&gt; (D)</pre><p>this is essentially:</p><pre>(A) -&gt; (D)</pre><p>but what we actually want is:</p><pre>(A) -&gt; (B) -&gt; (C) -&gt; (D) -&gt; (A, B, C, D)</pre><p>Let us attempt to try solve this.</p><p>If you would like to follow with a working solution, please view the following playground file.</p><p><a href="https://github.com/TYRONEMICHAEL/rop-functional-composition">TYRONEMICHAEL/rop-functional-composition</a></p><h3>Building a simple example using functional composition</h3><p>Let us build a ‘useful<em>’ </em><strong>Twitter Sentiment Tool </strong>off a fictitious API. We will begin by firstly defining our data models:</p><pre>struct User {<br>    let id: String<br>    let name: String<br>}</pre><pre>struct Tweet {<br>    let id: String<br>    let message: String<br>    let userId: String<br>}</pre><pre>struct TweetSentiment {<br>    let id: String<br>    let isPositive: Bool<br>    let tweetId: String<br>}</pre><p>Because of the way the API is structured, in order to get the actual sentiment of a tweet, we would first need to make an API call to <em>get the current user</em>. We would then use the the <strong><em>user’s data</em></strong><em> to get their latest tweet</em>. Finally we would use the <strong><em>tweet’s data</em></strong><em> to get the </em><strong><em>tweet’s sentiment</em></strong>.</p><p>We are not going to worry about the actual implementations for the functions below, instead let’s focus on their <strong>signatures</strong>. The function signature for getting a <strong>user</strong>:</p><pre>func getUser(with userId: String) -&gt; Result&lt;User, Error&gt;</pre><p>for getting the <strong>latest tweet</strong>:</p><pre>func getLatestTweet(for user: User) -&gt; Result&lt;Tweet, Error&gt;</pre><p>and finally for getting the <strong>sentiment of the tweet</strong>:</p><pre>func getTweetSentiment(for tweet: Tweet) <br>-&gt; Result&lt;TweetSentiment, Error&gt;</pre><p>So essentially we can only retrieve the <strong>tweet’s</strong> <strong>sentiment</strong>, if we are first able to retrieve the <strong>current user</strong> and then their <strong>latest tweet</strong>. If at any point during the pipeline something were to go wrong, we stop and the error falls through. For example, if we had the following:</p><pre>enum EmojiErr: Error {<br>    case 😩(String)<br>}</pre><pre>func getUser(with userId: String) -&gt; Result&lt;User, EmojiErr&gt;<br>func getLatestTweet(for user: User) -&gt; Result&lt;Tweet, EmojiErr&gt;<br>func getTweetSentiment(for tweet: Tweet) <br>-&gt; Result&lt;TweetSentiment, EmojiErr&gt;</pre><p>We achieve this:</p><pre>let result = getUser()<br>    .flatmap(getLatestTweet)<br>    .flatmap(getTweetSentiment)</pre><pre>switch result {<br>case let .success(value): <br>    print(&quot;Positive tweet: \(value.isPositive)&quot;)<br>case let .failure(error):<br>    switch error {<br>    case let .😩(value): assertionFailure(value)<br>    }<br>}</pre><p>Awesome, exactly what we are looking for. Now let us design a new data model that ecapsulates a <strong>user</strong>, their <strong>latest tweet</strong>, and the <strong>tweet’s</strong> <strong>sentiment</strong>. This model will extract the information we need to give us a nice message about the <strong>sentiment of the tweet</strong>.</p><pre>struct TweetDetails {<br>    private let user: User<br>    private let tweet: Tweet<br>    private let sentiment: TweetSentiment</pre><pre>    init(user: User, tweet: Tweet, sentiment: TweetSentiment) {<br>        self.user = user<br>        self.tweet = tweet<br>        self.sentiment = sentiment<br>    }</pre><pre>    var expressedMessage: String {<br>        let sentimentDescription = sentiment.isPositive <br>        ? &quot;positive&quot;<br>        : &quot;negative&quot;<br>        <br>        return &quot;\(user.name) said \(tweet.message) <br>        which has a \. (sentimentDescription) sentiment&quot; <br>    }<br>}</pre><p>Ok now let us create a method that returns this model:</p><pre>func getTweetDetails(for userId: String) <br>-&gt; Result&lt;TweetDetails, EmojiErr&gt; {<br>     return getUser()<br>         .flatmap(getLatestTweet)<br>         .flatmap(getTweetSentiment)<br>}</pre><p>Unfortunately this will not work, because our return type is of Result&lt;TweetSentiment, EmojiErr&gt; and should be of Result&lt;TweetDetails, EmojiErr&gt;.</p><p>We could, however, solve this <em>rather quickly</em> with the following snippet:</p><pre>func getTweetDetails(for userId: String) <br>-&gt; Result&lt;TweetDetails, EmojiErr&gt; {<br>    var user: User!<br>    var tweet: Tweet!<br>    <br>    return getUser(with: userId)<br>        .flatMap { userData -&gt; Result&lt;Tweet, EmojiErr&gt; in<br>            user = userData<br>            return getLatestTweet(for: userData)<br>        }.flatMap { <br>           tweetData -&gt; Result&lt;TweetSentiment, EmojiErr&gt; in<br>           tweet = tweetData<br>           return getTweetSentiment(for: tweetData)<br>        }.flatMap { sentimentData in<br>           .success(TweetDetails(user, tweet, sentimentData))<br>    }<br>}</pre><p>But now we moving away from code that was succinctly <strong>declarative</strong> to something more <strong>imperative</strong>. Since we are working with a functional pattern, we can do better.</p><p>To solve this, we first need to ammend our TweetDetails<strong> </strong>model to be built incrementally. We pass in the <strong>user</strong>, then the <strong>tweet</strong>, and finally the <strong>sentiment of the tweet</strong>.</p><pre>func createTweetDetails(user: User) -&gt; (_ tweet: Tweet) -&gt; (_ sentiment: TweetSentiment) -&gt; TweetDetails {<br>    return { tweet in<br>        return { sentiment in<br>            return TweetDetails(user, tweet, sentiment)<br>        }<br>    }<br>}</pre><pre>let result = createTweetDetails(user)(tweet)(sentiment)</pre><p>In other words createTweetDetails is a curried function of TweetDetails.init. Awesome. So let us rather create a generic curried function for this:</p><blockquote>Currying is the technique of translating the evaluation of a <a href="https://en.wikipedia.org/wiki/Function_(mathematics)">function</a> that takes multiple <a href="https://en.wikipedia.org/wiki/Parameter_(computer_science)">arguments</a> (or a <a href="https://en.wikipedia.org/wiki/Tuple">tuple</a> of arguments) into evaluating a sequence of functions, each with a single argument. — <a href="https://en.wikipedia.org/wiki/Currying">Wikipedia</a></blockquote><pre>func curry&lt;A, B, C, D&gt;(_ function: @escaping (A, B, C) -&gt; D) -&gt; (A) -&gt; (B) -&gt; (C) -&gt; D {<br>    return { (a: A) -&gt; (B) -&gt; (C) -&gt; D in { (b: B) -&gt; (C) -&gt; D in {<br>    (c: C) -&gt; D in function(a, b, c) } } }<br>}</pre><p>Now let us update our implementation for getTweetDetails:</p><pre>func getTweetDetails(for userId: String) <br>-&gt; Result&lt;TweetDetails, HTTPError&gt; {<br>     let tweetDetails = curry(TweetDetails.init)<br>     ... <br>}</pre><p>Now we are getting somewhere. So let us step back and unpack what we are trying to do from here:</p><ul><li>Firstly, we don’t ever want to change the signatures and implementations of our functions getUser, getLatestTweet, and getTweetSentiment.</li><li>So we need to create a function, that takes a result, passes the result to our tweetDetails model, and finally returns both the <strong>result</strong> and the <strong>partial model</strong> into the next function. We do this until we have a complete tweetDetails model.</li></ul><p>Let us create a generic function called applyResult that does just this:</p><pre>func applyResult&lt;A, B&gt;(of result: Result&lt;A, EmojiError&gt;, to partial: (A) -&gt; B) -&gt; Result&lt;(result: A, partial: B), EmojiError&gt; {<br>    return result.flatMap { value in<br>        .success((value, partial(value)))<br>    }<br>}</pre><p>Now let us go back to our implementation and update it:</p><pre>func getTweetDetails(for userId: String) <br>-&gt; Result&lt;TweetDetails, HTTPError&gt; {<br>     let tweetDetails = curry(TweetDetails.init)<br>     let result = applyResult(of: getUser(), to: tweetDetails)<br>     ...<br>}</pre><p>In order to flatmap correctly from here, we need to be able to define the next function that will need to be called to get the next result. We can do this by creating another generic function called applyResult with a different signature:</p><pre>func applyResult&lt;A, B, C&gt;(of fn: @escaping (C) -&gt; Result&lt;A, EmojiError&gt;) -&gt; (_ input: C, _ partial: (A) -&gt; B) -&gt; Result&lt;(result: A, transfrom: B), EmojiError&gt; {<br>    return { input, partial in<br>        return fn(input).flatMap { value in<br>            .success((value, partial(value)))<br>        }<br>    }<br>}</pre><p>Let us go back again and update our implementation:</p><pre>func getTweetDetails(for userId: String) <br>-&gt; Result&lt;TweetDetails, HTTPError&gt; {<br>     let tweetDetails = curry(TweetDetails.init)<br>     let result = applyResult(of: getUser(), to: tweetDetails)<br>         .flatMap(applyResult(of: getLatestTweet))<br>     ...<br>}</pre><p>Finally The last thing we need to do is return the completed model without the previous result, because at this point our model is <strong>complete</strong>. We can do this again by creating another generic function called applyResult with the following signature:</p><pre>func applyResult&lt;A, B, C&gt;(of fn: @escaping (C) -&gt; Result&lt;A, EmojiError&gt;) -&gt; (_ input: C, _ partial: (A) -&gt; B) -&gt; Result&lt;B, EmojiError&gt; {<br>    return { input, partial in<br>        return fn(input).flatMap { value in<br>            .success(partial(value))<br>        }<br>    }<br>}</pre><p>Which leads us back to the <strong>beginning</strong>:</p><pre>func getTweetDetails(for userId: String) -&gt; Result&lt;TweetDetails, EmojiError&gt; {<br>    let tweetDetails = curry(TweetDetails.init)<br>    return applyResult(of: getUser(), to: tweetDetails)<br>        .flatMap(applyResult(of: getLatestTweet))<br>        .flatMap(applyResult(of: getTweetSentiment))<br>}</pre><h3>Conclusion</h3><p>When writing generic functions, we rely on the compiler quite heavily, especially when composing functions together. You work with the compiler to create your solution. Even though the functions are rather small, they are quite dense. It takes more time to think of declarative functional solutions as opposed to an imperative one, but you end up with code that is easier to read, test, and compose together. <a href="https://medium.com/@_ericelliott">Eric Elliot</a> summed this up quite nicely:</p><blockquote><em>Less code = less surface area for bugs = fewer bugs.</em></blockquote><p>You can find all the working code in the following repository.</p><ul><li><a href="https://github.com/TYRONEMICHAEL/rop-functional-composition">TYRONEMICHAEL/rop-functional-composition</a></li><li><a href="https://twitter.com/tyroneavnit">Tyrone Avnit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a71875633d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>