<?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 Richard Casetta on Medium]]></title>
        <description><![CDATA[Stories by Richard Casetta on Medium]]></description>
        <link>https://medium.com/@rcasetta?source=rss-75dfc41209e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kcajhaRV2so0BceoCo8org.jpeg</url>
            <title>Stories by Richard Casetta on Medium</title>
            <link>https://medium.com/@rcasetta?source=rss-75dfc41209e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:09:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rcasetta/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 programming and its applications to real-world problems]]></title>
            <link>https://blog.tcmlabs.fr/functional-programming-and-its-applications-to-real-world-problems-38238daf2752?source=rss-75dfc41209e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/38238daf2752</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Richard Casetta]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 13:22:51 GMT</pubDate>
            <atom:updated>2021-02-12T13:58:47.942Z</atom:updated>
            <content:encoded><![CDATA[<p>Functional Programming is becoming more and more important these days as it is a great way to write robust, maintainable and elegant programs. If you want to know more about this paradigm and have a clear introduction on its advantages, read on!</p><h3>Introduction to functional programming</h3><p>First of all, what is functional programming? It is a programming paradigm that places functions and abstractions at the top of its thinking model. What does that mean exactly? You’ll see through this part that it enforces to think about function as any other variable you can create and pass around.</p><p>Functional programming is not actually well-defined as such, because some languages are more strict in its functional implementation than others. For example, you can apply some functional principles in Javascript, but you will be able to mutate data and have side-effectful functions. On the other hand, in Haskell, all functions do not have side effects, unless explicitly said in its signature. I will use mostly Haskell in this article, because its syntax is clear and adapted to functional thinking.</p><p>Let’s start with some characteristics you can find in functional programming languages!</p><h4>Immutable data</h4><p>In a functional language, data are immutable, which means that you cannot change the values you have previously defined. For example, if you have a list, you cannot change its elements. If you want to change a value, you have to recreate one. For example:</p><pre>xs = [1, 2, 3];<br>for (let i = 0 ; i &lt; xs.length ; i++) {<br>    xs[i] = xs[i] * 2; // Impossible when data are immutable<br>}</pre><pre>ys = xs.map(value =&gt; value * 2); // Good, create array with new        values</pre><pre>ys = map (*2) xs // In Haskell</pre><p>In this case, we create a new array with map to multiply all its elements by 2. Immutable data are useful when you want to make parallel and/or concurrent programs, keep track of the different states of a program (see redux for example).</p><h4>Pure functions</h4><p>A pure function is a function that respects two properties:</p><ol><li>Always return the same output for a given input</li><li>Does not have side effects</li></ol><p>For example:</p><pre>function (a) {<br>  b = a * 2;<br>  launchRocket(); // Side effect not allowed!</pre><pre>return b;<br>}</pre><pre>// Instead<br>function (a) {<br>  return a * 2;<br>} <br>// is pure (no side effect and always return the same output for a given input)</pre><p>Pure functions are really nice, because it is easier to have parallel and concurrent computations and also are more easier to reason about, No need to think about all the side effects it will have when changing the code, which reduce the cognitive load of the developer.</p><h4>Pattern matching</h4><p>Pattern matching is a powerful feature to increase expressiveness and understandability of your code. It allows to define function or retrieve result of an expression in a very elegant manner. For example:</p><pre>factorial :: Int -&gt; Int<br>factorial 0 = 1<br>factorial n = n * factorial (n - 1)</pre><p>Here, we define the function factorial. The first line tells us that this function take an Int as argument and return an Int. The second line is where the pattern matching occurs: if the argument is 0 then the result is 1, otherwise try another definition. The third line is evaluated if the first pattern matching fails, because n is generic and is not a fixed value. But it is useful when you have complex data structure, like:</p><pre>data Person = Person<br>  { name     :: String<br>  , lastName :: String<br>  }</pre><pre>getFullName :: Person -&gt; String<br>getFullName (Person name lastName) = name ++ &quot; &quot; ++ lastName</pre><p>Here we pattern match on the Person value, getting the name and lastName variable already available in the body of the function. (Here, arguments are matched in place, not by name).</p><h4>Higher order functions</h4><p>Higher order functions are really important in functional programming because it is an effective way to abstract behaviors and computations. These are functions that take other functions as an argument and/or return functions. For example, the map, filter and reduce are higher order functions. We can see that the abstraction is powerful because, in the case of map for example, we can use the function on any list or array, regardless of the type inside it (as long as it is the same).</p><p>In the next part, I will talk about Functors and Monads. These are two patterns we can find in functional programming. These are very useful to write elegant, robust and maintainable code in real-world problems.</p><h3>Application to real-world problems</h3><p>In this part, we will talk about pattern you can find in functional programming languages that are very useful to avoid mistakes when we write code.</p><h4>Functors</h4><p>The next two elements are from Category Theory, which is widely used in functional programming. Actually, these are not concepts tied to functional programming, but they tend to be easier to create and use in functional programming languages.</p><p>A functor, in Haskell, is like a container containing a value, with a method to update its inner value, called fmap. For example, a list is a functor, where the map function you know plays the role of fmap. It is important to note that a functor take a type and returns a new type, which means that for a type a, a functor F will create a new type F a . Let’s see the useful functor called Maybe . This functor is defined by:</p><pre>data Maybe a = Nothing | Just a</pre><p>This definition tells us that a value of type Maybe a is either Nothing or Just a . For example, Just 5 is a Maybe Int . Why is it useful? Actually, if you see a type as a set, you can see the Maybe type as the same set of values (provided by the Just x values) where we have added a null value Nothing , so the set has one more element, which is used to tell that a computation has failed.</p><p>Let’s see a deeper example. If I want to implement the division, I need to take care of the denominator not being 0 . How can I do that? With the Maybe type!</p><pre>safeDiv :: (Fractional a) =&gt; a -&gt; a -&gt; Maybe a<br>safeDiv x 0 = Nothing<br>safeDiv x y = Just (x / y)</pre><p>(Do not bother with the Fractional a part, it just tells that you can use division on the type a )</p><p>As you can see, if you can calculate the value, you return the result wrapped in a Just , otherwise you return Nothing , which is a better way to model computation that may fail than using null or undefined .</p><p>So, what would be the fmap function for the Maybe functor? Actually, it is very simple:</p><pre>fmap :: (a -&gt; b) -&gt; Maybe a -&gt; Maybe b<br>fmap f Nothing  = Nothing<br>fmap f (Just x) = Just (f x)</pre><p>This code tells us that, to apply a function to a Maybe , we have two choices: if the value is Nothing , then do nothing and return Nothing , otherwise, get the value inside the Just thanks to pattern matching, apply f on the value and wrapped it again inside a Just .</p><p>This pattern is useful when you want to apply a function to the result of a computation that may failed without having to check if the value is null or undefined . The next part will talk about Monads, which are improved Functors and allows to chain computations.</p><h4>Monads</h4><p>There are a lot of articles about Monads and it seems that it is a difficult concept to grasp. Actually, I took some time to understand Monads, but it is really worth it to try again and again, because it is a powerful way to think of computation. So what is a Monad?</p><p>A Monad can be seen as a way to chain computations. To grasp that idea, let’s try to develop a function that has the same behavior as the ; you have in some programming languages. How can we do that? The ; , in its essence, is just a way to tell the computer that the expression stops at this point and another one begin. For example:</p><pre>let a = someComputation();<br>let b = anotherComputation(a);</pre><p>Here, the ; tells that we define a as the result of someComputation , <strong>and then</strong> we define b as the result of anotherComputation(a) . This is the essence of Monads: chaining computations. But how can represent this? Let’s try to implement a function called andThen , that does the same thing as the ; :</p><pre>let andThen = (value, callback) =&gt; {<br>  return callback(value);<br>}</pre><p>This definition seems really stupid, it is just function application! But wait, let’s see how we can implement the previous code using this function:</p><pre>andThen(someComputation(), anotherComputation);</pre><p>Ok, no magic here. But what if we define:</p><pre>let a = someComputation();<br>let b = anotherComputation(a);<br>let c = anotherAgainComputation(a);<br>let d = againAnotherAgainComputation(b, c);</pre><p>We can then use the andThen this way:</p><pre>andThen(someComputation(), a =&gt; (<br>andThen(anotherComputation(a), b =&gt; (<br>andThen(anotherAgainComputation(a), c =&gt; (<br>        againAnotherAgainComputation(b, c)<br>))))))</pre><p>So we have the same result, the a , b , c variables and so on are available to the next calls! Actually, this seems pretty useless. And it is! Because what we have define is the Identity Monad, the Monad that does… Nothing much. But, look at our andThen function, we can do some interesting things with it:</p><pre>let andThen = (value, callback) =&gt; {<br>  // Put some magic here<br>  return callback(value);<br>}</pre><p>The advantage to define a function andThen is that we can repeat some code before returning a value! That is the magic of Monads! Let’s define andThen another way so that you will understand the power of Monads. Suppose we have function that either return a value or an error (an http call, something like that). What you usually write is:</p><pre>let { error, response } = computationWithError();<br>if (error) {<br>  return error;<br>}<br>let { error2, response2 } = anotherComputationWithError(response);<br>if (error2) {<br>  return error2;<br>}<br>return yetAnotherComputationWithError(response2);</pre><p>I have seen this pattern a lot of time, it is unreadable and error prone. Let’s try to use our andThen function to make it better:</p><pre>let andThenEither = ({ error, response }, callback) =&gt; {<br>  if (error) {<br>    return { error };<br>  }<br>  return callback(response)<br>}</pre><p>Here we take a value of a computation that may have failed, returning the error if it has and continuing the computation if the computation has been successful.</p><p>The previous code can then be rewritten:</p><pre>andThenEither(computationWithError(), response =&gt; (<br>andThenEither(anotherComputationWithError(response),<br>              yetAnotherComputationWithError<br>)))</pre><p>See? No trace of if statement, everything is checked in the andThenEither function: if a computation fails, it short-circuits the rest of the computations and returns the error. It is called the Either e Monad, where e is the type of the error.</p><p>So a monad is a way to chain computations. It is actually a container with two methods: return and andThen (called bind in Haskell and written &gt;&gt;= ). The return function is a way to wrap a value in a Monad. A Monad needs to respect some laws, but it is outside the scope of this article. Beside, in Haskell, the do notation, allows to avoid indentation like we have seen before:</p><pre>myFunction = do<br>  response &lt;- computationWithError<br>  response2 &lt;- anotherComputationWithError(response)<br>  yetAnotherComputationWithError(response2)</pre><p>Or, using the &gt;&gt;= operator:</p><pre>myFunction = computationWithError <br>  &gt;&gt;= anotherComputationWithError <br>  &gt;&gt;= yetAnotherComputationWithError</pre><p>Pretty cool, uh? That’s it, a Monad is a way to chain computation: in the Identity monad, no magic trick, but the Either e monad is pretty useful, you avoid all error checks in the code you write because the Monad takes care of it for you. You write code as if there were no errors!</p><p>The two patterns we have defined, Functors and Monads, are only the tip of the iceberg. There are a lot more pattern in functional programming languages that allows to write code without error, because we abstract the the thing we use: computations with monads, and lot more.</p><p>I hope this article helps you to understand the benefits of functional programming and that you will dig deeper in this gold mine!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38238daf2752" width="1" height="1" alt=""><hr><p><a href="https://blog.tcmlabs.fr/functional-programming-and-its-applications-to-real-world-problems-38238daf2752">Functional programming and its applications to real-world problems</a> was originally published in <a href="https://blog.tcmlabs.fr/">TCM Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>