<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://ernestobossi.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://ernestobossi.com/" rel="alternate" type="text/html" /><updated>2026-05-16T10:01:41-03:00</updated><id>https://ernestobossi.com/feed.xml</id><title type="html">Ernesto Bossi</title><subtitle>My Blog of random thoughts and coding...</subtitle><author><name>Ernesto Bossi</name></author><entry><title type="html">Intro to Monad Writers and Readers in Scala</title><link href="https://ernestobossi.com/fucntional%20programming/scala/monad-writer-reader/" rel="alternate" type="text/html" title="Intro to Monad Writers and Readers in Scala" /><published>2026-05-16T00:00:00-03:00</published><updated>2026-05-16T00:00:00-03:00</updated><id>https://ernestobossi.com/fucntional%20programming/scala/monad-writer-reader</id><content type="html" xml:base="https://ernestobossi.com/fucntional%20programming/scala/monad-writer-reader/"><![CDATA[<h1 id="understanding-reader-and-writer-monads-in-scala">Understanding Reader and Writer Monads in Scala</h1>

<h2 id="intro">Intro</h2>

<p>In functional programming, monads are a design pattern used to structure computations in a way that keeps side effects, context, or sequencing under control while still allowing code to remain composable and declarative. A monad can be understood as a type constructor together with two essential operations: one that places a value into the monadic context (commonly called pure or unit) and another that chains computations while preserving that context (commonly called flatMap or bind). In Scala, monads are deeply integrated into the language through constructs such as Option, Future, Either, and collections. The for comprehension syntax is syntactic sugar over repeated calls to flatMap and map, which makes monadic code readable while still preserving the mathematical structure underneath. Monads help developers model computations that may fail, computations that are asynchronous, computations with shared environments, or computations that accumulate effects, all without scattering imperative state management throughout the codebase.</p>

<h3 id="intro-to-reader-monad">Intro to Reader Monad</h3>

<p>The Reader monad is a specialized monad used to model computations that depend on a shared, immutable environment. Instead of passing configuration or contextual objects manually through every function call, the Reader monad encapsulates functions of the form Env =&gt; A, where Env is the shared environment and A is the resulting value. Conceptually, the Reader monad represents “a computation that can read from some context.” This is particularly useful in applications where many services depend on common configuration, database connections, repositories, or runtime context. In Scala, the Reader monad is commonly implemented either manually or through libraries such as Cats. Using Readers promotes dependency injection through composition rather than mutable global state or heavyweight frameworks. A Reader computation can be combined with others while implicitly threading the environment through all steps. For example, if an application has a configuration object containing database settings and API keys, multiple Reader computations can access this configuration without explicitly receiving it as a parameter in every intermediate function.</p>

<p>In Scala, a simple Reader monad can be represented as a case class wrapping a function from an environment to a value. The map operation transforms the produced value while leaving the environment untouched, and flatMap allows chaining computations that themselves depend on the same environment. This enables elegant composition using for comprehensions. A typical Reader implementation might define case class Reader<a href="run: E =&gt; A">E, A</a>. The flatMap method takes a function from A to another Reader[E, B] and produces a new Reader that feeds the same environment through both computations. This allows business logic to remain pure and testable because dependencies are represented explicitly as values rather than hidden global state. In large Scala systems, Reader-based patterns are often used alongside tagless-final architectures or effect systems such as Cats Effect and ZIO.</p>

<h3 id="intro-to-writer-monad">Intro to Writer Monad</h3>

<p>The Writer monad, in contrast, is designed to carry along an additional accumulated output while computations execute. Rather than reading from a shared environment, the Writer monad augments computations with a log, trace, or auxiliary piece of information. Conceptually, a Writer represents a pair (Log, A), where A is the computation result and Log is some accumulated metadata. The log type must support combination, usually through a mathematical structure called a monoid, meaning there is an identity value and an associative way to combine logs. In practice, Writer monads are useful for debugging, audit trails, execution traces, metrics collection, or compiler passes where intermediate information should be preserved without introducing mutable variables or side effects.</p>

<p>In Scala, the Writer monad can also be implemented manually or obtained through functional libraries like Cats. A basic implementation might use case class Writer<a href="log: L, value: A">L, A</a>. The map operation transforms the value while preserving the log, whereas flatMap combines the logs from sequential computations while propagating the resulting value forward. Because log accumulation is automatic, developers can build pipelines of computations that transparently collect information about what occurred during execution. For example, a sequence of arithmetic operations could record every intermediate step without manually appending strings throughout the code. This becomes especially powerful when the log is not merely text but structured data such as vectors of events or performance statistics.</p>

<p>Reader and Writer monads illustrate two important aspects of functional abstraction in Scala. The Reader monad models dependency propagation, while the Writer monad models effect accumulation. Together, they demonstrate how monads generalize computation patterns into reusable compositional structures. In real-world Scala development, these monads are often combined with others through monad transformers or effect systems, enabling applications to manage configuration, logging, errors, asynchronous execution, and state in a principled and type-safe manner. Rather than relying on implicit mutable state or framework magic, Scala’s monadic approach emphasizes explicit modeling of computational behavior through types, leading to code that is easier to reason about, test, and compose.</p>

<h3 id="quick-and-practical-definition-of-monads">Quick and practical definition of Monads</h3>

<p>In functional programming abstractions that initially seem complex, but solve very practical problems once understood. One of the most important abstractions is the <strong>Monad</strong>. In Scala, monads are everywhere: <code class="language-plaintext highlighter-rouge">Option</code>, <code class="language-plaintext highlighter-rouge">Future</code>, <code class="language-plaintext highlighter-rouge">Either</code>, collections, and many functional libraries all rely on the same compositional ideas.</p>

<p>A monad can be understood as a structure that wraps values inside a context while providing a way to chain computations together. In Scala, this chaining usually happens through <code class="language-plaintext highlighter-rouge">map</code> and <code class="language-plaintext highlighter-rouge">flatMap</code>, which also power the language’s <code class="language-plaintext highlighter-rouge">for</code> comprehensions.</p>

<p>Two particularly interesting monads are the <strong>Reader</strong> and <strong>Writer</strong> monads. While they are less commonly discussed than <code class="language-plaintext highlighter-rouge">Option</code> or <code class="language-plaintext highlighter-rouge">Future</code>, they demonstrate how functional programming models dependency management and effect accumulation in a purely compositional way.</p>

<hr />

<h2 id="the-reader-monad">The Reader Monad</h2>

<p>The <strong>Reader monad</strong> models computations that depend on a shared environment.</p>

<p>Instead of manually passing configuration or services through every function call, Reader encapsulates computations of the form:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Env</span> <span class="k">=&gt;</span> <span class="n">A</span>
</code></pre></div></div>

<p>Where:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">Env</code> is some shared environment or dependency</li>
  <li><code class="language-plaintext highlighter-rouge">A</code> is the resulting value</li>
</ul>

<p>This is especially useful for dependency injection, configuration management, repositories, or service composition.</p>

<h2 id="a-simple-reader-implementation">A Simple Reader Implementation</h2>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">case</span> <span class="k">class</span> <span class="nc">AppConfig</span><span class="o">(</span><span class="n">apiUrl</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">apiKey</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span>

<span class="k">case</span> <span class="k">class</span> <span class="nc">Reader</span><span class="o">[</span><span class="kt">Env</span>, <span class="kt">A</span><span class="o">](</span><span class="n">run</span><span class="k">:</span> <span class="kt">Env</span> <span class="o">=&gt;</span> <span class="n">A</span><span class="o">)</span> <span class="o">{</span>

  <span class="k">def</span> <span class="nf">map</span><span class="o">[</span><span class="kt">B</span><span class="o">](</span><span class="n">f</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="n">B</span><span class="o">)</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">Env</span>, <span class="kt">B</span><span class="o">]</span> <span class="k">=</span>
    <span class="nc">Reader</span><span class="o">(</span><span class="n">env</span> <span class="k">=&gt;</span> <span class="nf">f</span><span class="o">(</span><span class="nf">run</span><span class="o">(</span><span class="n">env</span><span class="o">)))</span>

  <span class="k">def</span> <span class="nf">flatMap</span><span class="o">[</span><span class="kt">B</span><span class="o">](</span><span class="n">f</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="nc">Reader</span><span class="o">[</span><span class="kt">Env</span>, <span class="kt">B</span><span class="o">])</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">Env</span>, <span class="kt">B</span><span class="o">]</span> <span class="k">=</span>
    <span class="nc">Reader</span><span class="o">(</span><span class="n">env</span> <span class="k">=&gt;</span> <span class="nf">f</span><span class="o">(</span><span class="nf">run</span><span class="o">(</span><span class="n">env</span><span class="o">)).</span><span class="py">run</span><span class="o">(</span><span class="n">env</span><span class="o">))</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">Reader</code> wraps a function that requires an environment.</p>

<p>Now we can define computations that depend on <code class="language-plaintext highlighter-rouge">AppConfig</code>:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">getApiUrl</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">AppConfig</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Reader</span><span class="o">(</span><span class="n">config</span> <span class="k">=&gt;</span> <span class="nv">config</span><span class="o">.</span><span class="py">apiUrl</span><span class="o">)</span>

<span class="k">def</span> <span class="nf">getApiKey</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">AppConfig</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Reader</span><span class="o">(</span><span class="n">config</span> <span class="k">=&gt;</span> <span class="nv">config</span><span class="o">.</span><span class="py">apiKey</span><span class="o">)</span>
</code></pre></div></div>

<p>And compose them:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">val</span> <span class="nv">program</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">AppConfig</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">url</span> <span class="k">&lt;-</span> <span class="n">getApiUrl</span>
    <span class="n">key</span> <span class="k">&lt;-</span> <span class="n">getApiKey</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="n">s</span><span class="s">"Calling $url with key $key"</span>
</code></pre></div></div>

<p>Finally:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">val</span> <span class="nv">config</span> <span class="k">=</span> <span class="nc">AppConfig</span><span class="o">(</span>
  <span class="n">apiUrl</span> <span class="k">=</span> <span class="s">"https://api.example.com"</span><span class="o">,</span>
  <span class="n">apiKey</span> <span class="k">=</span> <span class="s">"secret-key"</span>
<span class="o">)</span>

<span class="nf">println</span><span class="o">(</span><span class="nv">program</span><span class="o">.</span><span class="py">run</span><span class="o">(</span><span class="n">config</span><span class="o">))</span>
</code></pre></div></div>

<p>Output:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Calling</span> <span class="n">https</span><span class="o">://</span><span class="nv">api</span><span class="o">.</span><span class="py">example</span><span class="o">.</span><span class="py">com</span> <span class="k">with</span> <span class="n">key</span> <span class="n">secret</span><span class="o">-</span><span class="n">key</span>
</code></pre></div></div>

<h3 id="why-is-this-useful">Why is this useful?</h3>

<p>Without Reader, every function would need to explicitly receive <code class="language-plaintext highlighter-rouge">config</code> and manually pass it forward.</p>

<p>Reader allows the environment to flow implicitly through the computation while still remaining purely functional and testable.</p>

<p>This becomes very powerful in larger systems where many services depend on shared runtime configuration.</p>

<hr />

<h2 id="the-writer-monad">The Writer Monad</h2>

<p>While Reader propagates a shared environment, the <strong>Writer monad</strong> accumulates additional information alongside computations.</p>

<p>A Writer usually represents:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">(</span><span class="nc">Log</span><span class="o">,</span> <span class="n">A</span><span class="o">)</span>
</code></pre></div></div>

<p>Where:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">Log</code> is accumulated metadata</li>
  <li><code class="language-plaintext highlighter-rouge">A</code> is the resulting value</li>
</ul>

<p>This is useful for:</p>

<ul>
  <li>Logging</li>
  <li>Tracing execution</li>
  <li>Audit systems</li>
  <li>Compiler passes</li>
  <li>Metrics collection</li>
</ul>

<p>without relying on mutable state.</p>

<hr />

