<?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 Cristian Álvarez on Medium]]></title>
        <description><![CDATA[Stories by Cristian Álvarez on Medium]]></description>
        <link>https://medium.com/@belaustegui?source=rss-70cdc3f81361------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ulGkykjO_jLOeLojJZoAnw.png</url>
            <title>Stories by Cristian Álvarez on Medium</title>
            <link>https://medium.com/@belaustegui?source=rss-70cdc3f81361------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:15:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@belaustegui/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[Introducing Trans 2.0]]></title>
            <link>https://medium.com/hackernoon/introducing-trans2-407610887068?source=rss-70cdc3f81361------2</link>
            <guid isPermaLink="false">https://medium.com/p/407610887068</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[ecto]]></category>
            <category><![CDATA[translation]]></category>
            <dc:creator><![CDATA[Cristian Álvarez]]></dc:creator>
            <pubDate>Mon, 17 Apr 2017 13:20:06 GMT</pubDate>
            <atom:updated>2023-09-18T17:51:05.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JY_impSbrfGsBykD1uOCHw.jpeg" /></figure><h4>Smaller, safer, easier to use and more flexible</h4><blockquote>This article is also available in <a href="https://crbelaus.com/2017/04/17/introducing-trans-2-0.html">my personal blog</a>, which respects your privacy and doesn’t collect any kind of metrics or analytics.</blockquote><h3>What is Trans?</h3><p><a href="https://hex.pm/packages/trans"><strong>Trans</strong></a><strong> is an Elixir library for managing translations embedded into data structures</strong>. While <a href="https://hackernoon.com/tagged/frans">Trans</a> can be used only for fetching translations from maps or structs, it shines when coupled with <a href="https://hex.pm/packages/ecto">Ecto</a> for fetching and querying translations from the database.</p><p>The traditional approach to translation management consists on using database tables dedicated only to translation storage. For example we may have a posts table and a companion post_translations table. This is the approach used by the Ruby gem <a href="https://rubygems.org/gems/globalize">Globalize</a>.</p><p>While this approach is battle tested and works, it has a few disadvantages that can be improved:</p><ul><li>It complicates the database schema requiring a new table to be created for each translatable schema.</li><li>It complicates the database migrations, since changes in the structure of a table must be replicated into the translation tables.</li><li>It requires constant <em>JOINs</em> in order to filter or fetch records along with their translations. This has a visible impact on performance when multiple translatable schemas intervene in a query.</li></ul><p>Modern <a href="https://en.wikipedia.org/wiki/Relational_database_management_system">RDBMSs</a> support unstructured datatypes such as JSON. <strong>We can leverage this unstructured datatype support to embed the translations into a field of the schema itself</strong>, instead of having separated schemas for translations. This eliminates the need of maintaining duplicated database tables in sync and vastly reduces the number of JOIN clauses in queries.</p><p>While the database itself provides mechanisms for accessing unstructured data, <a href="https://hackernoon.com/tagged/ecto">Ecto</a> itself does not provide a high level interface for accessing them easily. This is where Trans mission begins.</p><p>Ecto allows you to write custom SQL fragments that can be used, among other things, to access JSON fields in the database. Writing those SQL fragments for each query that requires translations can get tiresome and error prone quickly. <strong>Trans generates the SQL fragments for you and validates them during compile time.</strong></p><h3>Trans 1.0 sins</h3><h4>Bypassing Ecto syntax for queries</h4><p><a href="https://hexdocs.pm/ecto/Ecto.Query.html#content">Ecto.Query</a> provides a nice syntax for query generation. Queries can be written using a series of macros (or functions, depending on which API you prefer) that allow for parameter interpolation, data binding, composition and prefixing.</p><p>Instead of enhancing Ecto.Query.Api Trans provided its own, different, API that didn’t interact with it. This caused a series of inconveniences and limitations.</p><p>The first and most noticeable inconvenience appears when writting a query with some conditions on the translatable data. Instead of specifying the conditions when building the query, Trans 1.0 required to build the query first, and then pass it to a function that would add the required conditions.</p><p>The first and most noticeable inconvenience appears when writing a query with some conditions on the translatable data. With a normal Ecto query you wold specify the conditions when building the query itself. Instead, <strong>Trans 1.0 required to build the query first, and then pass it to a function that would add the required conditions.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7002e7c38fb1a78a638f0cf92698042e/href">https://medium.com/media/7002e7c38fb1a78a638f0cf92698042e/href</a></iframe><p>Another problem of this approach is that <strong>conditions on translatable fields could be only added on the main schema of the query</strong>. Joined schemas and associations were out… Ouch!</p><h4>Mixing responsibilities in schema modules</h4><p>The translation container is the field that embeds the translations for the schema. Trans uses by default a field called translations, but allows this to be customized.</p><p>In Trans 1.0, you had two options: calling the QueryBuilder functions directly or using Trans in your schema module to get some convenience functions set up to avoid repetition. Setting up the convenience functions was the most comfortable option, but it <strong>added extra responsibilities and concerns to schema modules that did not belong there</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8fe8a7a2036e8493462f3d9c022271/href">https://medium.com/media/cb8fe8a7a2036e8493462f3d9c022271/href</a></iframe><h4>Unsafe against translation errors</h4><p>Trans 1.0 performed some basic checks against translation errors. For example, trying to add a query condition on an untranslatable field would result in a run-time ArgumentError.</p><p><strong>Trans 2.0 improves those checks and produces errors in the compilation phase instead on run-time.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb27c4f92fb2f14da51e7b669e95425e/href">https://medium.com/media/cb27c4f92fb2f14da51e7b669e95425e/href</a></iframe><h3>Trans 2.0 improvements</h3><h4>Embracing Ecto Syntax for queries</h4><p>In Trans 2.0, the QueryBuilder component has been completely rewritten: <strong>it now runs in compilation time and it’s only mission is the generation of the required SQL fragment</strong>. All the different functions in the QueryBuilder module have been unified into the translated/3 macro.</p><p>Being a macro allows the QueryBuilder to generate the SQL fragment in compile time and add it to the query being compiled. This way we can use the translated/3 macro when creating Ecto queries and <strong>interact with the rest of functions and macros provided by</strong><strong>Ecto.Query and </strong><strong>Ecto.Query.Api</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56139b0814c9433e103967fadd68b192/href">https://medium.com/media/56139b0814c9433e103967fadd68b192/href</a></iframe><h4>Extracting responsabilities out of schema modules</h4><p>With Trans 2.0, <strong>modules only export an underscore function named </strong><strong>__trans__</strong> that returns the Trans configuration for the module.</p><p>This <strong>keeps client modules clean and keeps the logic contained into the QueryBuilder and Translator modules</strong> instead of spreading it among the client code.</p><h4>Safety checks as soon as possible</h4><p>As explained before, Trans 1.0 did some basic checks in runtime. Since the translation configuration for each module is set up during the compilation, Trans 2.0 uses it to perform safety checks before runtime.</p><p>Want to translate a non existing field? Your application won’t compile. Want to translate a non-translatable field? Whooops… Your application won’t compile. Well… You get the idea. This makes Trans 2.0 safer and more approachable than the previous version.</p><h3>Future plans</h3><p>With this update Trans is in a good shape for being maintained and continuously improved. The main features that I want to include in future versions of Trans are:</p><ul><li><strong>Support for MySQL</strong>. MySQL 5.7 introduced a native JSON type that could be used by Trans in the same way as the PostgreSQL JSONB type. There is an <a href="https://github.com/xerions/mariaex/issues/119">open issue</a> in the <a href="https://github.com/xerions/mariaex">MySQL database driver</a> repository to add support for this type.</li><li><a href="https://github.com/belaustegui/trans/issues/14"><strong>Specify available locales</strong></a><strong> and </strong><a href="https://github.com/belaustegui/trans/issues/12"><strong>custom fallback sequences</strong></a>. Currently Trans falls back to the default language when a translation does not exist. This behavior could be customized to check other locales before falling back to the default language.</li><li><strong>Make translations an embedded schema and create a custom Ecto type</strong>. This is still an unfinished idea, but the main objective here would be to represent translations as embedded schemas. This way the translations could specify their own changesets and perform required validations or transformations.</li></ul><h3>Wrapping up</h3><p>Trans first release was on June 4th, 2016, so it will reach a year of life soon. This has been an interesting journey where <strong>we had 6 releases, 159 commits and have reached almost 250 downloads</strong>. Thank you all!</p><p>With this new release Trans has reached a level of maturity that makes it more usable, safe and maintainable for the time coming. So expect more improvements and features in the future.</p><p>If you found a bug or have any ideas or comments feel free to post there or to <a href="https://github.com/belaustegui/trans/issues/new">open an issue in GitHub</a>. There are also interesting discussions in the <a href="https://elixirforum.com/t/trans-embedded-translations-for-elixir/840">Trans thread at Elixir Forum</a>.</p><p>To finish this article I want to specially thank my friends <a href="https://medium.com/u/ff2508be75f8">Óscar de Arriba</a>, <a href="https://medium.com/u/a15f8add882e">Victor Ortiz</a>, <a href="https://medium.com/u/a70e615c440b">Enol Iglesias</a>, <a href="https://medium.com/u/d0b19f8b8579">Rubén Sierra</a> and <a href="https://medium.com/u/909015f6e9c2">dreamingechoes</a> for all the support ❤️. See you at the <a href="http://www.elixirconf.eu/">ElixirConf.EU</a>!</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><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=407610887068" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/introducing-trans2-407610887068">Introducing Trans 2.0</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[Lingüística y lenguajes de programación]]></title>
            <link>https://medium.com/the-cocktail-engineering/linguistica-y-lenguajes-de-programacion-30eefb430788?source=rss-70cdc3f81361------2</link>
            <guid isPermaLink="false">https://medium.com/p/30eefb430788</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[programación]]></category>
            <category><![CDATA[linguistics]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Cristian Álvarez]]></dc:creator>
            <pubDate>Sun, 04 Dec 2016 16:48:24 GMT</pubDate>
            <atom:updated>2023-09-18T18:18:50.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6JujVtobc4p61v_RIGnSQ.jpeg" /><figcaption>Imagen cortesía de <a href="http://www.flazingo.com/">http://www.flazingo.com/</a></figcaption></figure><h3>Lingüística y lenguajes de programación.</h3><blockquote>Puedes leer este articulo en mi <a href="https://crbelaus.com/2016/12/04/linguistica-lenguajes-programacion.html">blog personal</a>, que respeta la privacidad y no recoge ningún tipo de estadísticas ni métricas.</blockquote><p>Los lenguajes naturales (por ejemplo: el español o el inglés) tienden a ser ambiguos y en muchas ocasiones están sujetos a la interpretación, la cual puede variar en función del contexto, el interlocutor, el tono, etc.</p><p>Por otra parte los lenguajes de programación tienen el objetivo de describir procesos de computación o algoritmos a máquinas. Estos lenguajes tienen una descripción sintáctica y semántica precisa con el objetivo de evitar la ambigüedad propia de los lenguajes naturales.</p><p>Durante los años, el nivel de abstracción de los lenguajes de programación ha ido aumentando. Ésto ha proporcionado a los programadores herramientas con las que construir programas más complejos de forma más sencilla.</p><p>En este artículo veremos un ejemplo de cómo los lenguajes de programación pueden ser enriquecidos mediante ciertas características de los lenguajes naturales con el objetivo de crear nuevas abstracciones sobre las que trabajar.</p><h4>¿Qué es una anáfora?</h4><p>En lingüística, una anáfora es una expresión (normalmente un pronombre) cuyo significado depende de otra expresión previa. Las ánforas nos permiten hablar y mantener una conversación sobre algo sin necesidad de nombrarlo continuamente.</p><p>El diccionario de la Real Academia de la Lengua define la anáfora como:</p><blockquote>f. Ling. Relación de identidad que se establece entre un elemento gramatical y una palabra o grupo de palabras nombrados antes en el discurso</blockquote><p>Por ejemplo: en la frase “<em>Coge el teléfono y quítalo de la mesa</em>” el pronombre “<strong><em>lo</em></strong>” es una anáfora que hace referencia a “<strong><em>el teléfono</em></strong>”.</p><h4>¿Qué es una macro?</h4><p>En programación, una macro¹ (abreviatura de macroinstrucción) es una función que genera código. El proceso de generar código a partir de una macro se llama “<em>macro expansión”</em>.</p><p>En los lenguajes de programación que soportan macros, hay dos diferencias fundamentales entre éstas y las funciones:</p><ol><li>Las funciones devuelven resultados, mientras que las macros se expanden y devuelven expresiones (estas expresiones pueden a su vez ser funciones que devuelvan resultados).</li><li>La <em>macro expansión</em> tiene lugar en tiempo de compilación. En tiempo de ejecución sólo se ejecuta el código que haya generado la macro.</li></ol><p>Las macros son un mecanismo de metaprogramación muy potente puesto que permiten añadir características y construcciones a un lenguaje definiéndolas en el propio lenguaje y sin ningún coste de rendimiento durante la ejecución del programa.</p><p>Un ejemplo de uso de macros se puede ver en el <a href="https://github.com/elixir-lang/elixir">repositorio del lenguaje de programación Elixir</a>, que está programado casi en su totalidad en el propio Elixir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*bHp-D8LEe0XmDelyAaHy6A.png" /><figcaption>Recursos lingüísticos en lenguajes de programación¿Magia? No, macros</figcaption></figure><h4>¿Qué es una macro anafórica?</h4><p>El concepto de macro anafórica² fue introducido por <a href="http://www.paulgraham.com/">Paul Graham</a> en su libro <em>On Lisp, Advanced Techniques for Common Lisp³</em> (el libro puede descargarse gratuitamente, al final del artículo encontrarás un enlace a su web). Una macro anafórica simula el concepto de anáfora de los lenguajes naturales en un lenguaje de programación.</p><p>Técnicamente podemos decir que una macro anafórica <em>enriquece el ámbito de ejecución introduciendo en él automáticamente un nuevo identificador que toma el valor de una expresión ejecutada previamente.</em></p><h4>Caso de uso y ejemplo de implementación.</h4><p>A continuación veremos un ejemplo de la implementación y el funcionamiento de una macro anafórica. El lenguaje que usaremos para los ejemplos es <a href="http://elixir-lang.org/">Elixir</a>.</p><p>Supongamos que necesitamos comprobar si una expresión devuelve un valor verdadero (en Elixir cualquier valor se considera verdadero excepto <em>nil</em> y <em>false</em>) y, en caso afirmativo hacer algo con él. Si la expresión a evaluar requiere un cálculo costoso, la memorizaríamos de la siguiente manera:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6c86a98845a8568da5c8ea27ffba9ee/href">https://medium.com/media/e6c86a98845a8568da5c8ea27ffba9ee/href</a></iframe><p>Este enfoque es muy simple pero define la variable <strong>result</strong> en un ámbito superior al del <strong>if</strong> donde resulta útil, lo que provoca que dicha variable siga siendo accesible posteriormente. Éste es un clásico problema de <em>scoping⁴ </em>que se resuelve creando un nuevo ámbito de vida para la variable <strong>result</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c318b6f627f9a69046a4ea128164c0c/href">https://medium.com/media/1c318b6f627f9a69046a4ea128164c0c/href</a></iframe><p>Este proceso de guardar el resultado y crear un nuevo <em>scope</em> donde esté disponible puede ser automatizado por medio de una macro.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9930dffc7997e0932afc278110d26b0/href">https://medium.com/media/c9930dffc7997e0932afc278110d26b0/href</a></iframe><p>La macro <strong>quote</strong> devuelve el AST que representa a las expresiones que contiene. La macro <strong>unquote</strong> evalúa el valor real de la expresión que contiene antes de insertarlo en el AST. Podemos invocar nuestra macro así:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/536056a34bcac4be2b700b21f59c4a05/href">https://medium.com/media/536056a34bcac4be2b700b21f59c4a05/href</a></iframe><p>A pesar de que la variable <strong>it</strong> parece ser una variable libre, ésta ha sido creada durante el proceso de <em>macro expansión</em> de la macro <strong>Anaphora.if. </strong>Como podemos ver, su comportamiento es similar al de una anáfora en el lenguaje natural, puesto que su valor hace referencia al de la expresión que hemos pasado como primer argumento.</p><h4>Conclusión.</h4><p>La diferencia entre el lenguaje natural y un lenguaje de programación es que mientras que el primero es ambiguo y está sujeto a la interpretación, el segundo tiene una especificación formal que pretende eliminar la ambigüedad.</p><p>Gracias a la metaprogramación podemos incluir o simular ciertas características de los lenguajes naturales que hagan nuestros programas más legibles y fáciles de entender.</p><p>A pesar de toda la flexibilidad que nos permite la metaprogramación y, en particular, las macros, es importante destacar que son un mecanismo potencialmente peligroso y del que no hay que abusar. El isomorfismo de los lenguajes como Lisp o Elixir hacen más sencillo este tipo de metaprogramación.</p><p>La macro anafórica que hemos implementado no es mas que un ejemplo muy simple. La librería <em>anaphora</em>⁵ contiene una implementación mucho más completa y robusta de varias macros anafóricas en Elixir. Su código es muy limpio y fácil de entender, si tienes curiosidad merece la pena echarle un vistazo.</p><h4>Referencias.</h4><ol><li><a href="https://en.wikipedia.org/wiki/Macro_(computer_science)">Macro (computer science) — Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Anaphoric_macro">Anaphoric Macro — Wikipedia</a></li><li><a href="http://www.paulgraham.com/onlisp.html">“On Lisp. Advanced Techniques for Common Lisp” — Paul Graham, Prentice Hall, 1993. ISBN 0130305529.</a></li><li><a href="https://en.wikipedia.org/wiki/Scope_(computer_science)">Scope (computer science) — Wikipedia</a></li><li><a href="https://hex.pm/packages/anaphora">anaphora-elixir— Alexander Sviridov</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30eefb430788" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cocktail-engineering/linguistica-y-lenguajes-de-programacion-30eefb430788">Lingüística y lenguajes de programación</a> was originally published in <a href="https://medium.com/the-cocktail-engineering">The Cocktail Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[¿Qué es la programación funcional?]]></title>
            <link>https://medium.com/the-cocktail-engineering/qu%C3%A9-es-la-programaci%C3%B3n-funcional-c91b611b0258?source=rss-70cdc3f81361------2</link>
            <guid isPermaLink="false">https://medium.com/p/c91b611b0258</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Cristian Álvarez]]></dc:creator>
            <pubDate>Tue, 10 May 2016 12:00:04 GMT</pubDate>
            <atom:updated>2023-09-18T18:17:11.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPmGCA2rq_LuJp66bxr62Q.jpeg" /><figcaption>Haskell es un lenguaje de programación funcional.</figcaption></figure><blockquote>Puedes leer este articulo en <a href="https://crbelaus.com/2016/05/10/que-es-la-programacion-funcional.html">mi blog personal</a>, que respeta tu privacidad y no recoge ningún tipo de estadísticas ni métricas.</blockquote><p>Si eres programador es muy probable que en algún momento hayas leído o escuchado hablar sobre la programación funcional como algo que trae grandes beneficios al desarrollo de software.</p><p>La programación funcional tiene su origen en el <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda cálculo de Alonzo Church</a> y en los <a href="https://en.wikipedia.org/wiki/Formal_system">sistemas formales</a>, este fundamento fuertemente teórico y cercano a la matemática puede hacer complicado entender en qué consiste.</p><p>Este artículo pretende explicar qué es la programación funcional y en qué conceptos se basa.</p><p>La mayoría de problemas en un programa de software provienen de la incapacidad de los desarrolladores para predecir o tener en cuenta todos los posibles estados en los que puede ejecutarse una determinada pieza de código.</p><p>El paradigma de programación funcional pretende eliminar los cambios de estado, para ello se basa principalmente en la <em>composición de funciones</em>, <em>la transparencia referencial</em> y las <em>funciones puras</em>.</p><h4>Composición de funciones.</h4><p>En un lenguaje de programación orientado a objetos como puede ser Ruby los objetos son el elemento básico de abstracción. Los objetos encapsulan estructuras de datos y funciones que modifican estas estructuras. Los programas se construyen mediante una composición de diferentes tipos de objetos interactuando entre sí.</p><p><strong>El paradigma funcional separa las estructuras de datos y las funciones que operan sobre ellas</strong>. Los programas se construyen mediante la composición de funciones, de manera que una función realiza su trabajo llamando a otras funciones cada vez más simples hasta alcanzar las primitivas del lenguaje.</p><p><strong>Las funciones son un elemento de primer orden en el lenguaje</strong>, al igual que pueden ser los números o las cadenas de texto. Esto permite, entre otras cosas, el almacenamiento de funciones en una lista o en cualquier otra estructura de datos.</p><p>Puesto que las funciones son un elemento de primer orden, también <strong>pueden recibir otras funciones como parámetros o devolveras como resultado de su ejecución</strong>. Este tipo de funciones que reciben o devuelven otras funciones se llaman <a href="https://en.wikipedia.org/wiki/Higher-order_function">funciones de orden superior</a> y son el elemento básico de composición y reutilización de código en el paradigma funcional.</p><h4>Transparencia referencial y funciones puras.</h4><p>El gran pilar del paradigma funcional es <em>la transparencia referencial</em>. En la teoría de lenguajes de programación el concepto de transparencia referencial indica que <strong>una expresión puede ser sustituida directamente por su valor sin que esto afecte a la ejecución del programa</strong>. El ejemplo más claro de expresiones referencialmente transparentes son todas las funciones matemáticas.</p><p>A simple vista la implicación más directa de la transparencia referencial es que <strong>la evaluación de una expresión depende única y exclusivamente de sus parámetros de entrada</strong>. Entre otras cosas esto significa que invocar una función con los mismos argumentos siempre produce el mismo resultado.</p><p>El otro gran efecto de la transparencia referencial es la ausencia de <em>efectos colaterales</em>, <strong>una función sólo retorna un valor y no produce cambios de estado</strong>.</p><p>Por ejemplo, en un lenguaje de programación orientado a objetos podemos tener un objeto de tipo lista que contiene varios elementos, para añadir un nuevo elemento modificamos la lista de manera que contenga el nuevo elemento. Esta modificación de la lista original es un efecto colateral.</p><p>En un lenguaje de programación funcional la misma función devolvería una nueva lista incluyendo todos los elementos de la original y el nuevo elemento que queremos añadir. Crear una nueva lista equivalente en lugar de modificar la original hace que nuestra función no tenga efectos colaterales. Este tipo de funciones que no tienen efectos colaterales reciben el nombre de <a href="https://en.wikipedia.org/wiki/Pure_function"><em>funciones puras</em></a>.</p><h4>En resumen.</h4><p>El paradigma de programación funcional tiene como objetivo evitar los cambios de estado y hacer explícitas las transformaciones de datos. Para ello se basa en tres principios clave:</p><ul><li>Las funciones son el elemento básico de abstracción y reutilización de código. Los programas se construyen mediante una composición de funciones.</li><li>Las funciones son un elemento de primer orden en el lenguaje. Pueden guardarse en estructuras de datos, pasarse como argumentos y devolverse desde otras funciones.</li><li>El resultado de evaluar una expresión depende única y exclusivamente de sus parámetros de entrada. Ante una misma entrada siempre obtenemos el mismo resultado.</li></ul><h4>¿Dónde puedo investigar más?</h4><p>En mi opinión, la mejor explicación sobre la programación funcional y sus conceptos está en el paper <a href="http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html">Why Functional Programming Matters, John Hughes, 1984</a>. La <a href="https://en.wikipedia.org/wiki/Functional_programming">entrada en Wikipedia</a> sobre la programación funcional es también un buen punto de partida (son especialmente interesantes las secciones de <a href="https://en.wikipedia.org/wiki/Functional_programming#History">Historia</a> y <a href="https://en.wikipedia.org/wiki/Functional_programming#Comparison_to_imperative_programming">Comparación con la Programación Imperativa</a>). Para profundizar más, es muy interesante el clásico <a href="https://mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs, Abelson y Sussman, 1985</a>.</p><p>En cuanto a blogs, no puedo dejar de recomendar el post <a href="http://www.vasinov.com/blog/16-months-of-functional-programming/">16 Months of Functional Programming, Vasily Vasinov</a>, así como el genial <a href="http://gamasutra.com/view/news/169296/Indepth_Functional_programming_in_C.php">In-depth: Functional programming in C++, John Carmack</a>.</p><p>Por último, una muy buena introducción práctica es el curso <a href="https://es.coursera.org/course/progfun">Principios de Programación Funcional en Scala, Coursera</a> que imparte Martin Odersky (creador del lenguaje de programación Scala) y en el que te puedes matricular completamente gratis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c91b611b0258" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cocktail-engineering/qu%C3%A9-es-la-programaci%C3%B3n-funcional-c91b611b0258">¿Qué es la programación funcional?</a> was originally published in <a href="https://medium.com/the-cocktail-engineering">The Cocktail Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>