<?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 Ricardo Sánchez on Medium]]></title>
        <description><![CDATA[Stories by Ricardo Sánchez on Medium]]></description>
        <link>https://medium.com/@foolonhill?source=rss-71c9bbf21044------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VMzNKUsAqi_EKZ0MFg07ow.jpeg</url>
            <title>Stories by Ricardo Sánchez on Medium</title>
            <link>https://medium.com/@foolonhill?source=rss-71c9bbf21044------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:53:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@foolonhill/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[Environment injection with Readers]]></title>
            <link>https://medium.com/@foolonhill/environment-injection-with-readers-670fc37fbaec?source=rss-71c9bbf21044------2</link>
            <guid isPermaLink="false">https://medium.com/p/670fc37fbaec</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ricardo Sánchez]]></dc:creator>
            <pubDate>Mon, 09 Jan 2017 13:48:42 GMT</pubDate>
            <atom:updated>2017-01-09T14:07:41.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Ok, imagine one of those <strong>sticker books</strong> for kids in which there are some stickers the kid can place in different <strong>backgrounds</strong>. For example, he can take the cow sticker and place it in a picture of a field, with mountains and a river flowing. Or he can place the cow in an experimental lab, or in space, or in an circus… the book offers many different landscapes to choose from.</p><p>The <strong>result</strong> is a scene in which the cow is chewing cud in a field, in an circus, or in space, although there might not be much grass to chew there…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Opb2lS0FJqiIYnlvlELyhA.png" /><figcaption>Cow by an artist who wants to remain anonymous</figcaption></figure><p>The kid first takes the sticker from the sticker’s page in the book, then decides where to place it (most times in following a totally random logic) and finally puts it in a specific <strong>environment</strong>.</p><p>Then he can take another sticker, of a cow doing something else (jumping, sleeping…) or of a totally different character doing whatever. You get the point.</p><h3>Injecting context</h3><p>Ok, back in the world of adults, where you don’t play with stickers any more (unless you have kids). Imagine you are building an app, and at some point you get some data from a <strong>repository</strong>. It could be from any source, network or local, it doesn’t matter.</p><p>Lets say you are building a social app and you need to get a user for a specific email. You’ll have a method with the following signature:</p><pre>func getUser(email:String) -&gt; User</pre><p>In this example, following our sticker book analogy, the <strong>sticker</strong> is the email and the <strong>result</strong> is the <em>User</em> object. But where is the actual <strong>landscape</strong>?</p><p>The landscape is the context where all this happens, in the sticker book it’s the circus, or the field. In our little example it might be the specific repository we are accessing to get the data: A <strong>web service</strong>, a fully fledged persistence layer or a test mock (where there might not be any grass to chew).</p><p>For our app, let’s call this landscape, the <strong>service</strong>.</p><p>So, how do we let the previous function know which service to use, meaning, where should it get its data from? In other words, how can we <strong>inject</strong> the service? The direct solution might be just passing another <strong>parameter</strong> to the function.</p><pre>func getUser(email:String, service:Service) -&gt; User {<br>   return service.findUser(withEmail:email)<br>}</pre><p>Now the service accesses the repository to return a user for the email we are passing. For the moment we are ignoring all kinds of errors. This is great because now we can, for <strong>testing</strong> purposes, replace the service by anything else that conforms the same protocol, for example.</p><p>While there’s nothing wrong with this approach, it means that now every function of that kind has to include the service parameter. Adding a <strong>default</strong> value to the service parameter might look simpler, you can again use the previous function signature and the service will be the default one. But then you are making the dependency on the service <strong>implicit</strong> and harder to see for API users.</p><p>There’s also another problem, which might be a little harder to see. With that syntax, the caller of the function will have to pass the <em>userId</em> and the service, in other words, it’ll have to know that information when making the call. Two pieces of information that are, at first sight, totally unrelated: the id of the user and the service to get that user from. We are <strong>mixing</strong> two totally different <strong>responsibilities</strong> for the caller of this function: business logic and persistence or network code.</p><h3>An alternative. The Reader</h3><p>You are a good programmer, so you want to separate responsibilities. You believe in the “S” in <a href="https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)">SOLID</a>, so a class must have only <strong>one reason to change</strong>. We need to improve that code.</p><p>What if there was another way?. What if we could remove the service parameter from the function, and have a result value that allows for <strong>partial application</strong>. In a way, we first get the sticker, and then, whenever we are in the appropriate page of the sticker book and we are ready, we place it in the chosen landscape.</p><p>What we are going to do is have that function return some kind of structure, that can later accept the environment to compute the actual result of the operation. That something is a <strong>Reader</strong> and the new function signature would be:</p><pre>func getUser(email:String) -&gt; Reader&lt;Service, User&gt;</pre><p>The Reader is <strong>generic</strong> over two types: The environment and the actual result we want to get. And as the Reader is just a <strong>function</strong> from one to the other, it’ll be implemented like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90b645dd1c5e7ea2de00f85a0b1710c4/href">https://medium.com/media/90b645dd1c5e7ea2de00f85a0b1710c4/href</a></iframe><p>As you can see a Reader is just a struct that holds a function from one generic type (the environment) to another (the result). We are only adding a method <em>run</em> to actually <strong>run the function</strong>.</p><p>Having all that in place, the usage is pretty simple</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc78ef6fa2721520db7c3b96a88ad6f8/href">https://medium.com/media/fc78ef6fa2721520db7c3b96a88ad6f8/href</a></iframe><p>With this approach we don’t directly return the result from the service, but we are returning a <em>Reader</em> of a function from the <em>Service</em> to the <em>User</em>. So now <em>getUser</em> gives us a function (wrapped by a Reader) <strong>we can run at any time</strong>, by passing it the Service.</p><p>For our use of readers in this example we can create an <strong>alias</strong> to simplify the syntax a little bit. We can think of the <em>Reader</em> from <em>Service</em> to anything as an action we want to run in our <em>Service</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9364c14fe84d126a0c1bd9aca1c2fd8/href">https://medium.com/media/c9364c14fe84d126a0c1bd9aca1c2fd8/href</a></iframe><h3>One more step: The monad</h3><p>This is all fine, but I might seem a little overkill just to pass a dependency. Everything up to this point could be achieved by using curried functions. But with the <em>Reader</em> we can go further. The <em>Reader</em> is actually a <strong>Monad</strong>, and as such it can implement <strong><em>map</em></strong> and <strong><em>flatMap</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5d153e87396e823b2adf31d9c40bbae/href">https://medium.com/media/a5d153e87396e823b2adf31d9c40bbae/href</a></iframe><p>You can take a look at the implementations, but all you need to know is they work pretty much like the versions for <strong>Optional</strong> or <strong>Array</strong> (also monads) work in Swift.</p><p>On a side note: The <strong>Reader Monad</strong> is called like that because it “reads” from a shared environment, sometimes it’s also called <strong>Environmental Monad</strong>, which to me is a much more clear name, although less cool and less common.</p><p>Usage of map is pretty straight forward</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446e466e092c14fffa0876957da231e8/href">https://medium.com/media/446e466e092c14fffa0876957da231e8/href</a></iframe><p><strong><em>Flatmap</em></strong> will allow us to chain readers easily. For example, to get <em>User</em> objects that are friends with a <em>User</em> with a specific email.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f6a81074b34ddc96e90b54e45b13d54/href">https://medium.com/media/2f6a81074b34ddc96e90b54e45b13d54/href</a></iframe><p>Now let’s try to go the extra mile and get the ages of all the friends of a user with a specific email. With <em>flatMap</em> that should be pretty easy, right?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba8204b0f73d9409871f9cf1f6fa09e6/href">https://medium.com/media/ba8204b0f73d9409871f9cf1f6fa09e6/href</a></iframe><p>What’s going on there? Simple: We are getting an array of users from <em>getUserFriends</em>, and <em>getUserAge</em> needs a single <em>User</em>. What can we do? We could manually write the <em>flatMap</em> closure and return a reader which function maps over the users array asking for their age.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bbc0b6d7a0a55af72657f69f1d0fcc9/href">https://medium.com/media/7bbc0b6d7a0a55af72657f69f1d0fcc9/href</a></iframe><p>This works, but now it makes our code look ugly as we were aiming to have every step on our new action in just a single <em>flatMap</em> line. We can generalize what that <em>flatMap</em> does and extract the implementation to a function. If you think about it, what we are actually doing is just turning a function from <em>User</em> to a <em>Reader&lt;Service, Int&gt;</em>, to a function from <em>[User]</em> to <em>Reader&lt;Service, [Int]&gt;</em>. We can write a pure function that does just that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88295bf66d2b044f3fb57dd8fd65a08e/href">https://medium.com/media/88295bf66d2b044f3fb57dd8fd65a08e/href</a></iframe><h3>Conclusion</h3><p>This is getting a little long, so we are going to leave it here. But the basic idea is, the Reader (being a Monad), can be easily extended to <strong>compose</strong> it with other readers. That’s something that wouldn’t be so easy if we were to use a similar solution with curried functions or something else instead of readers.</p><p>Next up I’ll talk about making all this <strong>asynchronous</strong> and a specific challenge we’ll find along the way, which we we’ll solve with the help of <strong>Monad Transformers</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=670fc37fbaec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Techniques for a Functional Dependency Injection in Swift]]></title>
            <link>https://medium.com/@foolonhill/techniques-for-a-functional-dependency-injection-in-swift-b9a6143634ab?source=rss-71c9bbf21044------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a6143634ab</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[currying]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ricardo Sánchez]]></dc:creator>
            <pubDate>Wed, 21 Sep 2016 09:28:21 GMT</pubDate>
            <atom:updated>2016-09-21T10:04:23.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5QPXv2m8O6oNuWoX3NXjQ.jpeg" /><figcaption>Totally random image</figcaption></figure><p>Yeah, I know, I couldn’t find any more <strong>jargon</strong> to put in the title, but if you bear with me, we may be able to find something useful in this article.</p><p>Some days ago I was working on a new way to architect my Swift apps based on the concepts of the Redux for Javascript. Suddenly I found myself wanting to use many <strong>free functions</strong> for some tasks (more information in a future article). Those free functions used some dependencies and I needed a way to get those dependencies inside those functions, that is, to <strong>inject</strong> those dependencies.</p><p>I did a little research about how could I do that, and this is what I got. But before I forget I want to thank <a href="http://twitter.com/jdortiz">@jdortiz</a> for the tech review of this text.</p><p>Also, if you prefer there’s a <strong>Swift Playground</strong> version of this article <a href="https://github.com/Odrakir/Writings/tree/master/functionalDI/FunctionalDI.playground">here</a>.</p><h3>Dependency Injection</h3><p>If you are reading this you probably already know what dependency injection is, why it is <strong>important</strong> and why you should already be using it in your code. Nevertheless let’s do a quick summary.</p><p>According to the accurate and usually hard to grasp definition from <a href="https://en.wikipedia.org/wiki/Dependency_injection">Wikipedia</a>:</p><blockquote>In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an <a href="https://en.wikipedia.org/wiki/Object_(computer_science)">object</a> that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.</blockquote><p>In plain English that translates to <strong>passing stuff objects need, to them</strong>. That means if, for example, an object has a property that holds an instance of a service, we don’t want that object to instantiate the service, we want it to receive an instance of the service from <strong>outside</strong> that object.</p><p>This will encourage <strong>decoupling</strong> as the object in question won’t have to know how to construct its dependencies and thus, won’t necessarily need to know what specific services it is using. Given that you are using <strong>abstract</strong> rather than concrete types for the dependencies, the object in question will just know the dependencies implement a specific interface (or conform to a specific protocol in Swift language).</p><p>This will, in consequence, make <strong>testing easier</strong>, as we will be able to easily replace any dependency by a <strong>mock object</strong> which implements that interface.</p><p>The most basic way of dependency injection, then, is just passing an object’s dependencies in its constructor. This way we guarantee those dependencies are in place when we start using our object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c317a2c3c70b43ebe992ef81dd4b8aa4/href">https://medium.com/media/c317a2c3c70b43ebe992ef81dd4b8aa4/href</a></iframe><p>From this basic technique, you can complicate it as much as you want to the point of using <strong>factories</strong> or even using a whole <strong>framework</strong> to manage dependency injection. The gist of it still being: an object has to get its dependencies from somewhere else.</p><p>But you already know all that. Right?</p><h3>Functional it is</h3><p>Up to this point everything should be familiar to you. But what if I told you that, when Wikipedia talks about an ‘object’ it isn’t just talking about an <strong>instance of a class</strong>. Lets follow the hyperlink in the definition of Dependency Injection and see what an ‘object’ is according to Wikipedia.</p><blockquote>In computer science, an object can be a variable, a data structure, or a <strong>function</strong> or a method, and as such, is a location in memory having a value and possibly referenced by an identifier.</blockquote><p>The ‘<strong>function</strong>’ part is what I’m interested in. Nowadays functional is all the cool kids talk about. And lately, with all the Swift features it makes more sense every day to leave some of those old OOP paradigms behind and do the <strong>functional dance</strong>.</p><p>That’s why I wanted to write about how we should approach dependency injection in a functional way. What if the ‘object’ you are trying to pass dependencies to is <strong>not an instance</strong> of a class, but a function? Not a method either, a <strong>free function</strong> which doesn’t have access to any instance variables you can use to hold references to those injected properties.</p><p>A <strong>pure function</strong> in a sense that it just has parameters and a return value, it doesn’t perform any side effects and it can’t access any global variables, and in consequence <strong>it always gives the same results for the same input values</strong>.</p><p>Following there are some of the techniques I tried and a brief explanation of each of them. Which one is the best will probably, to some extent, depend on your needs.</p><h4>About the examples</h4><p>The code as it is will probably make <strong>no sense</strong> in a real application. We are, apparently, working with a network API that returns its results synchronously. This is just for the sake of simplicity, in real life you should use a method (such as Observables) to get those results in a <strong>asynchronous</strong> manner.</p><p>These are the structs and classes we will use in the following examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f575d620f01bf54c7328a14194293fd/href">https://medium.com/media/1f575d620f01bf54c7328a14194293fd/href</a></iframe><h3>ServiceLocator</h3><p>The first way to get a free function to have access to its dependencies <strong>disqualifies</strong> itself for several reasons, but I think its worth a thought anyway.</p><p>The idea behind the Service Locator pattern is to have a central structure in which dependencies <strong>get registered</strong> and can be queried for any time later. The idea is that those dependencies will implement an <strong>interface</strong> and by registering one or another we can change dependencies easily even at runtime.</p><p>There are many ways you can implement the Service Locator, but the usage will be more or less the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a37e0ecaf34469a00e3027b6bbe46b5/href">https://medium.com/media/3a37e0ecaf34469a00e3027b6bbe46b5/href</a></iframe><p>This all looks fine at first, we are injecting the dependencies, the object that receives them doesn’t know how to build them and it doesn’t even know which specific object it’s getting. It provides <strong>separation of concerns</strong>.</p><p>But this also goes against the behavior we were aiming at regarding the use of pure functions. We are getting <strong>global access</strong> to an instance so we can’t guarantee no side effects are happening.</p><p>Also we are making the dependency <strong>implicit</strong>. There’s nothing on the function signature that tells us it needs a dependency. The user of the function, somehow, has to know it needs that dependency and also how to register it. That could also be a big source of <strong>headaches</strong>.</p><p>In a way we are just displacing the dependency to a dependency on the Service Locator itself, which we are tightly coupled to.</p><p>Where does it make sense to use Service Locator? Well, maybe in really <a href="https://en.wikipedia.org/wiki/Cross-cutting_concern">cross cutting concerns</a>, like <strong>logging</strong>. We might want to be able to replace the standard logging output anytime, but it doesn’t really make sense to pass it around, as it’ll <strong>pollute the API</strong>, make the code harder to read and it really doesn’t have any advantages.</p><p>We could use Service Locator for that, but really we should find a better way. Let’s move on.</p><h3>Bastard Injection</h3><p>The name is usually attributed to a kind of <strong>constructor injection</strong> in OOP, but I think this works in a very similar way with functions, and I liked the name, so…</p><p>The basic idea is to have <strong>two function signatures</strong>, one which requires a dependency as one of its parameters, and one which doesn’t and uses a default object for that dependency. In Swift that can be easily done with a <strong>default value</strong> for that argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3e83c27433f66e1ded6d85ef4a81290/href">https://medium.com/media/f3e83c27433f66e1ded6d85ef4a81290/href</a></iframe><p>The problem with this approach is basically that, even if you are using a protocol as the type of the dependency, we are <strong>coupling</strong> the function with the default implementation of the dependency. So you’ll have to be careful with that, it’ll make more sense if the dependency is something <strong>local</strong> to the function, meaning something from the same module or layer of the application.</p><p>It won’t be a good idea to use this kind of injection if the dependency is something <strong>external</strong> to the function, as you will have to carry around that dependency wherever you wanted to use that function. So <strong>code reuse</strong> will be harder. Imagine trying to reuse some class in another project but being forced to also import some other dependencies that have nothing to do with your current usage of that class, just because they are set as the default dependency.</p><p>Also this will get <strong>complicated</strong> if the injected dependency has other dependencies itself or any other parameters that need to be passed to the constructor.</p><p>In the example above it may be ok to use this kind of dependency injection, maybe it’s not the best approach, but it is passable, as the load function will always require a service to load it from. So we can have a clean function signature and at the same time it’ll be easy to replace that dependency for something else if necessary.</p><p>But in any case, deciding if it is ok to couple the function with the default dependency is a <strong>hard call</strong>. In general, the less the code is coupled, the better. Also, this is not a very “functional” approach, so let’s look for something else.</p><h3>Currying</h3><p>Currying is a technique consisting in <strong>breaking a function</strong> that takes multiple arguments into multiple functions that each take one of those arguments and are evaluated <strong>sequentially</strong>.</p><p>If you’ve been following Swift 3.0 news, you probably heard something about currying getting <strong>deprecated</strong>. Fortunately. it is not deprecated, is just one of its syntaxes which is being <a href="https://www.google.es/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=swift%203%20currying">removed</a>.</p><p>Currying will still work like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6cf71c24432f228c0b3d962314c0f75/href">https://medium.com/media/f6cf71c24432f228c0b3d962314c0f75/href</a></iframe><p>As you can see the function <em>addNumbers</em> returns another function with the signature <em>(Int) -&gt; Int</em>. This second function will sum its argument with the argument passed to addNumbers. This way we can create a function that always sums 3 to whatever argument we pass to it.</p><p>We are using two Ints in that example, but those arguments can be <strong>anything</strong>, they don’t have to be of the same type. The great part is we’ll have access to both of them when the <strong>inner function</strong> is executed. See how that can help us inject a dependency?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e67d19d3167c5f567e0d94823bfd268/href">https://medium.com/media/2e67d19d3167c5f567e0d94823bfd268/href</a></iframe><p>Maybe in the code above it is not easy to see the advantages of this approach. But imagine having the invocation to <em>loadUser</em> in the view controller, for example, and the dependency to the service in another class. The view controller won’t have any <strong>knowledge</strong> of the actual service doing the request. And that is exactly what we aim for, <strong>decoupling</strong>.</p><h4>On parameter order</h4><p>As a side note, this example surprised a friend of mine (who wants to remain anonymous) when I showed it to him. As he would do it <strong>swapping</strong> the userId and Service parameters. So first we get a function for a specific Service and then we call that function with some userId. The signature of the function being <em>func loadUser(service:Service) -&gt; (String) -&gt; User?</em>.<br>This distinction is important as it’ll make the next technique easier to understand if you get this right.</p><p>So, we have two possible signatures, both of them having similar implementations as the one described before.</p><pre>func loadUser(userId:String) -&gt; (Service) -&gt; User?<br>//or<br>func loadUser(service:Service) -&gt; (String) -&gt; User?</pre><p>The first one can be used as</p><pre>let loadUserAction = loadUser(userId:”0001&quot;)<br>//then<br>let user = loadUserAction(WebService())</pre><p>Which can be read as, first create an action to get a specific user, and then run that action with this <strong>environment</strong> (the WebService).</p><p>The second one can be use like this</p><pre>let loadUserAction = loadUser(service:WebService())<br>//then<br>let user = loadUserAction(“0001”)</pre><p>And can be read as, first create an action that will be run in a specific environment, and then execute that action for a particular userId.</p><p>Both approaches are valid, using one or the other will ultimately depend on the <strong>usage</strong> you are giving to that function. In my case, it makes sense to generate those functions as complete actions and <strong>dispatching</strong> them to a store where the service will be injected and the function executed, but it’s a matter of personal preference.</p><p>Also, the first approach will help you better understand the following technique.</p><p>Is this <strong>functional</strong> enough for you? Well, we still can go another step farther into the functional world.</p><h3>Reader Monad</h3><p>Boom! The “M” word in a dependency injection article. Well, that “functional” in the title should have given you a hint. But, anyway, this is not an article about <strong>monads</strong>, if you want to learn about them in Swift you should read <a href="http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/">this</a>.</p><p>For our purpose, let’s just think of monads as <strong>wrappers</strong> that contain some kind of value, together with some <strong>methods</strong> defined on it. The methods to be precise, are <strong><em>map</em></strong> and <strong><em>flatMap</em></strong>. Let’s see what they do.</p><p>One of the most popular monads in Swift is the <strong>Optional</strong> type. As you know, an Optional is just an enum which contains a value and implements the two methods needed to be considered a Monad.</p><p>You can take a look at the signatures of <em>map</em> and <em>flatMap</em> in Optional to see what they do. Optional defines the type of the value it wraps as <strong>Wrapped</strong>.</p><pre>func map&lt;U&gt;(transform: (Wrapped) throws -&gt; U) -&gt; U?<br>func flatMap&lt;U&gt;(transform: (Wrapped) throws -&gt; U?) -&gt; U?</pre><p>The <em>map</em> method gets a function from Wrapped to another type and returns an Optional of the second type (that is, the second type wrapped). The <em>flatMap</em> method gets a function from Wrapped to an Optional of another type and returns an Optional of the second type.</p><p>So with map we can <strong>transform</strong> the wrapped value and with flatMap we can do the same even if the function that transforms that value returns an Optional itself. Both functions <strong>result in another Optional</strong>, which make them easy to <strong>chain</strong>.</p><p>If we were to build our own Optional type, it would look similar to this (let’s call it <em>Maybe</em> in order to not collide with Swift types):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/793b7018b3c2fe21dd7ba2258089cbfd/href">https://medium.com/media/793b7018b3c2fe21dd7ba2258089cbfd/href</a></iframe><p>This type of construct happens to be very useful, allowing us to chain transformations to any Optional, using either <em>map</em> or <em>flatMap</em> when needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bff1a51a587d57816ec354db30b8190/href">https://medium.com/media/7bff1a51a587d57816ec354db30b8190/href</a></iframe><p>Ok, now that we know, at least in an <strong>informal</strong> though very <strong>practical</strong> way, what a Monad is, let’s talk about the <strong>Reader Monad</strong>.</p><p>The Reader Monad is just like the Optional type, but the wrapped value is a <strong>function</strong> and the transformations change the <strong>return value</strong> of that function. It also offers a method to get the result of that function given an input parameter (that is, to <strong>run</strong> the function).</p><p>It’s called the Reader Monad because it reads values from a shared <strong>environment</strong>. It’s also sometimes called Environmental Monad.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afc4a894526e709db0ab10696ebe4c2d/href">https://medium.com/media/afc4a894526e709db0ab10696ebe4c2d/href</a></iframe><p>Comparing the code for the Reader Monad together with the one of the Optional, is easy to see the <strong>similarities</strong>. I hope this makes the Reader Monad a little less mysterious now.</p><p>This is how we will use it with the API example we are working with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f34a704e56102834d752adadc88767/href">https://medium.com/media/c8f34a704e56102834d752adadc88767/href</a></iframe><p>As with the Currying example, the real advantage of this comes when you have the creation of the ‘loadUser’ function and the injection of the dependency in <strong>different modules</strong>.</p><p>We can even, as with the Optional type, use <em>map</em> or <em>flatMap</em> to transform values or chain calls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88a66e1858fcb12a16d17f10692f87fb/href">https://medium.com/media/88a66e1858fcb12a16d17f10692f87fb/href</a></iframe><p>Look mum, I’m using monads! As you can see, this is a highly functional approach. It’s not too complicated, and it has great <strong>advantages</strong> in the usage of <em>map</em> and <em>flatMap</em>. But it’ll probably fit best in a code base that it’s already buying the functional product. It may be a little hard to understand for new comers if you present them with this out of the blue in a very OOP app.</p><p>You may think this is not a big change with respect to the currying technique, but, oh boy!, the Reader Monad can take us much farther. We can define more methods for our monads that will allow us to make some powerful operations just by <strong>combining</strong> simple blocks. For example we can use <strong>zip</strong> to combine two Reader Monads</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58738177aaf6d51fd52bd21b368ca69b/href">https://medium.com/media/58738177aaf6d51fd52bd21b368ca69b/href</a></iframe><p>There are more opportunities to improve your code once you are using monads, but we’ll talk about that in a future article.</p><h3>Conclusion</h3><p>I hope this was a good review of the different <strong>techniques</strong> at our disposal when approaching dependency injection in a functional environment. Other than the first two, which have very <strong>limited recommended applications</strong>, the decision between using currying or the Reader Monad is very personal and it will ultimately depend on the project and the team you are working with.</p><p>Currying is very simple to understand, and while the Reader Monad doesn’t add too much <strong>complexity</strong>, it might seem a little bit <strong>daunting</strong> at the first. But on the other hand, if used properly it’ll add lots of <strong>functional programming resources</strong> to your code. But that is probably material for another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a6143634ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>