<?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 JeanRaphael Bordet on Medium]]></title>
        <description><![CDATA[Stories by JeanRaphael Bordet on Medium]]></description>
        <link>https://medium.com/@jrBordet?source=rss-32c8276f4390------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kU44oVB_kC9HogYM.jpg</url>
            <title>Stories by JeanRaphael Bordet on Medium</title>
            <link>https://medium.com/@jrBordet?source=rss-32c8276f4390------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:22:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jrBordet/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[Swift is not a functional language, but…]]></title>
            <link>https://proudlynerd.vidiemme.it/swift-is-not-a-functional-language-but-64afcfdbdf85?source=rss-32c8276f4390------2</link>
            <guid isPermaLink="false">https://medium.com/p/64afcfdbdf85</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[JeanRaphael Bordet]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 07:28:26 GMT</pubDate>
            <atom:updated>2023-04-18T07:28:26.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*lOo2svH8NhHqKwFyjrUplg.jpeg" /></figure><p>Most of the code from this post is available in this <a href="https://github.com/jrBordet/vidiemme-swift-is-not-functional">repository</a>, and I strongly recommend following it while reading it.</p><h3>Introduction</h3><p>Before starting let me clarify that Swift is not a functional language and is not meant to be, but most concepts are inspired by this paradigm.</p><p>So the question is: what lessons can we learn from this kind of approach?</p><h3>The pillar of functional programming: Functors, Applicative, and Monads</h3><p>In the article <a href="https://www.adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html">Monads in picture</a> we have a wonderful explanation of the basics of those important concepts when applied to programming.</p><p>Basically, we should remind that our work is related to data manipulation, and usually, a developer writes code that specifies the steps that the algorithm must take to accomplish the goal. We can simply define a variable and manipulate pieces of information as we do every day.</p><p>For instance, we can do something like that</p><pre>var x: Int = 1<br><br>// increment by one<br>x += 1<br><br>// square<br>x *= x</pre><p>But, what’s the problem with the imperative approach? The problem is that we are missing consistency and safety because our pieces of information can be manipulated by anyone from anywhere.</p><p>Let&#39;s try a functional approach and instead of a free variable let&#39;s try to manipulate data inside a context. For instance, we can create an enum <strong>Maybe&lt;A&gt;</strong> that basically acts like an Optional in Swift.</p><pre>enum Maybe&lt;A&gt; {<br>    case none<br>    case value(A)<br>}</pre><h4>Functors</h4><p>The problem now is that we need a way to transform our data, and here comes the idea of a <strong>Functor.</strong></p><blockquote>Functor is any type that defines how map is applied to it.</blockquote><p>When a value is wrapped in a context you cannot simply apply a normal function to it as we have done before, we need an extra function, a map:</p><pre>func map&lt;B&gt;(<br>    _ f: @escaping (A) -&gt; B<br>    ) -&gt; Maybe&lt;B&gt; {<br>    guard case let .value(t) = self else {<br>        return .none<br>    }<br>        <br>    return .value(f(t))<br>}</pre><p><strong>map</strong> has a really clearly defined shape</p><p><strong>f: (A) -&gt; B</strong> is A function that describes how to transform <strong>B</strong> from a given</p><p><strong>A -&gt; Maybe&lt;B&gt;</strong> and returns the same container</p><p>And now we can use our brand new map to apply a function to Maybe and transform safely its content.</p><pre>Maybe&lt;Int&gt;(1).map(incr(_:))<br><br>// or with a simple syntax using Swift’s autoclosure:<br>Maybe&lt;Int&gt;(1).map { incr($0) } </pre><p>So map shows us how it’s done! But how does map know how to apply the function? Let’s go deep inside of the meaning of map function.</p><h3>map</h3><p><em>In many programming languages map is the name of a higher-order function that applies a given function to each element of a functor, e.g. a list, returning a list of results in the same order. It is often called apply-to-all when considered in functional form.</em></p><p>A generic map function should satisfy a couple of laws:</p><ul><li>Identity</li><li>Composition</li></ul><h3>identity law</h3><blockquote>map(id) == id</blockquote><p>If the transformation we supply to map doesn’t do anything, then it leaves the structure fixed. Seems like a very reasonable property for mapto have.</p><p>There’s a name for a function that does nothing but return its argument: the identity function. We can define it in full generality like so:</p><pre>func id&lt;A&gt;(<br>   _ a: A<br>) -&gt; A {<br>    a<br>}</pre><p>And let me verify if our map satisfies the first law.</p><pre>let maybe = Maybe&lt;Int&gt;(1)<br><br>let result = maybe.map { id($0) }<br><br>assert(unwrap(result) == unwrap(maybe))</pre><h3>composition law</h3><p>The composition law ensures that map (f) &gt;&gt;&gt; map (g) or map (f &gt;&gt;&gt; g) leads to the same result, or in other words that the composition of the maps is equal to the map of composition.</p><p>To demonstrate the second law we need a new function pipe to compose two functions.</p><pre>public func pipe&lt;A, B, C&gt;(<br>    _ f: @escaping (A) -&gt; B, <br>    _ g: @escaping (B) -&gt; C<br>    ) -&gt; (A) -&gt; C {<br>    return { a in<br>        g(f(a))<br>    }<br>}</pre><p>Basically, the idea behind a pipe function is that applying a function f: (A) -&gt; B and g: (B) -&gt; C is equal to apply just z: (A) -&gt; C.</p><p>Define two simple functions to compute an Int</p><pre>let incr: (Int) -&gt; Int = { v in v + 1 }<br>let square: (Int) -&gt; Int = { v in v * v }</pre><p>Compose them with pipe</p><pre>let incr_square = pipe(incr, square)</pre><p>The result of composition is the same as chaining</p><pre>let result_composition = Maybe<br>    .map(incr_square)<br><br>let result_chaining = Maybe<br>    .map(incr)<br>    .map(square)</pre><p>And that’s it, the composition of the maps is the map of composition, and the second law is verified.</p><p>And with the new pipe we can write more complex functionality.</p><p>For simplicity let me define a new operator &lt;^&gt; (&lt;$&gt; in Haskell) for the map and bring it together with pipe composition.</p><pre>func &lt;^&gt; &lt;A, B&gt;(f: @escaping (A) -&gt; B, a: Maybe&lt;A&gt;) -&gt; Maybe&lt;B&gt;</pre><p>The left side is just our map function that takes a value A and transforms it into B, and the right side is our Maybe over a generic A. As I said it is just an operator over the map function but it gives us great power to combine complex operations together.</p><pre>let incr: (Int) -&gt; Int = { $0 + 1 }<br>let square: (Int) -&gt; Int = { $0 * $0 }<br><br>let result = pipe(incr, square) &lt;^&gt; Maybe&lt;Int&gt;(3)</pre><p>This code takes a number 3 and increments it by 1 and then squares the result.</p><pre>let fancy: (Int) -&gt; String = {<br>    &quot;fancy \($0)&quot;<br>}<br>        <br>pipe(pipe(incr, square), fancy) &lt;^&gt; Maybe&lt;Int&gt;(3)<br>// &quot;fancy 16&quot;</pre><h4>Array and Optional as Functor</h4><p>For instance, we can think also Array and Optional (of course) as functors</p><pre>let transform = pipe({ $0 + 2 }, { $0 + 1 })<br> <br>let result = transform &lt;^&gt; [0, 1, 2, 3] // [0, 1, 2, 3].map(transform)<br><br>// [3, 4, 5, 6] </pre><pre>let a: Int? = 3<br><br>let transform = pipe({ $0 + 2 }, { $0 + 1 })<br><br>let result = transform &lt;^&gt; a // a.map(transform)<br><br>// 6</pre><h3>Applicative</h3><p>With functors we have seen how to transform data using a specific function. With an applicative functor we map objects in an ‘lifted world’ using functions from the same ‘lifted world’.</p><p>With an applicative functorour values are wrapped in a context just like functors, but our functions are wrapped in a context too: Maybe&lt;((A) -&gt; B)&gt;</p><p>So an applicative knows how to apply a <em>function</em> wrapped in a context to a <em>value</em> wrapped in a context:</p><pre>func apply&lt;B&gt;(<br>  _ f: Maybe&lt;((A) -&gt; B)&gt;<br>) -&gt; Maybe&lt;B&gt; {<br>    fatalError()<br>}</pre><p>Implementation</p><pre>switch f {<br>case .none:<br>    return .none<br>case let .value(transform): // (A) -&gt; B<br>    switch self {<br>    case .none:<br>        return .none<br>    case let .value(a):<br>        return Maybe&lt;B&gt;(transform(a))<br>    }<br>}</pre><p>Now pay attention to the first value case.</p><p>Does the nested switch statement remind you of anything? This code does pretty much the same as our map function does. So let’s refactor it a little bit and replace the nested switch with the map function.</p><p>Brilliant!</p><pre>func apply&lt;B&gt;(_ f: Maybe&lt;((A) -&gt; B)&gt;) -&gt; Maybe&lt;B&gt; {<br>    guard case let .value(transform) = f else {<br>        return .none<br>    }<br>    <br>    return self.map(transform)<br>}</pre><p>Here’s something you can do with applicatives that you cannot do with functors.</p><p>How do you apply a function that takes two arguments to two wrapped values?</p><pre>func addition(_ a: Int, b: Int) -&gt; Int { a + b }</pre><p>We can also define &lt;*&gt; to help us with apply</p><pre>let a = Maybe(41)<br>let b = Maybe(1)<br><br>let result = curry(addition) &lt;^&gt; a &lt;*&gt; b</pre><p>To clarify the previous example take a look at the implementation with optional. The result is exactly the same. This is because our Maybe acts as an optional.</p><pre>let a: Int? = 41<br>let b: Int? = 1<br><br>if <br>   let a = a, <br>   let b = b {<br>    let result = addition(a, b: b) // 42    <br>}</pre><p>Look at an example on Array. Considering a sequence of Int as an applicative functor we can define an apply function even on it.</p><pre>let result =  [ { $0 + 3 }, { $0 * 2 } ] &lt;*&gt; [1, 2, 3]<br>        <br>result == [4, 5, 6, 2, 4, 6]</pre><h3>Monads</h3><p>And finally monads apply a function that returns a wrapped value to a wrapped value. Monads have a function (»= in Haskell, pronounced <em>bind</em>) to do this.</p><pre>func flatMap&lt;B&gt;(<br>    _ f: @escaping(A) -&gt; Maybe&lt;B&gt;<br>    ) -&gt; Maybe&lt;B&gt; {<br>    guard case let .value(a) = self else {<br>        return .none<br>    }<br>    <br>    switch f(a) {<br>    case .none:<br>        return .none<br>    case let .value(v):<br>        return Maybe&lt;B&gt;(v)<br>    }<br>}</pre><p>And we can define an infix operator »- Here’s how it works:</p><pre>Maybe(3) &gt;&gt;- half<br>// .none<br>Maybe(4) &gt;&gt;- half<br>// 2<br>Maybe.none &gt;&gt;- half<br>// .none</pre><p>You can also chain these calls:</p><pre>let result = Maybe(20) &gt;&gt;- half &gt;&gt;- half<br>// 5</pre><h3>Monads’s law</h3><p>All monads type should obey the three monad laws:</p><ul><li>Left identity:</li><li>Right identity:</li><li>Associativity</li></ul><p>references at <a href="https://wiki.haskell.org/Monad_laws">Haskell — monad laws</a></p><p>For brevity, we are going to consider just the associativity law, which leads us to define the monad composition operator (aka Kleisli operator)</p><pre>func &gt;=&gt;&lt;A, B, C&gt;(<br>    _ lhs: @escaping(A) -&gt; Maybe&lt;B&gt;,<br>    _ rhs: @escaping(B) -&gt; Maybe&lt;C&gt;<br>) -&gt; (A) -&gt; Maybe&lt;C&gt;</pre><p>The Kleisli operator unlocks the power to compose flatMap in a consistent way.</p><pre>let fancy: (Int) -&gt; Maybe&lt;String&gt; = { Maybe.value(&quot;fancy \($0)&quot;) }<br><br>let compute =<br>    half(_:)<br>    &gt;=&gt; incr(_:)<br>    &gt;=&gt; fancy<br><br>let result = compute(100) <br><br>// &quot;fancy 51&quot;</pre><h3>Conclusion</h3><p>Functors, Applicative functors, and Monads have conquered the world of functional programming by providing general and powerful ways of describing effectful computations using pure functions.</p><p>so, in a nutshell</p><p>A functor is a type that implements map.</p><p>An applicative is a type that implements apply.</p><p>A monad is a type that implements flatMap.</p><p>What we have done in this article is to define again the Optional type with our Maybe just to demonstrate that we can consider Optional as a Monad</p><h3>What&#39;s the point?</h3><p>Everything is bright and shiny, but it&#39;s time to ask ourselves which kind of benefits we can take from the functional approach, and the answer is pretty much crystal clear: <strong>composition.</strong></p><p>All we have seen in this article are just forms of composition.</p><p>This concept drives us to another question: <strong>why composition?</strong></p><blockquote>Because compositionality is the only way to handle complexity</blockquote><p>Basically, when we face a problem</p><ul><li>Take it in a part</li><li>Solve every single piece</li><li>Combine the solution</li></ul><p>Let&#39;s think about the compactMap function, which is simply a composition of two functions, a map { $0 } and a filter { $0 != nil }. The point is that we can handle complexity by simplifying the code.</p><h3>References</h3><p><a href="https://www.adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html">Monads in picture</a></p><p><a href="https://github.com/pointfreeco/swift-composable-architecture">The Composable Architecture</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64afcfdbdf85" width="1" height="1" alt=""><hr><p><a href="https://proudlynerd.vidiemme.it/swift-is-not-a-functional-language-but-64afcfdbdf85">Swift is not a functional language, but…</a> was originally published in <a href="https://proudlynerd.vidiemme.it/">Proudly Nerd by Vidiemme</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>