<h3 id="a-simple-writer-implementation">A Simple Writer Implementation</h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">case</span> <span class="k">class</span> <span class="nc">Writer</span><span class="o">[</span><span class="kt">Log</span>, <span class="kt">A</span><span class="o">](</span><span class="n">log</span><span class="k">:</span> <span class="kt">Log</span><span class="o">,</span> <span class="n">value</span><span class="k">:</span> <span class="kt">A</span><span class="o">)</span> <span class="o">{</span>

  <span class="k">def</span> <span class="nf">map</span><span class="o">[</span><span class="kt">B</span><span class="o">](</span><span class="n">f</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="n">B</span><span class="o">)</span><span class="k">:</span> <span class="kt">Writer</span><span class="o">[</span><span class="kt">Log</span>, <span class="kt">B</span><span class="o">]</span> <span class="k">=</span>
    <span class="nc">Writer</span><span class="o">(</span><span class="n">log</span><span class="o">,</span> <span class="nf">f</span><span class="o">(</span><span class="n">value</span><span class="o">))</span>

  <span class="k">def</span> <span class="nf">flatMap</span><span class="o">[</span><span class="kt">B</span><span class="o">](</span><span class="n">f</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="nc">Writer</span><span class="o">[</span><span class="kt">Log</span>, <span class="kt">B</span><span class="o">])</span>
                <span class="o">(</span><span class="k">implicit</span> <span class="n">monoid</span><span class="k">:</span> <span class="kt">Monoid</span><span class="o">[</span><span class="kt">Log</span><span class="o">])</span><span class="k">:</span> <span class="kt">Writer</span><span class="o">[</span><span class="kt">Log</span>, <span class="kt">B</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>

    <span class="k">val</span> <span class="nv">next</span> <span class="k">=</span> <span class="nf">f</span><span class="o">(</span><span class="n">value</span><span class="o">)</span>

    <span class="nc">Writer</span><span class="o">(</span>
      <span class="nv">monoid</span><span class="o">.</span><span class="py">combine</span><span class="o">(</span><span class="n">log</span><span class="o">,</span> <span class="nv">next</span><span class="o">.</span><span class="py">log</span><span class="o">),</span>
      <span class="nv">next</span><span class="o">.</span><span class="py">value</span>
    <span class="o">)</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The Writer requires a way to combine logs, so we define a <code class="language-plaintext highlighter-rouge">Monoid</code>.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">trait</span> <span class="nc">Monoid</span><span class="o">[</span><span class="kt">A</span><span class="o">]</span> <span class="o">{</span>
  <span class="k">def</span> <span class="nf">empty</span><span class="k">:</span> <span class="kt">A</span>
  <span class="k">def</span> <span class="nf">combine</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">A</span><span class="o">,</span> <span class="n">y</span><span class="k">:</span> <span class="kt">A</span><span class="o">)</span><span class="k">:</span> <span class="kt">A</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Example for logs stored as <code class="language-plaintext highlighter-rouge">List[String]</code>:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">implicit</span> <span class="k">val</span> <span class="nv">stringListMonoid</span><span class="k">:</span> <span class="kt">Monoid</span><span class="o">[</span><span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]]</span> <span class="k">=</span>
  <span class="k">new</span> <span class="nc">Monoid</span><span class="o">[</span><span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]]</span> <span class="o">{</span>

    <span class="k">def</span> <span class="nf">empty</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Nil</span>

    <span class="k">def</span> <span class="nf">combine</span><span class="o">(</span>
      <span class="n">x</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">],</span>
      <span class="n">y</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>
    <span class="o">)</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span> <span class="k">=</span>
      <span class="n">x</span> <span class="o">++</span> <span class="n">y</span>
  <span class="o">}</span>
</code></pre></div></div>

<p>Now we can define computations that accumulate logs.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">addOne</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">Writer</span><span class="o">[</span><span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>, <span class="kt">Int</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Writer</span><span class="o">(</span>
    <span class="nc">List</span><span class="o">(</span><span class="n">s</span><span class="s">"Added one to $x"</span><span class="o">),</span>
    <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
  <span class="o">)</span>

<span class="k">def</span> <span class="nf">multiplyByTwo</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">Writer</span><span class="o">[</span><span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>, <span class="kt">Int</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Writer</span><span class="o">(</span>
    <span class="nc">List</span><span class="o">(</span><span class="n">s</span><span class="s">"Multiplied $x by two"</span><span class="o">),</span>
    <span class="n">x</span> <span class="o">*</span> <span class="mi">2</span>
  <span class="o">)</span>
</code></pre></div></div>

<p>And compose them:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">val</span> <span class="nv">result</span> <span class="k">=</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">a</span> <span class="k">&lt;-</span> <span class="nf">addOne</span><span class="o">(</span><span class="mi">3</span><span class="o">)</span>
    <span class="n">b</span> <span class="k">&lt;-</span> <span class="nf">multiplyByTwo</span><span class="o">(</span><span class="n">a</span><span class="o">)</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="n">b</span>
</code></pre></div></div>

<p>Reading the result:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">println</span><span class="o">(</span><span class="nv">result</span><span class="o">.</span><span class="py">value</span><span class="o">)</span>
<span class="nf">println</span><span class="o">(</span><span class="nv">result</span><span class="o">.</span><span class="py">log</span><span class="o">)</span>
</code></pre></div></div>

<p>Output:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="mi">8</span>

<span class="nc">List</span><span class="o">(</span>
  <span class="nc">Added</span> <span class="n">one</span> <span class="n">to</span> <span class="mi">3</span><span class="o">,</span>
  <span class="nc">Multiplied</span> <span class="mi">4</span> <span class="n">by</span> <span class="n">two</span>
<span class="o">)</span>
</code></pre></div></div>

<h3 id="why-is-this-useful-1">Why is this useful?</h3>

<p>Instead of mutating a global logger or printing directly inside functions, Writer allows logs to be accumulated as part of the computation itself.</p>

<p>This keeps the code pure and composable while still preserving execution information.</p>

<hr />

<h2 id="using-reader-and-writer-with-cats">Using Reader and Writer with Cats</h2>

<p>In real Scala projects, developers usually rely on functional libraries like Cats instead of implementing monads manually.</p>

<h3 id="reader-with-cats">Reader with Cats</h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">cats.data.Reader</span>
<span class="k">import</span> <span class="nn">cats.implicits._</span>

<span class="k">case</span> <span class="k">class</span> <span class="nc">Config</span><span class="o">(</span><span class="n">databaseUrl</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span>

<span class="k">val</span> <span class="nv">readDatabaseUrl</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">Config</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Reader</span><span class="o">(</span><span class="n">config</span> <span class="k">=&gt;</span> <span class="nv">config</span><span class="o">.</span><span class="py">databaseUrl</span><span class="o">)</span>

<span class="k">val</span> <span class="nv">readerProgram</span><span class="k">:</span> <span class="kt">Reader</span><span class="o">[</span><span class="kt">Config</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">db</span> <span class="k">&lt;-</span> <span class="n">readDatabaseUrl</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="n">s</span><span class="s">"Connecting to $db"</span>

<span class="nf">println</span><span class="o">(</span>
  <span class="nv">readerProgram</span><span class="o">.</span><span class="py">run</span><span class="o">(</span>
    <span class="nc">Config</span><span class="o">(</span><span class="s">"localhost:5432"</span><span class="o">)</span>
  <span class="o">)</span>
<span class="o">)</span>
</code></pre></div></div>

<h3 id="writer-with-cats">Writer with Cats</h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">cats.data.Writer</span>
<span class="k">import</span> <span class="nn">cats.implicits._</span>

<span class="k">type</span> <span class="kt">Logged</span><span class="o">[</span><span class="kt">A</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Writer</span><span class="o">[</span><span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>, <span class="kt">A</span><span class="o">]</span>

<span class="k">def</span> <span class="nf">divide</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">y</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">Logged</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Writer</span><span class="o">(</span>
    <span class="nc">List</span><span class="o">(</span><span class="n">s</span><span class="s">"Dividing $x by $y"</span><span class="o">),</span>
    <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
  <span class="o">)</span>

<span class="k">def</span> <span class="nf">increment</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">Logged</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span> <span class="k">=</span>
  <span class="nc">Writer</span><span class="o">(</span>
    <span class="nc">List</span><span class="o">(</span><span class="n">s</span><span class="s">"Incrementing $x"</span><span class="o">),</span>
    <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
  <span class="o">)</span>

<span class="k">val</span> <span class="nv">loggedProgram</span> <span class="k">=</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">a</span> <span class="k">&lt;-</span> <span class="nf">divide</span><span class="o">(</span><span class="mi">10</span><span class="o">,</span> <span class="mi">2</span><span class="o">)</span>
    <span class="n">b</span> <span class="k">&lt;-</span> <span class="nf">increment</span><span class="o">(</span><span class="n">a</span><span class="o">)</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="n">b</span>

<span class="nf">val</span> <span class="o">(</span><span class="n">logs</span><span class="o">,</span> <span class="n">value</span><span class="o">)</span> <span class="k">=</span>
  <span class="nv">loggedProgram</span><span class="o">.</span><span class="py">run</span>

<span class="nf">println</span><span class="o">(</span><span class="n">value</span><span class="o">)</span>
<span class="nf">println</span><span class="o">(</span><span class="n">logs</span><span class="o">)</span>
</code></pre></div></div>

<hr />

<h1 id="final-thoughts">Final Thoughts</h1>

<p>The Reader and Writer monads showcase how functional programming can model complex application behavior in a purely compositional way. The <strong>Reader</strong> propagates shared dependencies and configuration, while the <strong>Writer</strong> accumulates logs and metadata.
Both help avoid hidden mutable state while improving modularity, composability, and testability. In Scala, these abstractions become even more powerful when combined with libraries such as Cats, Cats Effect, or ZIO, forming the foundation for modern functional application design.</p>]]></content><author><name>Ernesto Bossi</name></author><category term="Fucntional Programming" /><category term="Scala" /><category term="Scala" /><category term="Monads" /><category term="Functional Programaming" /><summary type="html"><![CDATA[Monad Writers and Readers. Use in Scala]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://ernestobossi.com/assets/blog-images/monad.png" /><media:content medium="image" url="https://ernestobossi.com/assets/blog-images/monad.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Union type in Scala</title><link href="https://ernestobossi.com/union%20types/scala/functional%20programming/union-types-scala/" rel="alternate" type="text/html" title="Union type in Scala" /><published>2026-05-02T00:00:00-03:00</published><updated>2026-05-02T00:00:00-03:00</updated><id>https://ernestobossi.com/union%20types/scala/functional%20programming/union-types-scala</id><content type="html" xml:base="https://ernestobossi.com/union%20types/scala/functional%20programming/union-types-scala/"><![CDATA[<h1 id="folding-union-types-in-scala-2-and-scala-3">Folding Union Types in Scala 2 and Scala 3</h1>

<h2 id="introduction">Introduction</h2>

<p>Union types represent values that may belong to one among multiple possible types. While this feature is built directly into Scala 3 through the <code class="language-plaintext highlighter-rouge">|</code> operator, Scala 2 required developers to rely on advanced type-level encodings in order to approximate similar behavior.</p>

<p>One of the most well-known approaches used logical encodings inspired by the Curry–Howard correspondence, allowing union-like constraints to be represented through negation and double negation. Although these techniques were never native language features, they demonstrated the expressive power of Scala’s type system and became a notable example of type-level programming in Scala 2.</p>

<p>This article presents a <code class="language-plaintext highlighter-rouge">foldUnion</code> implementation for both Scala 2 and Scala 3. The Scala 2 version uses a classical union encoding combined with runtime dispatch, while the Scala 3 version illustrates how native union types simplify the same idea considerably.</p>

<hr />

<h2 id="union-type-encoding-in-scala-2">Union Type Encoding in Scala 2</h2>

<p>A common Scala 2 encoding for union types is the following:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">type</span> <span class="kt">¬</span><span class="err">[</span><span class="kt">A</span><span class="err">]</span> <span class="o">=</span> <span class="n">A</span> <span class="k">=&gt;</span> <span class="nc">Nothing</span>
<span class="k">type</span> <span class="kt">∨</span><span class="err">[</span><span class="kt">T</span><span class="o">,</span> <span class="n">U</span><span class="err">]</span> <span class="k">=</span> <span class="o">¬[</span><span class="kt">¬</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span> <span class="kt">with</span> <span class="kt">¬</span><span class="o">[</span><span class="kt">U</span><span class="o">]]</span>
<span class="k">type</span> <span class="kt">¬¬</span><span class="err">[</span><span class="kt">A</span><span class="err">]</span> <span class="o">=</span> <span class="o">¬[</span><span class="kt">¬</span><span class="o">[</span><span class="kt">A</span><span class="o">]]</span>

<span class="k">type</span> <span class="kt">|∨|</span><span class="err">[</span><span class="kt">T</span><span class="o">,</span> <span class="n">U</span><span class="err">]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">type</span> <span class="kt">λ</span><span class="o">[</span><span class="kt">X</span><span class="o">]</span> <span class="k">=</span> <span class="o">¬¬[</span><span class="kt">X</span><span class="o">]</span> <span class="o">&lt;:&lt;</span> <span class="o">(</span><span class="n">T</span> <span class="o">∨</span> <span class="n">U</span><span class="o">)</span>
<span class="o">}</span>
</code></pre></div></div>

<p>This encoding relies on logical negation and double negation in order to express type-level disjunction.</p>

<p>Using this construction, we can constrain a type parameter as follows:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">size</span><span class="o">[</span><span class="kt">T:</span> <span class="o">(</span><span class="kt">Int</span> <span class="kt">|∨|</span> <span class="kt">String</span><span class="o">)</span><span class="k">#</span><span class="kt">λ</span><span class="o">](</span><span class="n">t</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span> <span class="o">???</span>
</code></pre></div></div>

<p>Conceptually, this expresses that <code class="language-plaintext highlighter-rouge">T</code> must belong to the union <code class="language-plaintext highlighter-rouge">Int ∨ String</code>.</p>

<p>Although this is not a native union type, it provides a useful compile-time restriction and enables APIs that resemble union-based programming.</p>

<hr />

<h2 id="an-improved-foldunion-for-scala-2">An Improved <code class="language-plaintext highlighter-rouge">foldUnion</code> for Scala 2</h2>

<p>The following implementation modernizes the original approach by using <code class="language-plaintext highlighter-rouge">ClassTag</code> instead of <code class="language-plaintext highlighter-rouge">ClassManifest</code>, handling primitive boxing explicitly, and providing clearer runtime errors.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">scala.reflect.ClassTag</span>

<span class="k">type</span> <span class="kt">¬</span><span class="err">[</span><span class="kt">A</span><span class="err">]</span> <span class="o">=</span> <span class="n">A</span> <span class="k">=&gt;</span> <span class="nc">Nothing</span>
<span class="k">type</span> <span class="kt">∨</span><span class="err">[</span><span class="kt">T</span><span class="o">,</span> <span class="n">U</span><span class="err">]</span> <span class="k">=</span> <span class="o">¬[</span><span class="kt">¬</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span> <span class="kt">with</span> <span class="kt">¬</span><span class="o">[</span><span class="kt">U</span><span class="o">]]</span>
<span class="k">type</span> <span class="kt">¬¬</span><span class="err">[</span><span class="kt">A</span><span class="err">]</span> <span class="o">=</span> <span class="o">¬[</span><span class="kt">¬</span><span class="o">[</span><span class="kt">A</span><span class="o">]]</span>

<span class="k">type</span> <span class="kt">|∨|</span><span class="err">[</span><span class="kt">T</span><span class="o">,</span> <span class="n">U</span><span class="err">]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">type</span> <span class="kt">λ</span><span class="o">[</span><span class="kt">X</span><span class="o">]</span> <span class="k">=</span> <span class="o">¬¬[</span><span class="kt">X</span><span class="o">]</span> <span class="o">&lt;:&lt;</span> <span class="o">(</span><span class="n">T</span> <span class="o">∨</span> <span class="n">U</span><span class="o">)</span>
<span class="o">}</span>

