<?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 Pallás on Medium]]></title>
        <description><![CDATA[Stories by Ricardo Pallás on Medium]]></description>
        <link>https://medium.com/@PallasR?source=rss-e5aeacf306d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*U-Jq5-JRByBnhVLA.jpeg</url>
            <title>Stories by Ricardo Pallás on Medium</title>
            <link>https://medium.com/@PallasR?source=rss-e5aeacf306d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:27:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@PallasR/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[Functional architecture for Swift]]></title>
            <link>https://medium.com/hackernoon/functional-architecture-for-swift-dfa8854239cb?source=rss-e5aeacf306d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa8854239cb</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[architecturekit]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ricardo Pallás]]></dc:creator>
            <pubDate>Wed, 03 Jan 2018 16:42:17 GMT</pubDate>
            <atom:updated>2019-05-13T04:48:41.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rHrtpuEEnQj19mOUpS-pQ.png" /></figure><p>In this post I am going to introduce a library for architecting iOS apps, called ArchitectureKit:</p><blockquote>“Simplest architecture for FunctionalKit”</blockquote><h3>Table of contents</h3><ol><li>Introduction</li><li>Motivation</li><li>ArchitectureKit</li><li>Dependency Injection</li><li>Full example</li><li>Conclusion</li></ol><h3>1. Introduction</h3><p><a href="https://github.com/RPallas92/ArchitectureKit">ArchitectureKit</a> is a library that tries to enforce correctness and simplify the state management of applications and systems. It helps you write applications that behave consistently, and are easy to test. It’s strongly inspired by <a href="https://redux.js.org/">Redux</a> and <a href="https://github.com/NoTests/RxFeedback.swift">RxFeedback</a>.</p><h3>2. Motivation</h3><p>I have been trying to find a proper way and architecture to simplify the complexity of managing and handling the state of mobile applications, and also, easy to test.</p><p>I started with <a href="https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html">Model-View-Controller</a> (MVC), then <a href="https://msdn.microsoft.com/en-us/library/hh848246.aspx">Model-View-ViewModel</a> (MVVM) and also <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">Model-View-Presenter</a> (MVP) along with <a href="https://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/">Clean architecture</a>. MVC is not as easy to test as in MVVM and MVP. <strong>MVVM and MVP are easy to test</strong>, but the issue is the <strong>UI state can be a mess</strong>, since there is not a centralized way to update it, and you can have lots of methods among the code that changes the state.</p><p>Then it appeared <a href="https://guide.elm-lang.org/architecture/">Elm</a> and <a href="https://redux.js.org/">Redux</a> and other Redux-like architectures as <a href="https://github.com/redux-observable/redux-observable">Redux-Observable</a>, <a href="https://github.com/NoTests/RxFeedback.swift">RxFeedback</a>, <a href="https://cycle.js.org/">Cycle.js</a>, <a href="https://github.com/ReSwift/ReSwift">ReSwift</a>, etc. The main difference between these architectures (including ArchitectureKit) and MVP is that they <strong>introduce constrains of how the UI state can be updated, in order to enforce correctness and make apps easier to reason about.</strong></p><p>Which make ArchitectureKit different from these Redux-like architectures is it uses feedback loops to run effects and encodes them into part of state (we will see this in point 3) and uses monads from FunctionalKit to wrap the effects.</p><p><strong>ArchitectureKit runs </strong><a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)"><strong>side effects</strong></a><strong> for you. Your code stays 100% pure.</strong></p><h3>3. ArchitectureKit</h3><p>ArchitectureKit itself is very simple.</p><h4>The core concept</h4><p>Each screen of your app (and the whole app) has a state itself. in ArchitectureKit, this state is represented as and object (i.e. Struct). For example, the state of a TO-DO app might look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4f2ba1139611c52f1b9124168a3bb7d/href">https://medium.com/media/c4f2ba1139611c52f1b9124168a3bb7d/href</a></iframe><p>This State object, representes the state of the “List of TO-DOs screen” in a TO-DO app. The “todos” var contains all the to-dos that might be drawn in the screen and “visibilityFilter” tells what todos should appear in the list.</p><p>With this approach of having an object that actually represents the state of a screen, <strong>views are a direct mapping of state</strong>:</p><blockquote>view = f(state)</blockquote><p>That “f” function will be the UI binding function that we will see later on.</p><p>To change something in the state, you need to dispatch an <strong>Event</strong>. An event is an enum that describes what happened. Here are a few example events:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96eeefe8c41b852d3da35657cd669e5a/href">https://medium.com/media/96eeefe8c41b852d3da35657cd669e5a/href</a></iframe><p>Enforcing that every change is described as an event lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Events are like breadcrumbs of what has happened. Finally, to tie state and actions together, we write a function called a reducer. A reducer it’s just a function that takes state and action as arguments, and returns the next state of the app:</p><blockquote><strong>(State, Event) -&gt; State</strong></blockquote><p>We write a reducer for every state of every screen. For the list of todos’ screen:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0a4b4cc0dd23e96699169f0c2f867d3/href">https://medium.com/media/c0a4b4cc0dd23e96699169f0c2f867d3/href</a></iframe><p>Notice that the reducer is a pure function, in terms of <a href="https://en.wikipedia.org/wiki/Referential_transparency">referencial transparency</a>, and for state S and event E, it always return the same state, and has no side effects.</p><p>This is basically the whole idea of ArchitectureKit. Note that we haven’t used any ArchitectureKit APIs. It comes with a few utilities to facilitate this pattern, but the main idea is that you describe how your state is updated over time in response to events, and 90% of the code you write is just plain Swift, so the UI logic can be tested with ease.</p><p>But what about asynchronous code and side effects as API calls, DB calls, logging, reading and writing files?</p><h4>AsyncResult and FunctionalKit</h4><p>The <a href="https://github.com/RPallas92/ArchitectureKit/blob/master/ArchitectureKit/AsyncResult.swift"><strong>AsyncResult</strong></a><strong> </strong>data structure is used for handling asynchronous operations. AsyncResult is just a typealias to a Reader&lt;Future&lt;Result&gt;&gt; monad stack. These monads (and its monad transformers) are available in <a href="https://github.com/facile-it/FunctionalKit">FunctionalKit</a>, which is the only dependency in ArchitectureKit.</p><p>FunctionalKit provides basic functions and combinators for functional <a href="https://hackernoon.com/tagged/programming">programming</a> in <a href="https://hackernoon.com/tagged/swift">Swift</a>, and it can be considered a extension to Foundation. We mainly use the Reader monad along with the Future and Result.</p><ul><li><a href="https://github.com/facile-it/FunctionalKit/blob/master/Sources/FunctionalKit/ReaderType.swift"><strong>Reader monad:</strong></a><strong> </strong>it is used in the top of the monad stack to provide a way to inject dependencies. We will see it in depth later.</li><li><a href="https://github.com/facile-it/FunctionalKit/blob/master/Sources/FunctionalKit/FutureType.swift"><strong>Future monad:</strong></a> it is used to represent async values.</li><li><a href="https://github.com/facile-it/FunctionalKit/blob/master/Sources/FunctionalKit/ResultType.swift"><strong>Result monad:</strong></a> it represents if a computation was successful or there was an error.</li></ul><p>We use monad transformers to create AsyncResult as a stack of these three monads. <strong>An AsyncResult is a monad that represents an asynchronous operation that returns either a successful value or an error, and also provides a mechanism for dependency injection.</strong></p><p>We can see in the following snippet an example of Facebook login using AsyncResult:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7cd5542a0cabeda14efca0a2d48ce3f/href">https://medium.com/media/b7cd5542a0cabeda14efca0a2d48ce3f/href</a></iframe><p>To create an AsyncResult we use its static method unfoldTT (the TT stands for transformer, since it is a monad transformer). It expects a function as a parameter which has two inputs: an environment or context and a continuation or callback. The environment parameter comes from the Reader monad and it is an object that contains the injected dependencies. The continuation parameter is a callback function that must be called with the Result value returned from de async operation. In the example the Result returns an string when it succeeds. When the login succeeds, we call the continuation method with a successful Result with the token from Facebook. It the login fails, we call the continuation method with a failure Result that contains the error.</p><p>The AsyncResult must me parameterized with 3 values. First one is the Environment type (which contains the dependencies), second one is the actual value expected from the async operation (in the example we use string because we expect the Facebook login to return the login token), and the last one is the error type the Result will return if something goes wrong.</p><p>Every asynchronous operation and side effect must be performed using the AsyncResult monad and we will use Feedbacks from ArchitectureKit to execute the their side effects. Also, we will see how to work with AsyncResults in the full example.</p><h4>Design feedback loops</h4><p>Let’s add a new feature to our previous TO-DO app! We want let users to save their TO-DOs to the cloud. That would require an network call, which is a side effect and it is asynchronous, so to achieve it, we will use feedback loops. The way of dealing with effects in ArchitectureKit is encode them into part of state and then design the feedback loop.</p><p>A feedback loop is just a computation that is triggered in some cases, depending on the current state of the system, that launches a new event, and produces a new state.</p><p>A whole ArchitectureKit loop begins from a <a href="https://github.com/RPallas92/ArchitectureKit/blob/master/ArchitectureKit/UserAction.swift">UserAction</a> that triggers an event. Then the reducer function computes a new state from the event and previous state. ArchitectureKit checks if any feedback loop must be triggered from the new state. If so, the feedback produces a new event asynchronously (by executing side effects) and a new state if computed from the feedback’s event.</p><p>So, we can see a whole ArchitectureKit loop as the following sequence:</p><ol><li>UserAction produces an event.</li><li>reducer(Current state, event) -&gt; new state.</li><li>Query new state to check if feedback loop must be triggered.</li><li>if so, new event triggered (side effects executed).</li><li>reducer(new state, new event) -&gt; newer state.</li><li>Repeat from step 3 until no more feedback (or maximum of 5 feedback loops)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*HHbqRbOi9HHBrbwFahoCAQ.png" /><figcaption>ArchitectureKit whole loop</figcaption></figure><p>In the following code snippet, we can see a Feedback example of how to store the user’s TO-DOs in the cloud:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62d1aa262577c6e3020ed83755e38d50/href">https://medium.com/media/62d1aa262577c6e3020ed83755e38d50/href</a></iframe><p>For implementing this feature, two new events have been added storeTodos() and todosStored(Bool) and there is a new Bool variable in the state: mustStoreTodos. The storeUserTodos(todos:[Todo]) function is the function executed in the feedback loop, which returns an AsyncResult monad that returns the todosStored(Bool) event when side effects are executed. This function is in charge of storing the user’s TO-DOs.</p><p>A Feedback object is composed by two functions that receive the current state as parameter. The first function is the actual AsyncResult to be executed, and the second one checks when the feedback loop must be executed, depending on the state. In the example, the user’s TO-DOs feedback will be executed when mustStoreTodos variable is true.</p><p>In the new reducer, the storeTodos() event is setting mustStoreTodos to true, and todosStored(Bool) is setting it back to false. The storeTodos() event will be triggered by an UserAction, like tapping a button.</p><p>The following diagram illustrates the steps for storing the user’s TO-DOs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*gs6P6pEHxK6_iSNNaV4WbQ.png" /><figcaption>How Feedback loop is executed after an UserAction</figcaption></figure><h4>Who dispatches events? UserActions</h4><p><a href="https://github.com/RPallas92/ArchitectureKit/blob/master/ArchitectureKit/UserAction.swift">UserAction</a> is the object from ArchitectureKit that represents any action from the User or the iOS framework that triggers an event that changes the state (and from that state change it could trigger a feedback loop).</p><p>It has two methods:</p><ul><li>init: creates the UserAction and specifies what event will be triggered when user actions is executed</li><li>execute: executes the user action.</li></ul><h4>Simple example</h4><p>We can see here a simple example of how ArchitectureKit’s code would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5872bf4005bbbccaa40de658c1501386/href">https://medium.com/media/5872bf4005bbbccaa40de658c1501386/href</a></iframe><p>It’s a simple counter with an increment and decrement buttons. The State is just an integer that contains the current count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Mk6XqMNScFYorwUbdrHEuQ.gif" /></figure><h3>Dependency injection</h3><p>For Dependency Injection we are gonna be using the <a href="https://github.com/facile-it/FunctionalKit/blob/master/Sources/FunctionalKit/ReaderType.swift"><strong>Reader monad</strong></a> that is at the top level in our AsyncResult monad stack.</p><p><strong>The Reader wraps a computation with the type </strong><strong>(D) -&gt; A , and enables composition over computations with that type</strong>.</p><p>D stands for the <em>“Reader context”</em>, and it represents the dependencies needed for the computation to run. It also automatizes dependency passing all the way down, since it does it by itself thanks to the way Readers compose all together.</p><p>So, it defers computations at all levels, since it wraps computations and also injects dependencies by automatically passing those across the different function calls.</p><p>The approach is to create a Swift struct (that I call Context) with all needed dependencies and pass that object when running the Reader (AsyncResult) computation. In the following example we can see how to inject dependencies in ArchitectureKit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c43cc93a93f4a341419fed26f9446e/href">https://medium.com/media/96c43cc93a93f4a341419fed26f9446e/href</a></iframe><p>As you can see in the previous snippet, a<strong> </strong>BaseContext protocol is defined with the required dependencies that the AppContext class will have. In that class, we add the app’s global dependencies. Then we create a context class for each screen, like TodoListContext . It extends from the AppContext and includes specific dependencies for the TO-DOs list screen, such the view.</p><p>If we want to test the deleteAllTodosFromDatasource feedback, we can create a test context with a mock datasource and a mock view. With this approach we can also configure different contexts for each server environment: production, staging, test, development.</p><p>In the next section, we will see a full example where we are using different context for testing the app and the actual code.</p><p>You can see more about Dependency Injection with Reader Monad (in Kotlin for Android) in this Jorge Castillo’s article:</p><p><a href="https://medium.com/@JorgeCastilloPr/kotlin-dependency-injection-with-the-reader-monad-7d52f94a482e">Kotlin Dependency Injection with the Reader Monad</a></p><h3>Full example</h3><p>I created a simple but fully working app using both ArchitectureKit and FunctionalKit to illustrate how to use the library and how to architect the app itself. You can find the app’s <a href="https://github.com/RPallas92/FunctionalSwiftArchitecture"><strong>source code here</strong></a><strong>.</strong></p><p>The app is about jokes about Chuck Norris, retrieved from <a href="https://api.chucknorris.io/">this API</a>. The first screen shows a list with joke categories. When user taps on one category, a new screen appears with a random joke of that category. We can see some screenshots (disclaimer: I didn’t put any effort on the UI):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*HemBeCCveFEzS1tcw6Eg4Q.png" /><figcaption>List of joke categories screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*3anCI9QHCSpW-fCmPBB58w.png" /><figcaption>Custom joke detail screen</figcaption></figure><p>In the following image we can see the layers the app is divided in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*2E83juFItwgZqX-jouJfqw.png" /></figure><p>It is divided in:</p><ul><li><strong>Data</strong>: where we use the repository pattern</li><li><strong>Domain</strong>: Here there are domain objects, services, and use cases.</li><li><strong>Presentation: </strong>We can found the presentation logic (ArchitectureKit)</li><li><strong>View</strong>: the views of the app (ViewControllers)</li><li><strong>DI: </strong>we define the <em>Context</em> objects needed for Dependency Injection</li></ul><p>If you took a look into the <a href="https://github.com/RPallas92/FunctionalSwiftArchitecture/tree/master/FunctionalSwiftArchitectureTests">tests folder</a> you will see how we are injecting dependencies, and how easy is to test the whole app using a very simple mock view.</p><h3>Conclusion</h3><p>I would use ArchitectureKit as architecture for the View layer in a Clean architecture approach, replacing Model View Presenter. Also, I would architect the app with <em>Functional</em> Clean Architecture instead of OOP Clean Architecture. Trying to use functions over classes when possible, using the AsyncResult monad to keep your code pure, encoding side effects, injecting dependencies, take advantage of functional transformations… <strong>I think </strong><a href="https://github.com/RPallas92/FunctionalSwiftArchitecture"><strong>FunctionalSwiftArchitecture</strong></a><strong> is a good example of how I would make an app from scratch.</strong></p><p>The <strong>advantages</strong> I see in ArchitectureKit are:</p><ul><li><strong>Your code stays 100% pure.</strong> All side effects are executed by ArchitectureKit itself.</li><li>All changes in state are easy to reason about and helps correctness.</li><li>View is a direct mapping from state.</li><li>Easy to test, all business logic are isolated thanks to Clean Architecture and UI logic is pure Swift code. And dependency injection mechanism ArchitectureKit provides, makes apps easier to test.</li><li>Simple library with a few concepts.</li></ul><h4>Next steps</h4><p>I am planning to improve the UserAction mechanism. And creating a specific UserAction for every UIKIt control.</p><p>I will refactor the library and change it if new uses cases appear.</p><h4>Acknowledgments</h4><p>I want to say thank you to <a href="https://medium.com/u/fc39ebe507ff">Jesús Manuel López Martínez</a> and <a href="https://medium.com/u/d278e9977263">Jose Luis Alcala</a> for helping me with ArchitectureKit’s codebase and helping me writing this article.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa8854239cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/functional-architecture-for-swift-dfa8854239cb">Functional architecture for Swift</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional data validation in Swift]]></title>
            <link>https://medium.com/hackernoon/functional-data-validation-in-swift-2cf2c28d55cd?source=rss-e5aeacf306d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf2c28d55cd</guid>
            <category><![CDATA[swiftz]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[semigroup]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[applicative-functor]]></category>
            <dc:creator><![CDATA[Ricardo Pallás]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 11:52:51 GMT</pubDate>
            <atom:updated>2019-05-13T04:48:42.152Z</atom:updated>
            <content:encoded><![CDATA[<p>I am going to talk about a little library I created in Swift to be used either standlone or with <a href="https://github.com/typelift/Swiftz">Swiftz</a> lib. It is called <a href="https://github.com/RPallas92/Swiftz-Validation"><strong>Swiftz-Validation.</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*gfmaVQKjba0As4J_Bdo5vQ.png" /></figure><h4>What is Swiftz-Validation?</h4><p>It’s a data structure that typically models form validations, and other scenarios where you want to aggregate all failures, rather than short-circuit if an error happens (for which Swiftx’s Either is better suited). A Validation may either be a Success(value), which contains a successful value, or a Failure(value), which contains an error.</p><p>A Validation is a data structure that implements the Applicative interface (.ap), and does so in a way that if a failure is applied to another failure, then it results in a new validation that contains the failures of both validations. In other words, Validation is a data structure made for errors that can be aggregated, and it makes sense in the contexts of things like form validations, where you want to display to the user all of the fields that failed the validation rather than just stopping at the first failure.</p><p>Validations can’t be as easily used for sequencing operations because the.ap method takes two validations, so the operations that create them must have been executed already. While it is possible to use Validations in a sequential manner, it&#39;s better to leave the job to <a href="https://github.com/typelift/Swiftx/blob/master/Sources/Either.swift">Either</a>, a data structure made for that.</p><h4>Validating data example</h4><p>In the following example we are going to validate a password: it should contain more than 8 characters, it should contain an especial character and it has to be different from the user name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d0754b78570920fa5939e411a29072c/href">https://medium.com/media/5d0754b78570920fa5939e411a29072c/href</a></iframe><h3>Advantages of using Swiftz-Validation</h3><p>Things like form and schema validation are pretty common in <a href="https://hackernoon.com/tagged/programming">programming</a>, but we end up either using branching or designing very specific solutions for each case.</p><p>With branching, I mean using if-else conditions, things get quickly out of hand, it doesn’t scale because it’s difficult to abstract over it and it’s hard to reason about each rule. Let’s see an example of the same validation as before, using branching:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8acc41b9d9950c0121c2c82f2bb65dd/href">https://medium.com/media/b8acc41b9d9950c0121c2c82f2bb65dd/href</a></iframe><p>Because this function uses if conditions and modifies a local variable it&#39;s not very modular. This means it&#39;s not possible to split these checks in smaller pieces that can be entirely understood by themselves — they modify something, and so you have to understand how they modify that thing, in which context, etc. For very simple things it&#39;s not too bad, but as complexity grows it becomes unmanageable.</p><h4>Advantages</h4><p>The main advantages of Swiftz-Validation is that:</p><ul><li>Easy to understand and reason about each validation in its own</li><li>Easy to compose validation rules</li><li>Easy to reuse validation rules and compose more complex validations <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">(DRY principle)</a></li><li>It has a well know interface or abstraction to work with (It is a functor, pointed, applicative and a semigroup). So you can combine validations with <strong>sconcat (Semigroup)</strong>, apply functions with <strong>ap (Applicative)</strong>, transform results with <strong>fmap (Functor) </strong>and react to results with some kind of pattern matching with a <strong>switch</strong> statement.</li></ul><p>In the following example, you can see how the Validation structure gives you a <a href="https://hackernoon.com/tagged/tool">tool</a> for basing validation libraris and functions on in a way that’s reusable (DRY) and composable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/848a643acd25670a155465cff82f520c/href">https://medium.com/media/848a643acd25670a155465cff82f520c/href</a></iframe><h3>How to use the library</h3><p>The Validation lib is implemented as an <strong>enum</strong> with two cases:</p><ul><li><strong>Success</strong>(successValue) — represents a successful value.</li><li><strong>Failure</strong>(failureValue) — represents an unsuccessful value.</li></ul><p>Validation functions just return one of these two cases instead of throwing errors or mutating other variables. The keys of working with Validations are:</p><ul><li><strong>Combining validations:</strong> sometimes we want to create very complex validation rules. They key is to create simple reusable and composable validations in ther own and combine them into a complex validation structure.</li><li><strong>Transforming validations values:</strong> Sometimes we get a Validation value that is not what we are looking for. We don&#39;t really want to change anything about the status of the validation (whether it passed or failed), but we&#39;d like to tweak the <em>value</em> a little bit. This is the equivalent of applying functions in an expression.</li><li><strong>Reacting to validations results:</strong> Once we have the validation results, we need a way to react accordingly if the value is a success or a failure.</li></ul><p>Now, we are going to see some examples:</p><p><strong>Combining validations</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7d1e2d4948806c2aff5c04e57950490/href">https://medium.com/media/e7d1e2d4948806c2aff5c04e57950490/href</a></iframe><p><strong>Transforming validation values</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/282d25616b9e851a8ec51299d49bf3a5/href">https://medium.com/media/282d25616b9e851a8ec51299d49bf3a5/href</a></iframe><p><strong>Reacting to validation results</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f899656f4e47fba4f1fc05c69e36a4c7/href">https://medium.com/media/f899656f4e47fba4f1fc05c69e36a4c7/href</a></iframe><h3>Conclusion</h3><p>I wrote this lib as an personal experiment since the core SwiftZ library doesn’t include a similar data structure and I think it is a very important one, because validation is pretty common in every sowftware program. The lib is still work in progress but it can be used with SwiftZ or standalone. I would add more operations like liftA3 and similar.</p><p>Feel free to pull request the repo and improve it, thanks!.</p><p>The lib it’s inspired by the Validation Package for Haskell: <a href="https://hackage.haskell.org/package/Validation">https://hackage.haskell.org/package/Validation</a></p><p><strong>Acknowledgements</strong></p><ul><li>Thanks to <a href="https://medium.com/u/d278e9977263">Jose Luis Alcala</a> for helping me with Swift and SwiftZ.</li><li>Thanks to @jlopez_rz for helping me with test cases.</li><li>Thanks to <a href="https://medium.com/u/ca42497956b9">Jorge Aznar </a>for helping me writing this article.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf2c28d55cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/functional-data-validation-in-swift-2cf2c28d55cd">Functional data validation in Swift</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Awesome functional programming en JavaScript — Spanish version]]></title>
            <link>https://medium.com/@PallasR/awesome-functional-programming-en-javascript-spanish-version-76886466501e?source=rss-e5aeacf306d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/76886466501e</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ramda]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sanctuary]]></category>
            <dc:creator><![CDATA[Ricardo Pallás]]></dc:creator>
            <pubDate>Thu, 31 Aug 2017 21:41:58 GMT</pubDate>
            <atom:updated>2017-09-01T06:36:08.064Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript es un lenguaje de programación multi-paradigma, casi siempre utilizado orientado a objetos, aunque debido a su gran popularidad, se podría decir que es el lenguaje de programación funcional (<strong>FP</strong>) más utilizado.</p><p><strong><em>Disclaimer:</em></strong><em> Este artículo no pretende enseñar ni introducir en profundidad la programación funcional, sino que es una guía de bibliotecas y recursos, para poder utilizar la mayoría de herramientas y capacidades que da el estilo de programación funcional en JavaScript.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*5Ma0Z2oOwOsyJFAwT43kMg.png" /><figcaption>Lambda — Representa el <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>, base de la programación funcional.</figcaption></figure><h4>¿Qué es la programación funcional?</h4><p>Empecemos con una breve introducción de la programación funcional para ponernos en contexto.</p><p>La programación funcional es un paradigma de programación que se basa en funciones modeladas como funciones matemáticas. La esencia de la programación funcional es que los programas son una combinación de expresiones. Las expresiones pueden ser valores concretos, variables o funciones. Las funciones se pueden definir de forma más específica: son expresiones a las cuales se les aplica un argumento o entrada, y una vez aplicadas, se pueden <strong>reducir</strong> o <strong>evaluar</strong>. En los lenguajes funcionales y lenguajes modernos, las funciones son ciudadanos de primer clase: se pueden utilizar como valores o pueden ser pasadas como argumentos, o entradas, a otras funciones.</p><p>Cabe destacar que, los lenguajes puramente funcionales, están todos basados en el <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>.</p><h4>¿Por qué JavaScript?</h4><p>Ciertamente, no es el mejor lenguaje para hacer FP, siendo que la corriente actual suele programar en JavaScript de forma imperativa. Además, no es un lenguaje de programación funcional <a href="https://www.fpcomplete.com/blog/2017/04/pure-functional-programming">puro</a>, y es débilmente y dinámicamente tipado 😥.</p><p>Sin embargo, sus puntos a favor son:</p><ul><li>Es uno de los lenguajes más utilizados en la industria y seguramente trabajes con él.</li><li>Lo más probable, es que ya sepas programar en JavaScript. No tienes que aprender un lenguaje nuevo.</li><li>Con la ayuda de bibliotecas puedes utilizar muchas de las herramientas de la FP.</li></ul><h3>Bibliotecas (que facilitan la programación funcional)</h3><p>Voy a hablar, en este punto, de unas pocas bibliotecas, que he elegido y utilizado para FP en JavaScript.</p><h4>Sanctuary</h4><p>La primera de ellas (y mi favorita) es <a href="https://sanctuary.js.org/">Sanctuary</a>, cuyo lema es <em>“El refugio del JavaScript inseguro”, </em>refiriéndose a que ayuda a eliminar muchos errores en tiempo de ejecución, sobre todos los provocados por valores nulos.</p><p>Sanctuary está inspirado por los lenguajes de programación Haskell y PureScript. Provee un conjunto de funciones similares a Ramda y lodash-fp, pero muchas de ellas son seguras y trabajan con <em>data types</em> directamente, como por ejemplo el tipo Maybe.</p><p>Provee dos <em>data types</em> básicos, <a href="https://sanctuary.js.org/#maybe-type">Maybe</a> y <a href="https://sanctuary.js.org/#either-type">Either</a>, que cumplen la especificación de <a href="https://github.com/fantasyland/fantasy-land/tree/v3.3.0">Fantasy Land</a>, que es la especificación de facto de ADTs en JavaScript.</p><p>Promueve un estilo de programación más seguro, sin los odiosos null checks, y reduce los posibles errores en tiempo de ejecución.</p><p>Una gran ventaja es su <strong>sistema de tipos</strong> ad-hoc en tiempo de ejecución, definidos en <a href="https://github.com/sanctuary-js/sanctuary-def/tree/v0.12.1">sanctuary-def</a>. Con este sistema podemos detectar los errores causados por tipos de forma inmediata, lo cual nos evita las clásicas sorpresas de JavaScript…</p><p>Conviene leer la <a href="https://survivejs.com/blog/sanctuary-interview/">entrevista</a> que se le hizo a su creador, donde se explica el por qué de la biblioteca.</p><h4>Fluture</h4><p><a href="https://github.com/fluture-js/Fluture">Fluture</a>, es una biblioteca para provee de una mónada para ejecutar código asíncrono, parecido a una promesa. Como tal, representa un valor <em>success </em>o <em>failure, </em>que resulta de una operación asíncrona de<em> </em>I/O. La diferencia es que Fluture es una mónada (cumple con su interfaz y leyes), por lo tanto se evalúa de forma perezosa y no lanza los side-effects al crearla.</p><p>Puede haber confusión entre las similitudes de una Promesa con una mónada. Se podría decir que el <em>.then </em>es un <em>bind, </em>que el<em> resolve </em>es un<em> pure, etc. </em>Pero no hay que olvidarse de que, una promesa, no ofrece la interfaz especificada por Fantasy Land, ni mucho menos, las leyes de las mónadas. Además de que ejecutan la operación asíncrona (side effects) nada más crearlas. Se puede ver más claro en este <a href="https://glebbahmutov.com/blog/difference-between-promise-and-task/">artículo</a>.</p><h4>Daggy</h4><p><a href="https://github.com/fantasyland/daggy">Daggy</a>, es una pequeña, pero muy útil, biblioteca cuya finalidad es crear <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">ADTs</a> (También llamados <a href="https://guide.elm-lang.org/types/union_types.html">Union Types</a> por la comunidad JS/ELM). Permiten representar datos complejos de forma natural e incluso emular <a href="https://gist.github.com/yang-wei/4f563fbf81ff843e8b1e">pattern matching</a>.</p><p>En el siguiente <a href="https://codesandbox.io/s/3x47m2x0x6">ejemplo</a>, se puede ver una<strong> brillante manera</strong> de usar las <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">ADTs</a> creadas con <strong>Daggy</strong> en componentes de <strong>React</strong>.</p><h4>Otras</h4><p>Cabe destacar también, la biblioteca <a href="http://ramdajs.com/">RamdaJS</a>, que utilicé en su día junto a Sanctuary. Es una biblioteca de utilidades, es parecida a Underscore o lodash, pero ahora, Sanctuary es mucho más madura que al principio y ha incorporado la mayoría de funciones que provee Ramda, y por ello, dejé de usarla. Las principal diferencia entre ambas son como manejan las entradas invalidas y el sistema de tipos en runtime. Ramda es más insegura (sus funciones pueden causar excepciones) porque los creadores no quieren utilizar data types (ellos creen que les quitaría usuarios), y solo proveen de funciones típicas en programación funcional, como map, sin aprovechar todo el potencial de este paradigma de programación.</p><p>Y FolktaleJS, una de las pioneras. Su versión 1.o siempre ha sido muy respetada y ahora están haciendo un gran trabajo en la 2.0, reescribiéndola por completo. Es el mismo concepto que Sanctuary, funciones tipo map, curry, chain, etc y tipos de datos como Maybe, Either, Validation… Se podría decir que Folktale es más orientado a un estilo Java y Sanctuary más hacia Haskell. Además Folktale incluye el tipo <em>Task</em> para tareas asíncronas, muy parecido a lo que ofrece la biblioteca Fluture.</p><h3>Libros y artículos</h3><ul><li><a href="https://github.com/MostlyAdequate/mostly-adequate-guide">Professor Frisby’s Mostly Adequate Guide to Functional Programming</a> — Libro por excelencia en FP en JS, escrito por <a href="https://twitter.com/drboolean">Brian Lonsdorf</a>. Introduce al paradigma de programación funcional <strong>en general</strong> utilizando JavaScript. Es una introducción práctica, que va añadiendo, desde la intuición, ejemplos reales. Es un libro imprescindible si no se tiene experiencia previa con FP.</li><li><a href="https://github.com/getify/functional-light-js">Functional-Light JavaScript</a> — Este libro explora aquellos principios básicos de la FP que se pueden aplicar en JS. Se diferencia en su enfoque práctico, sin usar toda la terminología, que a muchos les echa atrás.</li><li><a href="https://hughfdjackson.com/javascript/why-curry-helps/">Why Curry Helps</a> — Una visión general de como el currying ayuda a escribir código mas reusable y declarativo.</li><li><a href="http://blog.jenkster.com/2016/06/functional-mumbo-jumbo-adts.html">Functional Mumbo Jumbo — ADTs</a> — Una introducción a los tipos algebraicos de datos, para principiantes.</li></ul><h3>Ejemplos</h3><ul><li>En el <a href="https://github.com/RPallas92/congreso-web-2016">repositorio</a> del taller que di en el Congreso web en 2016 acerca de la programación funcional en JS, podrás encontrar las <a href="https://github.com/RPallas92/congreso-web-2016/blob/master/slides.pdf">slides</a> y el <a href="https://github.com/RPallas92/congreso-web-2016/tree/master/app_videos/app_finished">proyecto de ejemplo</a>, un <strong>buscador de vídeos de Youtube (utilizando React y FP).</strong></li><li><a href="https://github.com/justsml/escape-from-callback-mountain">Escape from Callback Mountain</a> — Refactorización, diseño y buenas prácticas.</li><li>Design &amp; refactoring tips for Promise-based Functional JavaScript. Key benefits include better readability, testability, and reusability. MIT.</li></ul><h3><strong>Otros recursos</strong></h3><p>El repositorio de <a href="https://github.com/stoeffel/awesome-fp-js">Awesome FP JS</a> provee de muchos recursos además de los aquí comentados.</p><h3>Bola extra: TypeScript</h3><p>Sólo comentar que se <a href="https://github.com/gcanti">Giulio Canti</a> está en proceso de creación de la biblioteca <a href="https://github.com/gcanti/fp-ts">FP-TS</a>, que permitirá el uso de la <strong>programación funcional en TypeScript</strong>, con la gran mejora sobre JavaScript, de los tipos, que ayudan a escribir código más correcto. Gracias a estos, se puede emular cierto grado de <strong>pattern matching en TypeScript</strong>, sin bibliotecas adicionales, como se explica <a href="https://pattern-matching-with-typescript.alabor.me/">aquí.</a></p><h3>Conclusión</h3><p>Con la combinación de las bibliotecas <strong>Sanctuary, Fluture, Daggy</strong>, podemos llegar a programar en el paradigma de programación funcional de una manera muy similar a la que lo haríamos en cualquier otro lenguaje funcional, salvando las distancias.</p><p>Con este artículo quería demostrar que es posible poner en práctica los conceptos y herramientas de la FP, sin tener que recurrir a un lenguaje especializado.</p><p>Por otro lado quiero decir, que por sólo hacer FP no vas a desarrollar programas perfectos, sino que te expones a los mismos problemas que si no haces FP… pero que aprender FP te va a ayudar a aprender nuevos conceptos para ser mejor programador… como se discute <a href="https://medium.com/@bfil/just-enough-functional-programming-a0c4fd09c8f7">aquí</a>.</p><p>También quiero recomendar el uso en desarrollos frontend de otros lenguajes tipados como <a href="http://www.purescript.org/"><strong>PureScript</strong></a>, Elm, ReasonML, que ayudan a escribir programas más correctos, sobre todo cuando se trata de proyectos más grandes y complejos.</p><p>Antes de finalizar, decir que en los enlaces que se han ido poniendo a lo largo del artículo de puede ampliar más información.</p><p>Finalmente, para el siguiente post, veremos un ejemplo sencillo de como parsear JSON de un servidor de forma segura con programación imperativa vs programación funcional.</p><p><a href="https://twitter.com/PallasR">Ricardo Pallás (@PallasR) | Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76886466501e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>