<span class="k">final</span> <span class="k">class</span> <span class="nc">FoldUnionOps</span><span class="o">[</span><span class="kt">T</span><span class="o">](</span><span class="k">private</span> <span class="k">val</span> <span class="nv">value</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">AnyVal</span> <span class="o">{</span>

  <span class="k">private</span> <span class="k">def</span> <span class="nf">boxed</span><span class="o">(</span><span class="n">c</span><span class="k">:</span> <span class="kt">Class</span><span class="o">[</span><span class="k">_</span><span class="o">])</span><span class="k">:</span> <span class="kt">Class</span><span class="o">[</span><span class="k">_</span><span class="o">]</span> <span class="k">=</span>
    <span class="nf">if</span> <span class="o">(!</span><span class="nv">c</span><span class="o">.</span><span class="py">isPrimitive</span><span class="o">)</span> <span class="n">c</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Integer</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Integer</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Long</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Long</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Double</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Double</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Float</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Float</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Short</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Short</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Byte</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Byte</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Character</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Character</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Boolean</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Boolean</span><span class="o">]</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">c</span> <span class="o">==</span> <span class="nv">java</span><span class="o">.</span><span class="py">lang</span><span class="o">.</span><span class="py">Void</span><span class="o">.</span><span class="py">TYPE</span><span class="o">)</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">java.lang.Void</span><span class="o">]</span>
    <span class="k">else</span> <span class="n">c</span>

  <span class="k">private</span> <span class="k">def</span> <span class="nf">isSubtypeOf</span><span class="o">(</span><span class="n">actual</span><span class="k">:</span> <span class="kt">Class</span><span class="o">[</span><span class="k">_</span><span class="o">],</span> <span class="n">expected</span><span class="k">:</span> <span class="kt">Class</span><span class="o">[</span><span class="k">_</span><span class="o">])</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="o">=</span>
    <span class="nv">expected</span><span class="o">.</span><span class="py">isAssignableFrom</span><span class="o">(</span><span class="n">actual</span><span class="o">)</span> <span class="o">||</span>
      <span class="nf">boxed</span><span class="o">(</span><span class="n">expected</span><span class="o">).</span><span class="py">isAssignableFrom</span><span class="o">(</span><span class="nf">boxed</span><span class="o">(</span><span class="n">actual</span><span class="o">))</span>

  <span class="k">def</span> <span class="nf">foldUnion</span><span class="o">[</span><span class="kt">A</span>, <span class="kt">B</span>, <span class="kt">S</span><span class="o">](</span>
    <span class="n">fa</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="n">S</span><span class="o">,</span>
    <span class="n">fb</span><span class="k">:</span> <span class="kt">B</span> <span class="o">=&gt;</span> <span class="n">S</span>
  <span class="o">)(</span><span class="k">implicit</span>
    <span class="n">ev</span><span class="k">:</span> <span class="kt">¬¬</span><span class="err">[</span><span class="kt">T</span><span class="err">]</span> <span class="k">&lt;:</span><span class="kt">&lt;</span> <span class="o">(</span><span class="kt">A</span> <span class="kt">∨</span> <span class="kt">B</span><span class="o">),</span>
    <span class="n">ca</span><span class="k">:</span> <span class="kt">ClassTag</span><span class="o">[</span><span class="kt">A</span><span class="o">],</span>
    <span class="n">cb</span><span class="k">:</span> <span class="kt">ClassTag</span><span class="o">[</span><span class="kt">B</span><span class="o">]</span>
  <span class="o">)</span><span class="k">:</span> <span class="kt">S</span> <span class="o">=</span> <span class="o">{</span>

    <span class="nf">if</span> <span class="o">(</span><span class="n">value</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
      <span class="k">throw</span> <span class="k">new</span> <span class="nc">MatchError</span><span class="o">(</span><span class="s">"Cannot fold null as a union value"</span><span class="o">)</span>
    <span class="o">}</span>

    <span class="k">val</span> <span class="nv">actual</span> <span class="k">=</span> <span class="nv">value</span><span class="o">.</span><span class="py">asInstanceOf</span><span class="o">[</span><span class="kt">AnyRef</span><span class="o">].</span><span class="py">getClass</span>

    <span class="nf">if</span> <span class="o">(</span><span class="nf">isSubtypeOf</span><span class="o">(</span><span class="n">actual</span><span class="o">,</span> <span class="nv">ca</span><span class="o">.</span><span class="py">runtimeClass</span><span class="o">))</span>
      <span class="nf">fa</span><span class="o">(</span><span class="nv">value</span><span class="o">.</span><span class="py">asInstanceOf</span><span class="o">[</span><span class="kt">A</span><span class="o">])</span>
    <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="nf">isSubtypeOf</span><span class="o">(</span><span class="n">actual</span><span class="o">,</span> <span class="nv">cb</span><span class="o">.</span><span class="py">runtimeClass</span><span class="o">))</span>
      <span class="nf">fb</span><span class="o">(</span><span class="nv">value</span><span class="o">.</span><span class="py">asInstanceOf</span><span class="o">[</span><span class="kt">B</span><span class="o">])</span>
    <span class="k">else</span>
      <span class="k">throw</span> <span class="k">new</span> <span class="nc">MatchError</span><span class="o">(</span>
        <span class="n">s</span><span class="s">"Runtime class ${actual.getName} did not match either branch"</span>
      <span class="o">)</span>
  <span class="o">}</span>
<span class="o">}</span>

<span class="k">implicit</span> <span class="k">def</span> <span class="nf">toFoldUnionOps</span><span class="o">[</span><span class="kt">T</span><span class="o">](</span><span class="n">value</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span><span class="k">:</span> <span class="kt">FoldUnionOps</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span> <span class="k">=</span>
  <span class="k">new</span> <span class="nc">FoldUnionOps</span><span class="o">(</span><span class="n">value</span><span class="o">)</span>
</code></pre></div></div>

<hr />

<h2 id="using-foldunion">Using <code class="language-plaintext highlighter-rouge">foldUnion</code></h2>

<p>We can now define operations over union-like values.</p>

<h3 id="example-int--string">Example: <code class="language-plaintext highlighter-rouge">Int | String</code></h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">size</span><span class="o">[</span><span class="kt">T:</span> <span class="o">(</span><span class="kt">Int</span> <span class="kt">|∨|</span> <span class="kt">String</span><span class="o">)</span><span class="k">#</span><span class="kt">λ</span><span class="o">](</span><span class="n">t</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span>
  <span class="nv">t</span><span class="o">.</span><span class="py">foldUnion</span><span class="o">(</span>
    <span class="o">(</span><span class="n">i</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">i</span><span class="o">,</span>
    <span class="o">(</span><span class="n">s</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">length</span>
  <span class="o">)</span>
</code></pre></div></div>

<p>Usage:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">size</span><span class="o">(</span><span class="mi">10</span><span class="o">)</span>
<span class="c1">// 10</span>

<span class="nf">size</span><span class="o">(</span><span class="s">"hello"</span><span class="o">)</span>
<span class="c1">// 5</span>
</code></pre></div></div>

<p>Attempting to use an unsupported type fails at compile time:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">size</span><span class="o">(</span><span class="mf">3.14</span><span class="o">)</span>
<span class="c1">// does not compile</span>
</code></pre></div></div>

<hr />

<h3 id="example-boolean--string">Example: <code class="language-plaintext highlighter-rouge">Boolean | String</code></h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">describe</span><span class="o">[</span><span class="kt">T:</span> <span class="o">(</span><span class="kt">Boolean</span> <span class="kt">|∨|</span> <span class="kt">String</span><span class="o">)</span><span class="k">#</span><span class="kt">λ</span><span class="o">](</span><span class="n">t</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=</span>
  <span class="nv">t</span><span class="o">.</span><span class="py">foldUnion</span><span class="o">(</span>
    <span class="o">(</span><span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nf">if</span> <span class="o">(</span><span class="n">b</span><span class="o">)</span> <span class="s">"enabled"</span> <span class="k">else</span> <span class="s">"disabled"</span><span class="o">,</span>
    <span class="o">(</span><span class="n">s</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span>  <span class="k">=&gt;</span> <span class="n">s</span><span class="s">"message: $s"</span>
  <span class="o">)</span>
</code></pre></div></div>

<p>Usage:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">describe</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span>
<span class="c1">// enabled</span>

<span class="nf">describe</span><span class="o">(</span><span class="s">"system online"</span><span class="o">)</span>
<span class="c1">// message: system online</span>
</code></pre></div></div>

<hr />

<h2 id="limitations-of-the-scala-2-approach">Limitations of the Scala 2 Approach</h2>

<p>Although the encoding is elegant from a type-theoretical perspective, the implementation still depends on runtime class inspection and casting.</p>

<p>This introduces several limitations.</p>

<h3 id="overlapping-types">Overlapping Types</h3>

<p>Consider:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">example</span><span class="o">[</span><span class="kt">T:</span> <span class="o">(</span><span class="kt">AnyRef</span> <span class="kt">|∨|</span> <span class="kt">String</span><span class="o">)</span><span class="k">#</span><span class="kt">λ</span><span class="o">](</span><span class="n">t</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=</span>
  <span class="nv">t</span><span class="o">.</span><span class="py">foldUnion</span><span class="o">(</span>
    <span class="o">(</span><span class="k">_:</span> <span class="kt">AnyRef</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="s">"any reference"</span><span class="o">,</span>
    <span class="o">(</span><span class="k">_:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="s">"string"</span>
  <span class="o">)</span>
</code></pre></div></div>

<p>Since <code class="language-plaintext highlighter-rouge">String</code> is also an <code class="language-plaintext highlighter-rouge">AnyRef</code>, the first branch will match first. Therefore, branch ordering becomes significant.</p>

<hr />

<h3 id="type-erasure">Type Erasure</h3>

<p>Generic types cannot be distinguished safely at runtime:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">List</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="nc">List</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>
</code></pre></div></div>

<p>Both erase to <code class="language-plaintext highlighter-rouge">List</code>, making runtime dispatch ambiguous.</p>

<hr />

<h3 id="null-values">Null Values</h3>

<p>The implementation explicitly rejects <code class="language-plaintext highlighter-rouge">null</code> values with a <code class="language-plaintext highlighter-rouge">MatchError</code> in order to avoid confusing runtime failures.</p>

<hr />

<h2 id="scala-3-and-native-union-types">Scala 3 and Native Union Types</h2>

<p>Scala 3 introduces union types directly into the language:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">size</span><span class="o">(</span><span class="n">value</span><span class="k">:</span> <span class="kt">Int</span> <span class="kt">|</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span>
  <span class="n">value</span> <span class="k">match</span>
    <span class="k">case</span> <span class="n">i</span><span class="k">:</span> <span class="kt">Int</span>    <span class="o">=&gt;</span> <span class="n">i</span>
    <span class="k">case</span> <span class="n">s</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">length</span>
</code></pre></div></div>

<p>This eliminates the need for type-level encodings entirely.</p>

<p>The resulting code is substantially simpler and more expressive.</p>

<hr />

<h2 id="a-scala-3-foldunion">A Scala 3 <code class="language-plaintext highlighter-rouge">foldUnion</code></h2>

<p>Although direct pattern matching is generally preferable, it is still possible to define a <code class="language-plaintext highlighter-rouge">foldUnion</code> helper in Scala 3.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">scala.reflect.ClassTag</span>

<span class="n">extension</span> <span class="o">[</span><span class="kt">A</span>, <span class="kt">B</span><span class="o">](</span><span class="n">value</span><span class="k">:</span> <span class="kt">A</span> <span class="kt">|</span> <span class="kt">B</span><span class="o">)</span>
  <span class="k">def</span> <span class="nf">foldUnion</span><span class="o">[</span><span class="kt">S</span><span class="o">](</span>
    <span class="n">fa</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="n">S</span><span class="o">,</span>
    <span class="n">fb</span><span class="k">:</span> <span class="kt">B</span> <span class="o">=&gt;</span> <span class="n">S</span>
  <span class="o">)(</span><span class="n">using</span> <span class="n">ca</span><span class="k">:</span> <span class="kt">ClassTag</span><span class="o">[</span><span class="kt">A</span><span class="o">],</span> <span class="n">cb</span><span class="k">:</span> <span class="kt">ClassTag</span><span class="o">[</span><span class="kt">B</span><span class="o">])</span><span class="k">:</span> <span class="kt">S</span> <span class="o">=</span>
    <span class="n">value</span> <span class="k">match</span>
      <span class="k">case</span> <span class="kc">null</span> <span class="k">=&gt;</span>
        <span class="k">throw</span> <span class="nc">MatchError</span><span class="o">(</span><span class="s">"Cannot fold null as a union value"</span><span class="o">)</span>

      <span class="k">case</span> <span class="n">v</span> <span class="k">if</span> <span class="nv">ca</span><span class="o">.</span><span class="py">runtimeClass</span><span class="o">.</span><span class="py">isInstance</span><span class="o">(</span><span class="n">v</span><span class="o">)</span> <span class="k">=&gt;</span>
        <span class="nf">fa</span><span class="o">(</span><span class="nv">v</span><span class="o">.</span><span class="py">asInstanceOf</span><span class="o">[</span><span class="kt">A</span><span class="o">])</span>

      <span class="k">case</span> <span class="n">v</span> <span class="k">if</span> <span class="nv">cb</span><span class="o">.</span><span class="py">runtimeClass</span><span class="o">.</span><span class="py">isInstance</span><span class="o">(</span><span class="n">v</span><span class="o">)</span> <span class="k">=&gt;</span>
        <span class="nf">fb</span><span class="o">(</span><span class="nv">v</span><span class="o">.</span><span class="py">asInstanceOf</span><span class="o">[</span><span class="kt">B</span><span class="o">])</span>

      <span class="k">case</span> <span class="n">v</span> <span class="k">=&gt;</span>
        <span class="k">throw</span> <span class="nc">MatchError</span><span class="o">(</span>
          <span class="n">s</span><span class="s">"Runtime class ${v.getClass.getName} did not match either branch"</span>
        <span class="o">)</span>
</code></pre></div></div>

<p>Usage:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">size</span><span class="o">(</span><span class="n">value</span><span class="k">:</span> <span class="kt">Int</span> <span class="kt">|</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span>
  <span class="nv">value</span><span class="o">.</span><span class="py">foldUnion</span><span class="o">(</span>
    <span class="o">(</span><span class="n">i</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">i</span><span class="o">,</span>
    <span class="o">(</span><span class="n">s</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">length</span>
  <span class="o">)</span>
</code></pre></div></div>

<hr />

<h2 id="direct-pattern-matching-in-scala-3">Direct Pattern Matching in Scala 3</h2>

<p>In most practical Scala 3 codebases, direct pattern matching is clearer and preferable:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">describe</span><span class="o">(</span><span class="n">value</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="kt">|</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=</span>
  <span class="n">value</span> <span class="k">match</span>
    <span class="k">case</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="o">=&gt;</span> <span class="k">if</span> <span class="n">b</span> <span class="n">then</span> <span class="s">"enabled"</span> <span class="k">else</span> <span class="s">"disabled"</span>
    <span class="k">case</span> <span class="n">s</span><span class="k">:</span> <span class="kt">String</span>  <span class="o">=&gt;</span> <span class="n">s</span><span class="s">"message: $s"</span>
</code></pre></div></div>

<p>The union appears directly in the type signature:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Boolean</span> <span class="o">|</span> <span class="nc">String</span>
</code></pre></div></div>

<p>This removes the need for auxiliary encodings, type lambdas, and logical negation tricks.</p>

<hr />

<h2 id="comparison">Comparison</h2>

<h3 id="scala-2">Scala 2</h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">size</span><span class="o">[</span><span class="kt">T:</span> <span class="o">(</span><span class="kt">Int</span> <span class="kt">|∨|</span> <span class="kt">String</span><span class="o">)</span><span class="k">#</span><span class="kt">λ</span><span class="o">](</span><span class="n">t</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span>
  <span class="nv">t</span><span class="o">.</span><span class="py">foldUnion</span><span class="o">(</span>
    <span class="o">(</span><span class="n">i</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">i</span><span class="o">,</span>
    <span class="o">(</span><span class="n">s</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">length</span>
  <span class="o">)</span>
</code></pre></div></div>

<h3 id="scala-3">Scala 3</h3>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">size</span><span class="o">(</span><span class="n">t</span><span class="k">:</span> <span class="kt">Int</span> <span class="kt">|</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span>
  <span class="n">t</span> <span class="k">match</span>
    <span class="k">case</span> <span class="n">i</span><span class="k">:</span> <span class="kt">Int</span>    <span class="o">=&gt;</span> <span class="n">i</span>
    <span class="k">case</span> <span class="n">s</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">length</span>
</code></pre></div></div>

<p>The Scala 2 version is primarily interesting as an exploration of advanced type-level programming techniques. The Scala 3 version, by contrast, expresses the same intent directly in the language.</p>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>The Scala 2 <code class="language-plaintext highlighter-rouge">foldUnion</code> approach is a compelling example of how expressive Scala’s type system can be. Through logical encodings and type-level programming, developers were able to simulate union-like behavior years before native support existed.</p>

<p>However, despite the sophistication of the compile-time encoding, runtime dispatch still depends on type inspection and casting, which introduces practical limitations related to erasure and subtype overlap.</p>

<p>Scala 3 resolves these issues elegantly through native union types:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Int</span> <span class="o">|</span> <span class="nc">String</span>
</code></pre></div></div>

<p>As a result, code becomes simpler, clearer, and more maintainable while preserving the expressive power that earlier Scala 2 techniques attempted to approximate.</p>]]></content><author><name>Ernesto Bossi</name></author><category term="Union Types" /><category term="Scala" /><category term="Functional Programming" /><category term="functional" /><category term="computer science" /><summary type="html"><![CDATA[Union Types in Scala 2 and 3]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://ernestobossi.com/%7B%22path%22=%3Enil%7D" /><media:content medium="image" url="https://ernestobossi.com/%7B%22path%22=%3Enil%7D" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Installing OTP and Elixir from source code</title><link href="https://ernestobossi.com/elixir/installing-otp-elixir-source/" rel="alternate" type="text/html" title="Installing OTP and Elixir from source code" /><published>2024-06-07T00:00:00-03:00</published><updated>2024-06-07T00:00:00-03:00</updated><id>https://ernestobossi.com/elixir/installing-otp-elixir-source</id><content type="html" xml:base="https://ernestobossi.com/elixir/installing-otp-elixir-source/"><![CDATA[<p>Erlang/OTP and Elixir are both available as pre-built binary packages by most OS package managers. However, lately I’ve noticed that most of these binary packages are releasing old versions from both of these languages. 
This guide will point out a couple of ways to fetch newer and still stable versions of both of these languages.</p>

<figure>
    <a href="/assets/blog-images/natural_transformations.jpeg"><img src="/assets/blog-images/otp_elixir.png" /></a>
</figure>

<h2 id="otp">OTP</h2>

<p>We need to start installing OTP, which includes not only Erlang/OTP ecosystem but also the BEAM VM. We can fetch the code from OTP on any directory, in my case it’s <code class="language-plaintext highlighter-rouge">~/opt</code>, where i leave all my deps that i need to compile before i install them.</p>

<blockquote>
  <p>The complete building and installation instructions <a href="https://github.com/erlang/otp/blob/maint-27/HOWTO/INSTALL.md">can be found here</a>.</p>
</blockquote>

<h3 id="downloading-and-selecting-the-otp-version">Downloading and selecting the OTP version</h3>

<p>We start by downloading the OTP repository from github</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://github.com/erlang/otp
</code></pre></div></div>

<p>Checkout the branch or tag of your choice. Generally <code class="language-plaintext highlighter-rouge">maint-&lt;version&gt;</code> is recommended as these are the latest maintenance version.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout maint-27    # current latest stable version
</code></pre></div></div>

<blockquote>
  <p>If this isn’t the first time installing OTP by source and you already have installed it this way, this is a good time to run the <code class="language-plaintext highlighter-rouge">make clean</code> command in order to cleanup any setup from the previous installation. This is to prevent unwanted errors on the building step.</p>
  <h3 id="configuring">Configuring</h3>
</blockquote>

<p>Run the following commands to configure the build:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./configure [ options ]
</code></pre></div></div>

<p>By default, Erlang/OTP release will be installed in <code class="language-plaintext highlighter-rouge">/usr/local/{bin,lib/erlang}</code>. If you for instance don’t have the permission to install in the standard location, you can install Erlang/OTP somewhere else. For example, to install in <code class="language-plaintext highlighter-rouge">/opt/erlang/%OTP-VSN%/{bin,lib/erlang}</code>, use the <code class="language-plaintext highlighter-rouge">--prefix=/opt/erlang/%OTP-VSN%</code> option.</p>

<p>On some platforms Perl may behave strangely if certain locales are set. If you get errors when building, try setting the LANG variable:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ export LANG=C   # Assuming bash/sh
</code></pre></div></div>

<h3 id="building">Building</h3>

<p>Build the Erlang/OTP release.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ make
</code></pre></div></div>

<h3 id="testing">Testing</h3>

<p>Before installation you should test whether your build is working properly by running our smoke test. The smoke test is a subset of the complete Erlang/OTP test suites. First you will need to build and release the test suites.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ make release_tests
</code></pre></div></div>

<p>This creates an additional folder in <code class="language-plaintext highlighter-rouge">$ERL_TOP/release</code> called <code class="language-plaintext highlighter-rouge">tests</code>. Now, it’s time to start the smoke test.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd release/tests/test_server
$ $ERL_TOP/bin/erl -s ts install -s ts smoke_test batch -s init stop
</code></pre></div></div>

<p>To verify that everything is ok you should open <code class="language-plaintext highlighter-rouge">$ERL_TOP/release/tests/test_server/index.html</code> in your web browser and make sure that there are zero failed test cases.</p>

<blockquote>
  <h4 id="note--info-">Note {: .info }</h4>

  <p>On builds without <code class="language-plaintext highlighter-rouge">crypto</code>, <code class="language-plaintext highlighter-rouge">ssl</code> and <code class="language-plaintext highlighter-rouge">ssh</code> there is a failed test case for undefined functions. Verify that the failed test case log only shows calls to skipped applications.</p>
</blockquote>

<h3 id="installing">Installing</h3>

<p>You are now ready to install the Erlang/OTP release! The following command will install the release on your system.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ make install
</code></pre></div></div>

<h3 id="testing-1">Testing</h3>

<p>Once everything is installed, we can just run the <code class="language-plaintext highlighter-rouge">erl</code> command in order to enter the Erlang/OTP encironment.</p>

<h2 id="installing-elixir">Installing Elixir</h2>

<h2 id="retrieve-and-compile-elixir">Retrieve and compile Elixir</h2>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">mkdir</span> ~/dev
<span class="nv">$ </span><span class="nb">cd</span> ~/dev
<span class="nv">$ </span>git clone https://github.com/elixir-lang/elixir.git
<span class="nv">$ </span><span class="nb">cd </span>elixir 
<span class="nv">$ </span>make clean <span class="nb">test</span>
</code></pre></div></div>

<h3 id="fetching-exdoc">Fetching ExDoc</h3>

<p>Create a fork on GitHub at: <a href="https://github.com/elixir-lang/ex_doc">https://github.com/elixir-lang/ex_doc</a></p>

<p>Clone your fork:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">cd</span> ~/dev
<span class="nv">$ </span>git clone https://github.com/&lt;github_username&gt;/ex_doc
<span class="nv">$ </span><span class="nb">cd </span>ex_doc
<span class="nv">$ </span>git remote add upstream https://github.com/elixir-lang/ex_doc
<span class="nv">$ </span>git fetch upstream
</code></pre></div></div>

<h2 id="compile-exdoc">Compile ExDoc</h2>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">cd</span> ~/dev/ex_doc <span class="o">&amp;&amp;</span> ../elixir/bin/mix <span class="k">do </span>deps.get, compile
</code></pre></div></div>

<h2 id="how-to-use-exdoc-for-build-documentation">How to use ExDoc for build documentation</h2>

<p>For example, if we want to build Elixir documentation with ExDoc.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">cd</span> ~/dev/elixir
<span class="nv">$ </span>../ex_doc/bin/ex_doc <span class="s2">"Elixir"</span> <span class="s2">"1.16.2"</span> <span class="s2">"lib/elixir/ebin"</span> <span class="nt">-m</span> <span class="s2">"Kernel"</span> <span class="nt">-u</span> <span class="s2">"https://github.com/elixir-lang/elixir"</span> <span class="nt">-o</span> doc <span class="nt">-p</span> http://elixir-lang.org/docs.html
</code></pre></div></div>

<p>The docs can be found below the <code class="language-plaintext highlighter-rouge">doc/</code> directory</p>]]></content><author><name>Ernesto Bossi</name></author><category term="Elixir" /><category term="OTP" /><category term="Elixir" /><summary type="html"><![CDATA[A reminder of the steps i need to remind myself each time i install/update these tools]]></summary></entry><entry><title type="html">Just got a refurb laptop to my collection</title><link href="https://ernestobossi.com/random/new-laptop/" rel="alternate" type="text/html" title="Just got a refurb laptop to my collection" /><published>2019-12-09T00:00:00-03:00</published><updated>2019-12-09T00:00:00-03:00</updated><id>https://ernestobossi.com/random/new-laptop</id><content type="html" xml:base="https://ernestobossi.com/random/new-laptop/"><![CDATA[<p>I just got a refurbished laptop that i ordered on Ebay a couple of weeks ago. it’s a Lenovo X230 with an i7-3520m, with a 256gb ssd and 8gb of ram which i bumped already to 16gb. I decided to go for this laptop as i was pretty affordable and it was in a pretty good condition and didn’t need to do a whole lot of upgrades, besides the RAM and the screen which is a TN one. Also i was looking for a lightweight option to carry to the university or anywhere easily.</p>

<p>When it arrived it was a bit dusty and came with a Windows 10 installed… After a cleanup of both the OS and front and back lid (still with a scratch at the front..), i went for installing a debian buster. After 10mins i got my linux up and running.</p>

<figure>
    <a href="/assets/blog-images/natural_transformations.jpeg"><img src="/assets/blog-images/20191211_161650.jpg" /></a>
</figure>

<p>Did some tests to check the thermals and apparently i got about 49C on idle and 85C on full load, so i’ll leave the repasting for next month.</p>

<p>i was a bit concerned about the battery, which could be a lottery ticket when buying a second hand laptop, the one it came with is a 6-cell battery 44+ lenovo one, and after running this command to check the battery status:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>upower <span class="nt">-i</span> /org/freedesktop/UPower/devices/battery_BAT0
</code></pre></div></div>

<p>and got the following output</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  native-path:          BAT0
  vendor:               LGC
  model:                45N1025
  serial:               74
  power supply:         yes
  updated:              Mon 09 Dec 2019 11:24:33 PM -03 (41 seconds ago)
  has history:          yes
  has statistics:       yes
  battery
    present:             yes
    rechargeable:        yes
    state:               charging
    warning-level:       none
    energy:              45.65 Wh
    energy-empty:        0 Wh
    energy-full:         45.65 Wh
    energy-full-design:  57.72 Wh
    energy-rate:         2.437 W
    voltage:             12.567 V
    percentage:          100%
    capacity:            78.7422%
    technology:          lithium-ion
    icon-name:          'battery-full-charging-symbolic'
  History (rate):
    1576203873	2.437	charging
</code></pre></div></div>

<p>where apparently the capacity left on the battery is a bit les than 78.75%, which is pretty good so far. I’ve got about 4-5hr mark with a light use (visualstudio code + browser), so i’ll probably start looking for a new 6 or 9-cell battery later on next year, for now i think i’m pretty fine with this one.</p>

<p>So far i’m pleased with my laptop and hope to upgrade soon, probably next month the display to an IPS one.</p>]]></content><author><name>Ernesto Bossi</name></author><category term="Random" /><category term="random" /><summary type="html"><![CDATA[New laptop to my collection, my first refurbished laptop]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://ernestobossi.com/assets/blog-images/20191211_161534.jpg" /><media:content medium="image" url="https://ernestobossi.com/assets/blog-images/20191211_161534.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">An introduction to category theory, functors and monads</title><link href="https://ernestobossi.com/categories/monads/functors/introduction-catgories/" rel="alternate" type="text/html" title="An introduction to category theory, functors and monads" /><published>2019-10-26T00:00:00-03:00</published><updated>2019-10-26T00:00:00-03:00</updated><id>https://ernestobossi.com/categories/monads/functors/introduction-catgories</id><content type="html" xml:base="https://ernestobossi.com/categories/monads/functors/introduction-catgories/"><![CDATA[<p>This will be a post about category theory and the relation between it and functors, monads and monoids in Haskell/Scala. This will be kind of a long post but i’ll cut the unnecessary details as much as possible. This first part is to talk more about theory and haskell relation between monads, functors and the category theory behind them.</p>

<h1 id="category-theory-definitions">Category Theory: Definitions</h1>

<h2 id="components-of-a-category">Components of a Category</h2>

<p>Categories can be summed up as simple collections, that have the following components</p>

<ul>
  <li>A collection of objects, obj ((C))</li>
  <li>A collection of morphisms, that are caled in other computer science literature as arrows, each of which can tie two objects, a source/target object, together. We can write it as:</li>
</ul>

<script type="math/tex; mode=display">
  f: A \rightarrow B
</script>

<p>For these functions we have that A is the domain and B is the codomain of f. The collection of arrows in a category C is denoted by Arr(C)</p>

<ul>
  <li>For each object in the category, they have an identity arrow where the domain an codomain is the same object, thus:</li>
</ul>

<script type="math/tex; mode=display">
  id_A: A \rightarrow A
</script>

<ul>
  <li>A notion of composition of these morphisms/arrows. For eg. if we have these 2 morphisms:</li>
</ul>

<script type="math/tex; mode=display">
  f: A \rightarrow B
</script>

<script type="math/tex; mode=display">
  g: B \rightarrow C
</script>

<p>We can have a composed morphism of the previous two resulting in the following morphism:</p>

<script type="math/tex; mode=display">
  f \circ g: A \rightarrow C
</script>

<p>These are only the mosaics to build categories, as these rules gives some kind of freedom of what type or other properties can the categories have. These are only very basic properties that any category should have to be considered one.</p>

<p>As we see these arrows, it may seem that they are always functions, but these needn’t to be the case. For example, any partial order ((P, \leq)) defines a category where the objects are the elements of P, and there is a morphism between any two objects A and B.</p>

<h2 id="category-laws">Category Laws</h2>

<p>There are three laws that the categories need to follow.</p>

<h3 id="associative-law">Associative law</h3>

<p>Based on the following arrows:</p>

<script type="math/tex; mode=display">
 A \xrightarrow[]{f} B \xrightarrow[]{g} C \xrightarrow[]{h} D
</script>

<p>The composition of morphism needs to be Associative. Thus:</p>

<script type="math/tex; mode=display">
  f \circ (g \circ h) = (f \circ g) \circ h
</script>

<figure>
    <a href="/assets/blog-images/associative_law.jpeg"><img src="/assets/blog-images/associative_law.jpeg" /></a>
</figure>

<p>Morphisms are applies right to left in most of mathematical notications and conventions and in haskell. So if we have a composition like</p>

<script type="math/tex; mode=display">
  f \circ g
</script>

<p>g is applied first and then f.</p>

<h3 id="closed">Closed</h3>

<p>Under these compositions</p>

<script type="math/tex; mode=display">
  f : B \rightarrow C
</script>

<p>and</p>

<script type="math/tex; mode=display">
  g : A \rightarrow B
</script>

<p>then we have a morphism h where</p>

<script type="math/tex; mode=display">
  h : A \rightarrow C
</script>

<p>as seen by the composition property we can have this following representation of the category:</p>

<figure>
    <a href="/assets/blog-images/basic_category.jpeg"><img src="/assets/blog-images/basic_category.jpeg" /></a>
</figure>

<p>if now f and g are both morphisms we can compose them and get another morphism in the category so which is the morphism of f o g ? The only option is id((A)). Similarly g o f = id((B))</p>

<h3 id="identity">Identity</h3>

<p>based on the identity rule we saw previously, if we have something like</p>

<script type="math/tex; mode=display">
  A \xrightarrow[]{f} B
</script>

<p>Then we can sum up this law by:</p>

<script type="math/tex; mode=display">
  id_B \circ f = f = f \circ id_A
</script>

<h2 id="a-simple-example">A simple example</h2>

<p>We can have the following category:</p>

<figure>
    <a href="/assets/blog-images/Simple-cat2.pngg"><img src="/assets/blog-images/Simple-cat2.png" /></a>
</figure>

<p>Where this is a category, with three objects A, B and C, three identity morphisms:</p>

<script type="math/tex; mode=display">
  ob(C) = \{ id_A, id_B , id_C \}
</script>

<p>and morphisms</p>

<script type="math/tex; mode=display">
  hom(C) = \{ f: C \rightarrow B , g : A \rightarrow B \}
</script>

<p>We can then compose f and g functions to build up a composition</p>

<script type="math/tex; mode=display">
  (\circ) = { h: A \rightarrow C = g \circ f}
</script>

<p>We can see that we have even mosphisms for neutral elements or better called identity morphisms, for both A and B objects.</p>

<script type="math/tex; mode=display">
  id_B 
</script>

<h2 id="commutative-diagrams">Commutative diagrams</h2>

<p>Before moving foward with the category theory we can also represent the associative and identity laws by a directed graph diagram, where the law of composition is</p>

<figure>
    <a href="/assets/blog-images/connmutative_associative_law.jpeg"><img src="/assets/blog-images/connmutative_associative_law.jpeg" /></a>
</figure>

<script type="math/tex; mode=display">
  f \circ (g \circ h) = (f \circ g) \circ h
</script>

<p>and the law of identity is for ex:</p>

<figure>
    <a href="/assets/blog-images/conmmutatuve_arrow_identity.jpeg"><img src="/assets/blog-images/conmmutatuve_arrow_identity.jpeg" /></a>
</figure>

<script type="math/tex; mode=display">
  id_B \circ f = f = f \circ id_A
</script>

<p>We can see in both of these diagrams that the path with the same source and destination is equal, thus they are commutative, this is only true on the case we mention and also that all directed paths in the diagram with the same start and endpoints lead to the same result by composition. Geometrically a diagram is commutative if every polygonal subdiagram is commutative.</p>

<h2 id="categories-everywhere">Categories everywhere?</h2>

<p>Now that we have seen the composition and laws that the categories should have we can mention some of the categories defined and existant even in Haskell. We can mention some examples like:</p>

<ul>
  <li>Categories freely generated by directed graphs.</li>
  <li>Degenerate categories such as:</li>
  <li>
    <ul>
      <li>Sets – ie categories where all arrows are identities.</li>
    </ul>
  </li>
  <li>
    <ul>
      <li>Monoids – ie categories with only one object.</li>
    </ul>
  </li>
  <li>
    <ul>
      <li>Preorders: categories with at most one arrow between every two objects.</li>
    </ul>
  </li>
  <li>0, 1, .. , ω.</li>
  <li>Opposite categories C op: obtained by reversing the arrows of given categories C, while
keeping the same objects.</li>
  <li>Set: the category of, sometimes small, sets and functions; composition is the usual function composition, and so is in the remaining examples. Note that type matter: the identity on
the natural numbers is a different function from the inclusion of the natural numbers
into the integers.</li>
  <li>Set∗: pointed sets, ie sets with a selected base-point, and functions preserving the base
point.</li>
  <li>N: finite ordinals and functions.</li>
  <li>FinSet: finite sets and functions.</li>
  <li>Preord: preorders and monotone functions.</li>
  <li>Poset: partial orders and monotone functions</li>
  <li>Hask: Category for defining haskell types</li>
</ul>

<p>These are some examples only to mention we’ll go deeper into some of them later but what are the differences of each of them? Well mentioned before the characteristics of the category and laws that it’ll have to comply are only the barebones of a category, we defined composition, arrows and objects at an abstract level but in reality each category will define what are it’s objects, arrows and how they can compose, these implementations vary depending on the category. We can see that even there is a category for the type declarations on Haskell, we’ll go into this later on..</p>

<p>for now lets go with a small exmaple, in this case Strings… for strings we have that the objects is represented by ob(Str) where the element could be represented by any string value, so if the object is the type only all the objects of this category will be only one: Str, so we can say this is only a singleton. Now the values that are for that type are any string value, so hom(Str) will be each string we can possibily build, that’s why we can say that ω will represent all the possible string values. Now our small category will need a composition (o) value which will be the concatenation in this case (++). So if we want to represent this category we can do like this following image, the w is actually</p>

<figure>
    <a href="/assets/blog-images/simple_category_example.jpeg"><img src="/assets/blog-images/simple_category_example.jpeg" /></a>
</figure>

<p>Now let’s try to see if the category laws can be verified:</p>

<p>For identity we had that:</p>

<script type="math/tex; mode=display">
  id_B \circ f = f = f \circ id_A
</script>

<p>now the id for Str will be</p>

<script type="math/tex; mode=display">
  id_Str = ""
</script>

<p>perfect the empty string is actually the identity, this will vary depending on the category, now lets prove it for any string z, lets see if the law can be verified:</p>

<script type="math/tex; mode=display">
  "" ++ z = z = z ++ ""
</script>

<p>allright, now lets try to demostrate if the associative law can be validated for any three strings.</p>

<script type="math/tex; mode=display">
  f \circ (g \circ h) = (f \circ g) \circ h
</script>

<p>for strings x,y and z we have that</p>

<script type="math/tex; mode=display">
  (x ++ y) ++ z = x ++ (y ++ z)
</script>

<p>So summing up this string example is kind of small but we can see that even with infinite paths, actually arrows, we can demostrate that the laws of category are respected. For a finite example we have that for a given category X</p>

<ul>
  <li>ob((X)) = {A, B, C} these are the objects and represent the vertices of the diagram</li>
  <li>hom((X)) = {ε,α,β,γ,αβ,βγ,…} and each of these elements represent a path between the vertices.</li>
  <li>and finally the concatenation for ie. αβ∘γ=αβγ</li>
</ul>

<h2 id="monoids">Monoids</h2>

<p>When the small example of Strings where shown, we said that they could be categories with a single value, we demonstrated that for all the strings that we can form, thus we can say that these are a spacial class of categories called Monoids, the axioms required of a monoid operation are exactly those required of morphism composition when restricted to the set of all morphisms whose source and target is a given object, that is that a monoid is essentially, the same thing as a category with a single object.</p>

<p>More precisely, given a monoid ((M, •)), one can construct a small category with only one object and whose morphisms are the elements of M. The composition of morphisms is given by the monoid operation •.
These degenerated category, can be thought as a concept in which the categories are an extension of monoids, that can be generalised to small categories with more than one object.</p>

<p>some examples can be seen in this wikipedia <a href="https://en.wikipedia.org/wiki/Monoid#Examples">link</a></p>

<p>With a more formal approach we can say that each monoid is represented by the triplet ((M,e,⊙)) where ob((M))={∙},hom((M))=M,∘=⊙</p>

<p>Examples of a monoid could be something like ((String, ‘Hello’, ++)) or ((String, ‘Something’, ++)), and in a more general way something that understands ((A, v, ⊙)), where A is the obj or class, v a value and ⊙ a way to compose with other monoids.</p>

<p>Monoids are very common. There are the monoids of numbers like N,
Q, or R with addition and 0, or multiplication and 1. But also for any set X, the set of functions from X to X, written as</p>

<script type="math/tex; mode=display">
  Hom_Sets (X, X)
</script>

<p>is a monoid under the operation of composition. More generally, for any object C in any category C, the set of arrows from C to C, written as Hom C (C, C), is a monoid under the composition operation of C.</p>

<h2 id="isomorphisms">Isomorphisms</h2>

<p>In a category C, if we have an arrow of f : A → B, we can say that it’s called an isomorphism if there is an arrow g : B → A in C, that</p>

<script type="math/tex; mode=display">
  g \circ f = id_A , f \circ g = id_B
</script>

<p>Since the inverses are unique, we write (g = f^{−1}). We say that A is isomorphic to B, written A≌B, if there exists an isomorphism between them, where = is mostly ≌. The definition of isomorphism is our first example of an abstract, category theoretic definition of an important notion. It is abstract in the sense that it makes use only of the category theoretic notions, rather than some additional information about the objects and arrows.</p>

<h2 id="choices-and-other-properties-of-categories">Choices and other properties of categories</h2>

<p>We can define that Integers can be saw as monoids, where the type is the object set of the category, meaning ob((Int)) is a singleton or either each of the numbers as a new category, for example, 0 could be a category with only it’s identity, and a category where 0 and 1 are objects and have the composition where you can compose both objects with a + function, these are two different categories, but you can also form a monoid based on Intgers where the value 0,1.. etc is actually not an object but instead the morphism, on integers that could be seen as monoids we can say that ((Integer, 0, +)) could be seen as a monoid too, so the same object can be seen in many different way as a category and also you can choose what are object, morphisms and composition, this applies only when you can prove that the categories laws are proveed and verified. Some examples of these besides Integers are Str and discrete((Σ*))</p>

<figure>
    <a href="/assets/blog-images/numbers_succ_cat.jpeg"><img src="/assets/blog-images/numbers_succ_cat.jpeg" /></a>
</figure>

<p>A category will also have properties based on their objects, morphisms and composition.</p>

<h3 id="initial-and-terminal-symbols">Initial and terminal symbols</h3>

<p>An object is initial in a category C if for every object X in C there exists a unique arrow in C from it to X. Note that initial objects are unique up to isomorphism. The notation for ‘the’ initial object is 0, and 1 for ‘the’ final object, about this, an object is final, or terminal, in a category C if for every object X in C there exists a
unique arrow in C from X to it, again there could be or not initial and final objects, then we can say that: A final in C iff A initial in (C^{op})</p>

<p>so final objects are unique up to isomorphism too. The initial object in a preorder is the bottom element, if it exists; the final object is the top.</p>

<h3 id="duality-principle">Duality principle</h3>

<p>First, let us look again at the formal definition of a category: There are two kinds of things, objects like ob((C)) = { A, B, C } and  arrows hom((C)) = { f, g, h, …}, four operations dom(f), cod(f), id , g ◦ f, and these category properties satisfy the following seven axioms of the duality principle:</p>

<script type="math/tex; mode=display">
 dom(id_A ) = A \rightarrow cod(id_A ) = A
</script>

<script type="math/tex; mode=display">
 f ◦ id_{dom(f)} = f \rightarrow 1_{cod(f)} ◦ f = f
</script>

<script type="math/tex; mode=display">
 dom(g ◦ f) = dom(f) \rightarrow cod(g ◦ f) = cod(g)
</script>

<script type="math/tex; mode=display">
 dom(g ◦ f) = dom(f) \rightarrow cod(g ◦ f) = cod(g)
</script>

<script type="math/tex; mode=display">
 h ◦ (g ◦ f) \rightarrow (h ◦ g) ◦ f
</script>

<p>The operation (g ◦ f) is only defined where</p>

<script type="math/tex; mode=display">
 dom(g) = cod(f)
</script>

<p>so a suitable form of this should occur as a condition on each equation containing ◦, as in:</p>

<script type="math/tex; mode=display">
 dom(g) = cod(f) \rightarrow dom(g ◦ f ) = dom(f)
</script>

<p>Now, given any sentence Σ in the elementary language of category theory, we can form the “dual statement” Σ ∗ by making the following replacements:</p>

<ul>
  <li>(f ◦ g) for (g ◦ f)</li>
  <li>cod for dom</li>
  <li>dom for cod</li>
</ul>

<p>It is easy to see that then Σ* will also be a well-formed sentence. Next, suppose we have shown a sentence Σ to entail one Δ, that is, Σ ⇒ Δ, without using any
of the category axioms, then clearly Σ* ⇒ Δ* , since the substituted terms are treated as mere undefined constants, so we have for all the axioms showed for a category named CT that</p>

<script type="math/tex; mode=display">
 CT^{∗} = CT
</script>

<p>We therefore have the following duality principle.</p>

<h3 id="functors-the-category-theory-approach">Functors… the category theory approach</h3>

<p><em>Shamessly taken from <a href="https://en.wikibooks.org/wiki/Haskell/Category_theory">https://en.wikibooks.org/wiki/Haskell/Category_theory</a></em></p>

<p>Well finally we can transform categories into another type of categories, for these exists the functors. We’ll see in this small section theorically what a functor does, later on we’ll see how functors work on Haskell, let’s see a functor ransforms a category A into a category B in this way bu a functor F:</p>

<script type="math/tex; mode=display">
  F : A \rightarrow B
</script>

<p>The functor will do the following on the transformation:</p>

<ul>
  <li>Maps any object A in C to F((A)), in D.</li>
  <li>Maps morphisms (f : C \rightarrow D) in A to  F((f)): F((C)) (\rightarrow) F((D))  in B.</li>
</ul>

<p>See this example:</p>

<figure>
    <a href="/assets/blog-images/Functor_category.png"><img src="/assets/blog-images/Functor_category.png" /></a>
</figure>

<p>A functor between two categories, (C) and (D). Of note is that the objects A and B both get mapped to the same object in (D), and that therefore g becomes a morphism with the same source and target object, but isn’t necessarily an identity, and (id_A) and (id_B) become the same morphism. The arrows showing the mapping of objects are shown in a dotted, pale olive. The arrows showing the mapping of morphisms are shown in a dotted, pale blue.</p>

<p>For any category C, we can define a functor known as the identity functor on C, or (1_C : C \rightarrow C), that just maps objects to themselves and morphisms to themselves. We’ll use this later on monads.</p>

<p>Once again there are a few axioms that functors have to obey. Firstly, given an identity morphism (id_A) on an object A, F((id_A)) must be the identity morphism on F((A)):</p>

<script type="math/tex; mode=display">
    F(id_A) = id_{F(A)}
</script>

<p>also functors understand composition and must distribute over their morphisms:</p>

<script type="math/tex; mode=display">
    F(f \circ g) = F(f) \circ F(g)
</script>

<p>One last thing to remember, there are some functors that will transform from one category A to another category A, these are called endofunctors.</p>

<p>Now for some more small demonstration of functors, given two categories A and B we can demosntrate that these have the following rules verified:</p>

<script type="math/tex; mode=display">
id_A \circ_{A} f = f
\\
f \circ_{A} id_A = f
\\
(f \circ_{A} g) \circ_{A} h = f \circ_{A} (f \circ_{A} h)
</script>

<p>and</p>

<script type="math/tex; mode=display">
id_B \circ_{B} f = f
\\
f \circ_{B} id_B = f
\\
(f \circ_{B} g) \circ_{B} h = f \circ_{B} (f \circ_{B} h)
</script>

<p>the functor F that transforms from one A to B will have a function called map that will make the following transformations:</p>

<p>Transform the composition operator after trnasforming it’s objects and arrows:</p>

<script type="math/tex; mode=display">
map (f \circ_A g) = map f \circ_B map g
</script>

<p>and also transform the identity:</p>

<script type="math/tex; mode=display">
map id_A = id_B
</script>

<h2 id="haskell-time">Haskell time</h2>

<p>We have seen some pretty long explanaition of introductory category theory, how does this has to do anything with Haskell code. In fact what I mentioned in the beginning was that there is a Hask category, let’s see what is it.</p>

<h3 id="hask-category">Hask category</h3>

<p><em>Shamessly taken from wikibooks of haskell</em></p>

<p>Hask category treats Haskell types as objects and Haskell functions as morphisms and uses for composition ((\circ)) the function ((.)), a function (f :: A -&gt; B) for types A and B is a morphism in Hask.</p>

<figure>
    <a href="/assets/blog-images/hask.jpg"><img src="/assets/blog-images/hask.jpg" /></a>
</figure>

<p>We can prove the composition between functions for eg that h = f.g, on the Hask there is also the identity ob an object defined by id, in Haskell</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>id :: (a -&gt; a)
id x = x
</code></pre></div></div>

<p>The function id in Haskell is polymorphic — it can take many different types for its domain and range, or, in category-speak, can have many different source and target objects. But morphisms in category theory are by definition monomorphic — each morphism has one specific source object and one specific target object. A polymorphic Haskell function can be made monomorphic by specifying its type (instantiating with a monomorphic type), so it would be more precise if we said that the identity morphism from Hask on a type A is (id :: A -&gt; A). With this in mind, the above law would be rewritten as:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(id :: B -&gt; B) . f = f . (id :: A -&gt; A) = f
</code></pre></div></div>

<p>If we want, we can also check the types of composition</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(.) :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; (a -&gt; c)
(f . g) x = f (g x)
</code></pre></div></div>

<p>if we want to prove if the laws of categories are complied</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-- left identity 
id . f = f 

= \x -&gt; id (f x)
= \x -&gt; f x
= f

-- right identity

f . id
= \x -&gt; f (id x)
= \x -&gt; f x
= f

-- associative law

(f . g) . h
= \x -&gt; (f . g) (h x)
= \x -&gt; f (g (h x))
= \x -&gt; f ((g . h) x)
= \x -&gt; (f . (g . h)) x
= f . (g . h)
</code></pre></div></div>

<p>Now types can define a lot about what is the behaviour of our functions in Haskell, some example could be the first function</p>

<pre><code class="language-.Haskell">Prelude&gt; :t fst
fst :: (a, b) -&gt; a
</code></pre>

<p>given a tuple of a type variable a and b as first and second member it returns the first element which is of type variable a. If you don’t exactly recall of know about type variables in haskell, you could look up in this section of learn you some haskell <a href="http://learnyouahaskell.com/types-and-typeclasses">http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101</a>. Types can give you some good information about what the function expects and returns, what it’s important is that with type parameters we can generalize a function to handle different types, for eg. fst accepts a tuple if ([Char], Integer), for example:</p>

<pre><code class="language-Haskell">Prelude&gt; :t fst ("Hola", 1)
fst ("Hola", 1) :: [Char]
</code></pre>

<p>a is resolved to ([Char]) and b as Int in this case, so the type that will return fst is ([Char]), we’ll talk about this in the end of this post.</p>

<p>Another paper that you could read more about this is in <em><a href="http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf">Theorems for free</a></em></p>

<h2 id="the-functor-typeclass-in-haskell">The Functor… typeclass in Haskell</h2>

<h3 id="typeclases">typeclases</h3>

<p>A typeclass is a kind of interface that defines a behavior, if a type is part of a typeclass, it’ll support and implement the behavior that describes the typeclass. This can be somewhat confusing for people coming from the object paradigm, so the typeclases are as Java interfaces, but implementing the behavior and not only defining your contract. Yeah, i know this is kind of an ugly comparison but if you come from an almost pure object paradigm it could be a little difficult to understand at first.</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="o">:</span><span class="n">t</span> <span class="p">(</span><span class="o">+</span><span class="p">)</span>
<span class="p">(</span><span class="o">+</span><span class="p">)</span> <span class="o">::</span> <span class="kt">Num</span> <span class="n">a</span> <span class="o">=&gt;</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">a</span>
</code></pre></div></div>

<p>In this case + is a function that has a as a type variable and a type constraint that a can be of type Num or derivated from it, let’s see another example now:</p>

<pre><code class="language-Haskell">Prelude&gt; :t (&lt;=)
(&lt;=) :: Ord a =&gt; a -&gt; a -&gt; Bool
</code></pre>

<p>now this function is for comparing two different values of the same type that are of type Ord or derivated of this one. Ord is actually a <em><a href="https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-Ord.html">typeclass</a></em> and defines the prototypes for comparing two objects. Typeclasses are useful when defining new types for your own use as you can derive typeclasses to add not only the prototype of the typeclasses that you extend for your new type but also you can extend the typeclass by defining what it should do. In some cases you have to do this last thing. if you want to know more in depth and extense explanation about this see: <em><a href="http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101">http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101</a></em>.</p>

<h3 id="functors">Functors</h3>

<p>let’s look a little what a functor is. Basically Functor is a typeclass to which you can apply the map operation. One would think that can be done in principle on lists, and this is what is usually seen in introductory functional programming material, but here we see that can also be used for other types, let’s see what the wiki says haskell:</p>

<p>More information on <em><a href="https://wiki.haskell.org/Functor">https://wiki.haskell.org/Functor</a></em></p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">class</span> <span class="kt">Functor</span> <span class="n">f</span> <span class="kr">where</span>  
    <span class="n">fmap</span> <span class="o">::</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">f</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">f</span> <span class="n">b</span>  
</code></pre></div></div>

<p>when we go to the part of the theory relate category, we see that the laws apply to this class:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fmap (f . g) = fmap f . fmap g  -- Composition law

fmap id = id                    -- Identity law
</code></pre></div></div>

<p>Fmap then takes a function that goes from a -&gt; b, and a functor applied with one type, and returns a functor applied with another type. See the case for map</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="o">:</span><span class="n">t</span> <span class="n">map</span>
<span class="n">map</span> <span class="o">::</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="n">a</span><span class="p">]</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="n">b</span><span class="p">]</span>
</code></pre></div></div>

<p>Interestingly, seen as also takes a function of a -&gt; b, and a list and returns another list, actually map is a particular case of fmap, so map is also a functor and map is a fmap defined for lists.</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">instance</span> <span class="kt">Functor</span> <span class="kt">[]</span> <span class="kr">where</span>
    <span class="n">fmap</span> <span class="o">=</span> <span class="n">map</span>  
</code></pre></div></div>

<p>so we can use directly fmap for operating with the functor on the list class!</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="n">fmap</span> <span class="p">(</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span> <span class="p">]</span>
<span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">6</span><span class="p">]</span>
<span class="kt">Prelude</span><span class="o">&gt;</span> <span class="n">fmap</span> <span class="p">(</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="p">[</span><span class="mi">2</span><span class="p">]</span>
<span class="kt">Prelude</span><span class="o">&gt;</span> <span class="n">fmap</span> <span class="p">(</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span> <span class="kt">[]</span>
<span class="kt">[]</span>
</code></pre></div></div>

<p>It happens when we do a fmap on a list, empty? returns an empty list, this is logical, but makes a list of type ([a]) to type ([b]), where a and b of the same type.</p>

<h3 id="maybe-and-either">Maybe and Either</h3>

<p>let’s see the Maybe structure:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">data</span> <span class="kt">Maybe</span> <span class="n">a</span> <span class="o">=</span> <span class="kt">Just</span> <span class="n">a</span> <span class="o">|</span> <span class="kt">Nothing</span>
</code></pre></div></div>

<p>What does this mean? Maybe a represents something that can be (Just), or not (Nothing). That is, if we think as a container, Maybe is a box that can contain zero or item. And if you think like a computer, a function that returns a computation represents Maybe that may or may not yield a result, ie, a computation that can fail. What is the difference between the Maybe and eg Boolean, or list the ways we define before? The data type does not define values, but new types, this is known as constructors type, so in this case may be of a type x, so if we have a Maybe Int can result in a Nothing or Just one Int. For example if we take the most basic example, the reverse, if the inverse of x is 1 / x, if x == 0 then, its inverse would approaching infinity. so we have a case in which the computer can fail, because you can not compute to infinity, then see how we can represent an inverse function using Maybe.</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">inverse</span> <span class="mi">0</span> <span class="o">=</span> <span class="kt">Nothing</span>
<span class="n">inverse</span> <span class="n">x</span> <span class="o">=</span> <span class="kt">Just</span> <span class="p">(</span><span class="mi">1</span> <span class="o">/</span> <span class="n">x</span><span class="p">)</span>
</code></pre></div></div>

<p>if we want to have Maybe to extend the idea of the functor we need to implement fmap for this type:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">instance</span> <span class="kt">Functor</span> <span class="kt">Maybe</span> <span class="kr">where</span>
    <span class="n">fmap</span> <span class="o">::</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="kt">Maybe</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="kt">Maybe</span> <span class="n">b</span><span class="p">)</span>
    <span class="n">fmap</span> <span class="n">f</span> <span class="p">(</span><span class="kt">Just</span> <span class="n">a</span><span class="p">)</span> <span class="o">=</span> <span class="kt">Just</span> <span class="p">(</span><span class="n">f</span> <span class="n">a</span><span class="p">)</span>
    <span class="n">fmap</span> <span class="n">f</span> <span class="kt">Nothing</span> <span class="o">=</span> <span class="kt">Nothing</span>
</code></pre></div></div>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">fmap</span> <span class="p">(</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span> <span class="p">(</span><span class="kt">Just</span> <span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="kt">Just</span> <span class="mi">2</span>
<span class="n">fmap</span> <span class="p">(</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span> <span class="kt">Nothing</span>  <span class="o">==</span> <span class="kt">Nothing</span>
</code></pre></div></div>

<p>now with either structre we have that:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">data</span> <span class="kt">Either</span> <span class="n">a</span> <span class="n">b</span> <span class="o">=</span> <span class="kt">Left</span> <span class="n">a</span> <span class="o">|</span> <span class="kt">Right</span> <span class="n">b</span> <span class="kr">deriving</span> <span class="p">(</span><span class="kt">Eq</span><span class="p">,</span> <span class="kt">Ord</span><span class="p">,</span> <span class="kt">Read</span><span class="p">,</span> <span class="kt">Show</span><span class="p">)</span>
</code></pre></div></div>

<p>Either as we see is a data type that can have values ​​of two types, and use one at a time. It behaves like a box with two compartments, but use one disables the other and vice versa. Then, as container is quite obvious: it is that allows you to store one of two values. And as computing, a function that returns Either depicts a computer that can be successful or not, and deliver a result or an error may occur. By convention, the Left is the error and right is the correct value. mnemonic: Right also means correct English.</p>

<p>A simple usage is with the inverse again:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">inverse</span> <span class="mi">0</span> <span class="o">=</span> <span class="kt">Left</span> <span class="s">"Arithmetic Error: Division by zero"</span>
<span class="n">inverse</span> <span class="n">x</span> <span class="o">=</span> <span class="kt">Right</span> <span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="n">x</span><span class="p">)</span>
</code></pre></div></div>

<p>we can also extend Either for use with the Functor typeclass:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">instance</span> <span class="kt">Functor</span> <span class="p">(</span><span class="kt">Either</span> <span class="n">e</span><span class="p">)</span> <span class="kr">where</span>
	<span class="n">fmap</span> <span class="kr">_</span> <span class="p">(</span><span class="kt">Left</span> <span class="n">a</span><span class="p">)</span> <span class="o">=</span> <span class="kt">Left</span> <span class="n">a</span>
	<span class="n">fmap</span> <span class="n">f</span> <span class="p">(</span><span class="kt">Right</span> <span class="n">a</span><span class="p">)</span> <span class="o">=</span> <span class="kt">Right</span> <span class="p">(</span><span class="n">f</span> <span class="n">a</span><span class="p">)</span>
</code></pre></div></div>

<p>So Maybe a is used generally to handle the absence of the value a, fo eg. null in other languages. Either is used more in favour to handle errors.</p>

<p>so in this case, Functor is a type class used for types that can be mapped over.</p>

<p>generally a Functor accepts any two concrete types, how is this known in such a generic style? We saw that values like 1, “Hello” have associated types that are seen as labels that enable to know which type is a value. Types also have labels that tell about if they are concrete types or derivated form another constructions, these are called kinds. Type constructors take other types as parameters to eventually produce concrete types, this is something that is resolved by these labels that the type have, it’s kind. Lets see a small example</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="o">:</span><span class="n">k</span> <span class="p">[</span><span class="kt">Char</span><span class="p">]</span>
<span class="p">[</span><span class="kt">Char</span><span class="p">]</span> <span class="o">::</span> <span class="o">*</span>
</code></pre></div></div>

<p>The * means that ([Char]) is a concrete type and no other replacement should take place when we have a type variable in a function declaration. for example if we see Either:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="o">:</span><span class="n">k</span> <span class="kt">Either</span>
<span class="kt">Either</span> <span class="o">::</span> <span class="o">*</span> <span class="o">-&gt;</span> <span class="o">*</span> <span class="o">-&gt;</span> <span class="o">*</span>
</code></pre></div></div>

<p>Either takes two concrete types and return a concrete type, type parameters can also be applied partially:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="o">:</span><span class="n">k</span> <span class="kt">Either</span> <span class="kt">Int</span>
<span class="kt">Either</span> <span class="kt">Int</span> <span class="o">::</span> <span class="o">*</span> <span class="o">-&gt;</span> <span class="o">*</span>
</code></pre></div></div>

<p>This is what happens when we use an Either based on it’s kind a type parameter can take the value of a Type, given that the structure we’re using is of it’s same kind, producing a concrete type, we can use Either with any type. Now let’s try to see the Functor typeclass in a more theoric way:</p>

<p>The typeclass Functor has the followind kind prototype and definition</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Prelude</span><span class="o">&gt;</span> <span class="o">:</span><span class="n">k</span> <span class="kt">Functor</span> 
<span class="kt">Functor</span> <span class="o">::</span> <span class="p">(</span><span class="o">*</span> <span class="o">-&gt;</span> <span class="o">*</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">GHC</span><span class="o">.</span><span class="kt">Prim</span><span class="o">.</span><span class="kt">Constraint</span>


<span class="kr">class</span> <span class="kt">Functor</span> <span class="n">f</span> <span class="kr">where</span>  
    <span class="n">fmap</span> <span class="o">::</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">f</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">f</span> <span class="n">b</span>  
</code></pre></div></div>

<p>now if we Functor is:</p>

<script type="math/tex; mode=display">
F : ob(Hask) \rightarrow ob(Hask)
\\
fmap: hom(Hask) \rightarrow hom(Hask)
</script>

<p>then the tuple (F, fmap) is a Hask functor if for any x :: F a</p>

<script type="math/tex; mode=display">
fmap\,id\,x = x
\\
fmap (g. h) x = (fmap \,g \,. \,fmap \,h) x 
</script>

<p>so summing up we can say that haskell Functors are endofunctors that map: (F :: A \rightarrow A) where A = Hask category, and the tuple (F, fmap) is similar to say (Object, Morphism) theorically.</p>

<h2 id="natural-transformations">Natural Transformations</h2>

<p>Given two functors F and G that transforms between two different categories:</p>

<script type="math/tex; mode=display">
F: A \rightarrow B
\\
G: A \rightarrow B
</script>

<p>we can construct a mapping that we will call natural transformation ((η)) that will map between the functors ans will associate any X object in category A to a morphism in category B, that is:</p>

<script type="math/tex; mode=display">
η_X :F(X) \rightarrow G(X)
\\
η_X ∈ hom(B), η_X ∈ hom(B) \wedge X ∈ ob(A)
</script>

<p>We have that for any morhpism that (f: X \rightarrow Y) called the naturallity condition, thus we have that:</p>

<script type="math/tex; mode=display">
η_Y \circ F(f) = G(f) \circ η_X
</script>

<p>this is called naturality square, represented by the following diagram:</p>

<figure>
    <a href="/assets/blog-images/natural_transformations.jpeg"><img src="/assets/blog-images/natural_transformations.jpeg" /></a>
</figure>

<h3 id="some-examples">Some examples</h3>

<p>Let’s say we want to make a transformation from a type List to Maybe and backwards, we should have something like:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">listToMaybe</span> <span class="o">::</span> <span class="p">[</span><span class="n">a</span><span class="p">]</span> <span class="o">-&gt;</span> <span class="kt">Maybe</span> <span class="n">a</span>
<span class="n">listToMaybe</span> <span class="kt">[]</span> <span class="o">=</span> <span class="kt">Nothing</span>
<span class="n">listToMaybe</span> <span class="p">(</span><span class="n">x</span><span class="o">:</span><span class="n">xs</span><span class="p">)</span> <span class="o">=</span> <span class="kt">Just</span> <span class="n">x</span>
</code></pre></div></div>

<figure>
    <a href="/assets/blog-images/list_maybe_natural_transformations.jpeg"><img src="/assets/blog-images/list_maybe_natural_transformations.jpeg" /></a>
</figure>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">maybeToList</span> <span class="o">::</span> <span class="kt">Maybe</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="n">a</span><span class="p">]</span>
<span class="n">maybeToList</span> <span class="kt">Nothing</span> <span class="o">=</span> <span class="kt">[]</span>
<span class="n">maybeToList</span> <span class="kt">Just</span> <span class="n">x</span>  <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="p">]</span>
</code></pre></div></div>

<figure>
    <a href="/assets/blog-images/maybe_list_natural_transformations.jpeg"><img src="/assets/blog-images/maybe_list_natural_transformations.jpeg" /></a>
</figure>

<p>Another example could be a natural transformation between Either and Maybe</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">eitherToMaybe</span> <span class="o">::</span> <span class="kt">Either</span> <span class="n">a</span> <span class="n">b</span> <span class="o">-&gt;</span> <span class="kt">Maybe</span> <span class="n">b</span>
<span class="n">eitherToMaybe</span> <span class="p">(</span><span class="kt">Right</span> <span class="n">x</span><span class="p">)</span> <span class="o">=</span> <span class="kt">Just</span> <span class="n">x</span>
<span class="n">eitherToMaybe</span> <span class="kr">_</span> <span class="o">=</span> <span class="kt">Nothing</span>

<span class="n">maybeToEither</span> <span class="o">::</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="kt">Maybe</span> <span class="n">b</span> <span class="o">-&gt;</span> <span class="kt">Either</span> <span class="n">a</span> <span class="n">b</span> 
<span class="n">maybeToEither</span> <span class="n">leftValue</span> <span class="o">=</span> <span class="n">maybe</span> <span class="p">(</span><span class="kt">Left</span> <span class="n">leftValue</span><span class="p">)</span> <span class="kt">Right</span> 
</code></pre></div></div>

<h2 id="composition-of-functors">Composition of functors</h2>

<p>We want now to compose two functions that have the folowing prototype:</p>

<script type="math/tex; mode=display">
f :: a \rightarrow F b
\\
g :: b \rightarrow F c
</script>

<p>the composition would be:</p>

<script type="math/tex; mode=display">
◎ :: (b \rightarrow F c) \rightarrow (a \rightarrow F b) \rightarrow (a \rightarrow F c)
</script>

<p>as the function f takes a parameter of type a the output of f, in terms of the type b is the input for the function g. But doing something like:</p>

<script type="math/tex; mode=display">
 (f.g) 1
</script>

<p>doesn’t quite work, because g is expecting a b not an (F b). So let’s start with the composition of:</p>

<script type="math/tex; mode=display">
 (f◎g) x
</script>

<p>Where x is any value of type parameter a that is an input for function f. now if we now that (f x :: Fb), then we have to find how to apply F b to the function g somehow. What do have to do?</p>

<p>Again let’s see what we have:</p>

<script type="math/tex; mode=display">
f :: a \rightarrow F\,b
\\
g :: b \rightarrow F\,c
\\
f a :: F\,b
</script>

<p>we can use fmap that we saw previously</p>

<script type="math/tex; mode=display">
 fmap :: Functor f => (a \rightarrow b) \rightarrow f a \rightarrow f b
</script>

<p>and in a more generic way.</p>

<script type="math/tex; mode=display">
 fmap :: (c \rightarrow d) \rightarrow F\,c \rightarrow F\,d 
</script>

<p>if we take that</p>

<script type="math/tex; mode=display">
c = b
\\
d = F\,c
\\
fmap :: (b \rightarrow F\,c) \rightarrow F\,b \rightarrow F (F\,c)
\\
(fmap\,g) :: F\,b \rightarrow F (F\,c) ---> by\,g :: b -> F\,c
\\
(fmap\,g) (f\,a) :: F (F\,c) ---> by f\,a :: F\,b
</script>

<p>now we have that F (F\,c) as result with using the fmap, we need to get to F c that’s what g is returning, we can’t do anything with this but fortunately we have the join function:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">join</span> <span class="o">::</span> <span class="n">m</span> <span class="p">(</span><span class="n">m</span> <span class="n">a</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">a</span>
</code></pre></div></div>

<p>with this we can express:</p>

<script type="math/tex; mode=display">
 (f◎g) x = join ((fmap\,g) (f\,a))
</script>

<p>◎ is called the Klesli composition, denoted by the folowing symbol in haskell (&lt;=&lt;).</p>

<p>this composition must obey the following properties:</p>

<script type="math/tex; mode=display">
join (join (F (F (F a))))=join (F (join (F (F a))))
\\
join = \circ
\\
(F \circ F) \circ F = F \circ (F \circ F) ---> {associate\,law}
\\
η :: a \rightarrow F a ---> {natural\,transformation}
\\
η⊙F = F = F⊙η
</script>

<p>finally the klesli composition is defined in this way in haskell:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cd">-- | Left-to-right Kleisli composition of monads.</span>
<span class="p">(</span><span class="o">&gt;=&gt;</span><span class="p">)</span>       <span class="o">::</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">b</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">c</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">c</span><span class="p">)</span>
<span class="n">f</span> <span class="o">&gt;=&gt;</span> <span class="n">g</span>     <span class="o">=</span> <span class="nf">\</span><span class="n">x</span> <span class="o">-&gt;</span> <span class="n">f</span> <span class="n">x</span> <span class="o">&gt;&gt;=</span> <span class="n">g</span>

<span class="cd">-- | Right-to-left Kleisli composition of monads. @('&gt;=&gt;')@, with the arguments flipped</span>
<span class="p">(</span><span class="o">&lt;=&lt;</span><span class="p">)</span>       <span class="o">::</span> <span class="p">(</span><span class="n">b</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">c</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">c</span><span class="p">)</span>
<span class="p">(</span><span class="o">&lt;=&lt;</span><span class="p">)</span>       <span class="o">=</span> <span class="n">flip</span> <span class="p">(</span><span class="o">&gt;=&gt;</span><span class="p">)</span>
</code></pre></div></div>

<p>see <a href="https://hackage.haskell.org/package/base-4.8.2.0/docs/Control-Monad.html">Control.Monad</a> for more information.</p>

<h2 id="monads">Monads</h2>

<p>Given all the definitions we have defined already the monads. Monads are formed by the triplet ((M,⊙,η)), where:</p>

<ul>
  <li>M is an endofunctor</li>
  <li>⊙ is a natural transformation where (⊙: M × M \rightarrow M), for eg. join function</li>
  <li>η is a natural transformation where η:I→M and I is the Identity functor</li>
</ul>

<p>the rules that must obey this category are as alway associative and identity rules:</p>

<script type="math/tex; mode=display">
M ⊙ (M ⊙ M) = (M ⊙ M) ⊙ M
\\
η ⊙ M = M = M ⊙ η
</script>

<p>so a monad is an endofunctor M: C -&gt; C and we have for every object in it’s category two morphisms:</p>

<ul>
  <li>(unit_{X}^{M} : X \rightarrow M(X)) unit is actually the η ransformation</li>
  <li>(join_{x}^{M} : M((M((X)) )) \rightarrow M(X) ) join is actually our ⊙ transformation</li>
</ul>

<p>let’s see now how is this translated in haskell:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">class</span> <span class="kt">Functor</span> <span class="n">m</span> <span class="o">=&gt;</span> <span class="kt">Monad</span> <span class="n">m</span> <span class="kr">where</span>
  <span class="n">return</span> <span class="o">::</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">a</span>
  <span class="p">(</span><span class="o">&gt;&gt;=</span><span class="p">)</span>  <span class="o">::</span> <span class="n">m</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">b</span>
</code></pre></div></div>

<p>We have a type constraint for m where it has to be a Functor, this is only to ensure that we have mapping of morphisms and objects. We see that <em>return</em> is the polymorphic equivalence to (unit_x) for any X. But out bind function, denoted »=, is not similar to the join function we defined previously. However, we have the join function defined for Monads in haskell, as the following:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">join</span> <span class="o">::</span> <span class="kt">Monad</span> <span class="n">m</span> <span class="o">=&gt;</span> <span class="n">m</span> <span class="p">(</span><span class="n">m</span> <span class="n">a</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">a</span>
<span class="n">join</span> <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">&gt;&gt;=</span> <span class="n">id</span>
</code></pre></div></div>

<p>and we can recover join from »= and vice-versa:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="o">&gt;&gt;=</span><span class="p">)</span> <span class="o">::</span> <span class="kt">Monad</span> <span class="n">m</span> <span class="o">=&gt;</span> <span class="n">m</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">b</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">m</span> <span class="n">b</span>
<span class="n">x</span> <span class="o">&gt;&gt;=</span> <span class="n">f</span> <span class="o">=</span> <span class="n">join</span> <span class="p">(</span><span class="n">fmap</span> <span class="n">f</span> <span class="n">x</span><span class="p">)</span>
</code></pre></div></div>

<p>so in terms of matematical approach, we need to define <em>unit</em> and <em>join</em> to have a monad, and in haskell we need to define the <em>return</em> and <em>»=</em> functions. Any time you see in haskell something that receives an x and returns a M((x)) naturally and a transformation from (M(M(x))) to M((x)), you’re probably using a monad.</p>

<p>There is a lot of well documented information further for seeing the monadic laws and examples on <a href="https://en.wikibooks.org/wiki/Haskell/Category_theory#Monads">https://en.wikibooks.org/wiki/Haskell/Category_theory#Monads</a> and <a href="https://en.wikibooks.org/wiki/Haskell/Understanding_monads">https://en.wikibooks.org/wiki/Haskell/Understanding_monads</a></p>

<p>I’ll continue with some more theory about monads, and klesli categories in the next post, but trying to make some more code in scala this time.</p>

<h2 id="where-to-go-from-here">Where to go from here?</h2>

<p>I’de recommend to see Stephen Diehl post about <a href="http://www.stephendiehl.com/posts/monads.html">Monads: The hard way</a>, as it takes some of the theorically principles i showed in this post with some more details on haskell implementation of how you can see the relation between the category theory and haskell code.</p>

<p>I’ll try to take a more practical approach on my next post with Scala</p>

<h1 id="bibliography">Bibliography</h1>

<ul>
  <li>Awodey, Steve (2006). Category theory. Oxford University Press. p. 11. ISBN 9780198568612</li>
  <li>Vinberg, Ėrnest Borisovich (2003). A Course in Algebra. American Mathematical Society. p. 3. ISBN 9780821834138.</li>
  <li>Lipovaca, Miran (2011). Learn You a Haskell for Great Good!: A Beginner’s Guide. ISBN 978-1593272838.</li>
  <li>Turi, Daniele. Category Theory Lecture Notes</li>
  <li><a href="https://en.wikibooks.org/wiki/Haskell/Category_theory">https://en.wikibooks.org/wiki/Haskell/Category_theory</a></li>
  <li><a href="http://yogsototh.github.io/Category-Theory-Presentation">http://yogsototh.github.io/Category-Theory-Presentation</a></li>
  <li><a href="http://www.haskellforall.com/2012/09/the-functor-design-pattern.html">http://www.haskellforall.com/2012/09/the-functor-design-pattern.html</a></li>
</ul>]]></content><author><name>Ernesto Bossi</name></author><category term="Categories" /><category term="Monads" /><category term="Functors" /><category term="functional" /><category term="computer science" /><summary type="html"><![CDATA[This will be a post about category theory and the relation between it and functors, monads and monoids in Haskell]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://ernestobossi.com/assets/blog-images/front2.jpg" /><media:content medium="image" url="https://ernestobossi.com/assets/blog-images/front2.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Update all Ruby gems</title><link href="https://ernestobossi.com/ruby/update-gems-ruby/" rel="alternate" type="text/html" title="Update all Ruby gems" /><published>2013-08-12T00:00:00-03:00</published><updated>2013-08-12T00:00:00-03:00</updated><id>https://ernestobossi.com/ruby/update-gems-ruby</id><content type="html" xml:base="https://ernestobossi.com/ruby/update-gems-ruby/"><![CDATA[<p>Last week i wanted to update some ruby projects that i have packed in gems and wanted to update their dependencies (just to have the project updated).
My objective was to be able to update all my gems in a single bash line, luckily i managed to do this by issuing the following line:</p>

<figure class="highlight"><pre><code class="language-bash" data-lang="bash"><span class="nb">sudo </span>gem update <span class="sb">`</span>gem list | <span class="nb">cut</span> <span class="nt">-d</span> <span class="s1">' '</span> <span class="nt">-f</span> 1<span class="sb">`</span></code></pre></figure>]]></content><author><name>Ernesto Bossi</name></author><category term="Ruby" /><category term="link" /><category term="Post Formats" /><summary type="html"><![CDATA[Last week i wanted to update some ruby projects that i have packed in gems and wanted to update their dependencies (just to have the project updated). My objective was to be able to update all my gems in a single bash line, luckily i managed to do this by issuing the following line:]]></summary></entry></feed>