<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Romes' Blog RSS Feed</title>
    <link href="http://alt-romes.github.io/atom.xml" rel="self" />
    <link href="http://alt-romes.github.io" />
    <id>http://alt-romes.github.io/atom.xml</id>
    <author>
        <name>Rodrigo Mesquita</name>
        
        <email>rodrigo.m.mesquita@gmail.com</email>
        
    </author>
    <updated>2026-04-01T00:00:00Z</updated>
    <entry>
    <title>Running out of Disk Space in Production</title>
    <link href="http://alt-romes.github.io/posts/2026-04-01-running-out-of-disk-space-on-launch.html" />
    <id>http://alt-romes.github.io/posts/2026-04-01-running-out-of-disk-space-on-launch.html</id>
    <published>2026-04-01T00:00:00Z</published>
    <updated>2026-04-01T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Last night I put up a simple server which allowed customers to download the
digital Kanjideck files. This server is hosted on a small Hetzner machine
running NixOS, at 4GB of RAM and 40GB of disk space. One of these downloadable
files weights 2.2GB.</p>
<p>The matter at hand boils down to a simple Haskell program which serves static
files (with some extra steps regarding authorization) plus an nginx reverse
proxy which proxies requests to a certain “virtual host” to the Haskell program.</p>
<figure>
<img src="/images/running-out-of-disk-space-on-launch/architecture.svg" alt="Fig 1. Simplified server architecture" />
<figcaption aria-hidden="true">Fig 1. Simplified server architecture</figcaption>
</figure>
<h1 data-number="1" id="first-panic"><span class="header-section-number">1</span> First, Panic</h1>
<p>Not even minutes after I announced that the files were finally available,
hundreds of customers visited my server all at once.
As the logs started flying off of my screen with all the accesses, I started
noticing a particularly interesting message, repeated over and over again:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>Mar 31 20:43:03 mogbit kanjideck-fulfillment[2528300]: user error</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>(Unexpected reply to: MAIL &quot;&lt;...&gt; at kanjideck.com&quot;,</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>Expected reply code: 250, Got this instead: 452 &quot;4.3.1 Insufficient system storage\r\n&quot;)</span></code></pre></div>
<p>Oh no. No one’s able to access their files and I’m already receiving emails about it.
I messaged the users explaining the server was having some issues that I was resolving.</p>
<p>Grafana shows 40GB/40GB disk space used up, so does <code>df -h</code> have 100% usage of <code>/dev/sda</code>.
I have to clear up space fast. I’m afraid at this point that I’m not even
receiving the user complaints anymore since my mail could be getting dropped by
lack of space.</p>
<p>I rushed to run <code>du -sh</code> on everything I could, as that’s as good as I could manage.
The two larger culprits were <code>/var/lib</code>’s Plausible Analytics, with a 8.5GB (clickhouse)
database, and the <code>/nix/store</code> with the full server configuration,
installation, and executables, at 15GB.</p>
<p>(In hindsight, I should have stopped right here to think carefully about what
could possibly be occupying the remaining 20GB. I assumed “the rest of the
files”, but looking back the “rest of the files” could hardly total 20GB.)</p>
<p>Delete <em>everything</em> that I can.</p>
<p>First off, the <code>/nix/store</code> may have unnecessary executables and past
configurations. This should be a big win. Drop it all with</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>$ nix-collect-garbage -d</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>...</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>removing old generations of profile /nix/var/nix/profiles/system</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>error: opening lock file &#39;/nix/var/nix/profiles/system.lock&#39;: No space left on device</span></code></pre></div>
<p>Clearing the nix store doesn’t work because there’s no space left on device
(meanwhile, imagine the panic as the errors scroll by as users try over and
over again to download the files which keep giving them errors).</p>
<p>OK, let’s kill the logs first.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>journalctl --vacuum-time=1s</span></code></pre></div>
<p>This restored enough space for me to clear the nix store.
Next big item on the list is the clickhouse database. Some googling tells me I
can truncate some of the logs tables to reduce the size. Let’s try it:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>clickhouse-client -q &quot;TRUNCATE TABLE system.query_log&quot;</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>  Received exception from server (version 24.3.7):</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  Code: 243. DB::Exception: Received from localhost:9000. DB::Exception: Cannot reserve 1.00 MiB, not enough space. (NOT_ENOUGH_SPACE)</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  (query: TRUNCATE TABLE system.query_log)</span></code></pre></div>
<p>Aaaand we’ve run out of space again. The service is still returning errors left
and right to the users. Maybe the nix store didn’t clear up enough space, but
there’s clearly something that keeps consuming more and more space, correlated
with the influx of users.</p>
<h1 data-number="2" id="mounting-the-nix-store-on-a-separate-volume"><span class="header-section-number">2</span> Mounting the Nix Store on a separate Volume</h1>
<p>When in panic, buy more space. Except that <a href="https://status.hetzner.com/incident/0a75c7ae-3377-41dc-aabe-601063724d24">Hetzner didn’t have an available
cloud instance</a>
with more space for me to upgrade to.</p>
<p>Plan B: I could still buy more space as a separate Volume.</p>
<p>The <code>/nix/store</code> is an immutable store and I had heard of people setting up
their nix stores on separate drives before. It was also the largest system
component at 12GB now. A perfect candidate.</p>
<p>Luckily (rather, due to NixOS) everything went smoothly with this transition.
Following the instructions on <a href="https://nixos.wiki/wiki/Storage_optimization#Moving_the_store">“Moving the store” in the NixOS
Wiki</a> worked
flawlessly. The new Volume was labeled <code>nix</code> with <code>mkfs.ext4 -L nix /dev/sdb</code>
and the mounting migration first done manually, but at the end of the day we
have a final declarative configuration of the system:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode nix"><code class="sourceCode nix"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>  fileSystems<span class="op">.</span><span class="st">&quot;/nix&quot;</span> = <span class="op">{</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>     <span class="va">device</span> <span class="op">=</span> <span class="st">&quot;/dev/disk/by-label/nix&quot;</span><span class="op">;</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>     <span class="va">fsType</span> <span class="op">=</span> <span class="st">&quot;ext4&quot;</span><span class="op">;</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>     <span class="va">neededForBoot</span> <span class="op">=</span> <span class="cn">true</span><span class="op">;</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>     <span class="va">options</span> <span class="op">=</span> <span class="op">[</span> <span class="st">&quot;noatime&quot;</span> <span class="op">];</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>   <span class="op">}</span>;</span></code></pre></div>
<p>After rebooting the server, the <code>/nix/store</code> was living in a separate volume
and the root drive finally had enough space to reply to the users.</p>
<p>Grafana was no longer red all over and the logs were no longer streaming error
messages. The filesystem was still 50% used up and it seemed to increase up to
around 60-65% when various users were downloading the large 2.2GB file. But. Working.</p>
<h1 data-number="3" id="finding-the-root-cause-in-nginx"><span class="header-section-number">3</span> Finding the root cause in Nginx</h1>
<p>This morning I anxiously opened my inbox.
There were a handful of complaints about the large 2.2GB file download stopping
halfway through and never successfully downloading.</p>
<p>However, users were able to access the download page and download all the other
(arguably more important) files. Not bad! Grafana was still green and filesystem
usage at about 50%.</p>
<p>The large file bug was important to fix promptly.</p>
<ul>
<li><p>Recall from the server architecture that nginx proxies to the program which serves the files.</p></li>
<li><p>With some investigation I found
<a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_max_temp_file_size">proxy_max_temp_file_size</a>, which defaults to</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>Default: proxy_max_temp_file_size 1024m;</span></code></pre></div></li>
<li><p>Increasing the value to <code>5000m</code> allowed the 2.2GB file to be served successfully by the proxy!</p></li>
<li><p>Have you read the documentation for this option? I just skimmed.</p></li>
</ul>
<p>One bug down. And the disk space issue seemed tamed, but… during the day, it briefly spiked up to 100% again!
Without last night’s huge pressure I was able to investigate this more soundly.</p>
<p>The <code>lsof +L1</code> command finds unlinked open files (see <code>man lsof</code>), i.e. files
to which there are no links from the file system but are still referenced by
some process and thus can’t be collected. Files which wouldn’t ever show up
with <code>ds -h</code>. I was greeted by 14.5 GB of deleted files held by <code>nginx</code>!</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>[nix-shell:~]# lsof +L1 | grep nginx</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>  nginx     4659       nginx mem    REG    0,1   10485760     0    1187 /dev/zero</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>  nginx     4659       nginx mem    REG    0,1       4096     0    1188 /dev/zero</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx mem    REG    0,1   10485760     0    1187 /dev/zero</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx mem    REG    0,1       4096     0    1188 /dev/zero</span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  19u   REG   8,17  137494528     0 2103873 /tmp/nginx_proxy/6/19/0000000196 (deleted)</span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  21u   REG   8,17  596893696     0 2104973 /tmp/nginx_proxy/1/17/0000000171 (deleted)</span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  24u   REG   8,17  298344448     0 2105098 /tmp/nginx_proxy/3/17/0000000173 (deleted)</span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  25u   REG   8,17 1785765888     0 2105000 /tmp/nginx_proxy/2/17/0000000172 (deleted)</span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  29u   REG   8,17  894984192     0 2105100 /tmp/nginx_proxy/4/17/0000000174 (deleted)</span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  31u   REG   8,17 1489068032     0 2101531 /tmp/nginx_proxy/5/17/0000000175 (deleted)</span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  35u   REG   8,17  745529344     0 2103341 /tmp/nginx_proxy/7/17/0000000177 (deleted)</span>
<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  37u   REG   8,17  965054464     0 2105961 /tmp/nginx_proxy/2/21/0000000212 (deleted)</span>
<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  41u   REG   8,17 1340678144     0 2103603 /tmp/nginx_proxy/0/18/0000000180 (deleted)</span>
<span id="cb7-15"><a href="#cb7-15" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  43u   REG   8,17 1633722368     0 2101619 /tmp/nginx_proxy/3/18/0000000183 (deleted)</span>
<span id="cb7-16"><a href="#cb7-16" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  44u   REG   8,17 1927659520     0 2103872 /tmp/nginx_proxy/5/19/0000000195 (deleted)</span>
<span id="cb7-17"><a href="#cb7-17" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  52u   REG   8,17  795958957     0 2103671 /tmp/nginx_proxy/2/19/0000000192 (deleted)</span>
<span id="cb7-18"><a href="#cb7-18" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  53u   REG   8,17 1591967405     0 2103702 /tmp/nginx_proxy/3/19/0000000193 (deleted)</span>
<span id="cb7-19"><a href="#cb7-19" aria-hidden="true" tabindex="-1"></a>  nginx     4972       nginx  58u   REG   8,17 2387853312     0 2103313 /tmp/nginx_proxy/1/21/0000000211 (deleted)</span>
<span id="cb7-20"><a href="#cb7-20" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-21"><a href="#cb7-21" aria-hidden="true" tabindex="-1"></a>[nix-shell:~]# lsof +L1 | awk &#39;/nginx/ {sum += $7} END {print sum/1024/1024/1024 &quot; GiB&quot;}&#39;</span>
<span id="cb7-22"><a href="#cb7-22" aria-hidden="true" tabindex="-1"></a>  14.5528 GiB</span></code></pre></div>
<p>Remember
<a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_max_temp_file_size">proxy_max_temp_file_size</a>?
Let’s read the documentation more carefully this time:</p>
<blockquote>
<p>When <em>buffering</em> of responses from the proxied server is enabled, […],
a part of the response can be saved to a temporary file.</p>
<p><strong>The zero value disables buffering of responses to temporary files.</strong></p>
</blockquote>
<p>Nginx is buffering the 2.2GB file my program is serving to temporary files.
Oh dear. Let’s fix that:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode nix"><code class="sourceCode nix"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>    <span class="st">&quot;&lt;...&gt;.kanjideck.com&quot;</span> = base <span class="op">{</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>      <span class="st">&quot;/&quot;</span> <span class="op">=</span> <span class="op">{</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>        <span class="va">proxyPass</span> <span class="op">=</span> <span class="st">&quot;http://127.0.0.1:&quot;</span> <span class="op">+</span> <span class="bu">toString</span><span class="op">(</span>ports<span class="op">.</span>kanjideck<span class="op">-</span>fulfillment<span class="op">)</span> <span class="op">+</span> <span class="st">&quot;/&quot;</span><span class="op">;</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>        <span class="va">extraConfig</span> <span class="op">=</span> <span class="st">&#39;&#39;</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a><span class="st">          proxy_buffering off;</span></span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a><span class="st">          proxy_max_temp_file_size 0;</span></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a><span class="st">        &#39;&#39;</span><span class="op">;</span></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a>      <span class="op">};</span></span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span>;</span></code></pre></div>
<p>Grafana immediately cheered up, the server was finally fresh and lean and disk usage jumped to 20% with no more spikes:</p>
<p><img src="/images/running-out-of-disk-space-on-launch/instruments.png" alt="Fig 2. Green grafana instruments, disk usage below 20%" />
<img src="/images/running-out-of-disk-space-on-launch/disk_usage_1.png" alt="Fig 3. Disk space usage graph when I first fixed the bug" />
<img src="/images/running-out-of-disk-space-on-launch/disk_usage_2.png" alt="Fig 4. Disk space usage graph after a few hours" /></p>
<p>In the disk usage graph images you can find the sudden drop to acceptable levels, which now reigns.</p>
<h1 data-number="4" id="conclusion"><span class="header-section-number">4</span> Conclusion</h1>
<ul>
<li><p>The server couldn’t serve access requests from 20:40 to sometime around
23:00, i.e. for about the first 2 hours immediately after launch.</p></li>
<li><p>Secondly, users couldn’t download the large file despite the remaining ones being available.</p></li>
<li><p>Both of these bugs turned out to be misconfigurations in the nginx reverse proxy.</p></li>
<li><p>It’s difficult to reason under pressure. Experience, that I didn’t have here, would have helped.</p></li>
</ul>
<p><em>Note: this was written fully by me, human.</em></p>
<!-- I messaged all users to explain the situation as soon as the problem happened, -->
<!-- and replied to everyone who said they were having difficulties with the -->
<!-- download directly and promptly that all the issues were resolved. -->]]></summary>
</entry>
<entry>
    <title>How I turned my Anki side project into a Kickstarter: A Walkthrough</title>
    <link href="http://alt-romes.github.io/posts/2026-01-30-from-side-project-to-kickstarter-a-walkthrough.html" />
    <id>http://alt-romes.github.io/posts/2026-01-30-from-side-project-to-kickstarter-a-walkthrough.html</id>
    <published>2026-01-30T00:00:00Z</published>
    <updated>2026-01-30T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#the-initial-idea-august-2024" id="toc-the-initial-idea-august-2024"><span class="toc-section-number">1</span> The initial idea (August 2024)</a>
<ul>
<li><a href="#what-if" id="toc-what-if"><span class="toc-section-number">1.1</span> What if ?</a></li>
</ul></li>
<li><a href="#manufacturing-physical-cards-september-2024" id="toc-manufacturing-physical-cards-september-2024"><span class="toc-section-number">2</span> Manufacturing physical cards (September 2024)</a></li>
<li><a href="#starting-a-company-in-the-u.s.-october-2024" id="toc-starting-a-company-in-the-u.s.-october-2024"><span class="toc-section-number">3</span> Starting a Company in the U.S. (October 2024)</a>
<ul>
<li><a href="#accounting-and-taxes" id="toc-accounting-and-taxes"><span class="toc-section-number">3.1</span> Accounting and Taxes</a></li>
</ul></li>
<li><a href="#spreadsheets-and-pricing-november-2024" id="toc-spreadsheets-and-pricing-november-2024"><span class="toc-section-number">4</span> Spreadsheets and Pricing (November 2024)</a></li>
<li><a href="#digital-infrastructure-december-2024" id="toc-digital-infrastructure-december-2024"><span class="toc-section-number">5</span> Digital Infrastructure (December 2024)</a></li>
<li><a href="#marketing-and-ads-january-2025" id="toc-marketing-and-ads-january-2025"><span class="toc-section-number">6</span> Marketing and Ads (January 2025)</a></li>
<li><a href="#burn-out-march-2025" id="toc-burn-out-march-2025"><span class="toc-section-number">7</span> Burn-out (March 2025)</a></li>
<li><a href="#reaching-out-for-help-october-2025" id="toc-reaching-out-for-help-october-2025"><span class="toc-section-number">8</span> Reaching out for help (October 2025)</a></li>
<li><a href="#launching-on-kickstarter-january-2026" id="toc-launching-on-kickstarter-january-2026"><span class="toc-section-number">9</span> Launching on Kickstarter (January 2026)</a>
<ul>
<li><a href="#murphys-law" id="toc-murphys-law"><span class="toc-section-number">9.1</span> Murphy’s Law</a></li>
</ul></li>
<li><a href="#conclusion" id="toc-conclusion"><span class="toc-section-number">10</span> Conclusion</a></li>
</ul>
</div>
<p>I think this is my first non-Haskell related post on this blog! This time, I
want to walk through how I successfully launched
<a href="https://kanjideck.com/">Kanjideck</a> <a href="https://www.kickstarter.com/projects/rromes/kanjideck">on Kickstarter</a>
starting from zero, in my spare time.</p>
<p>I want to go over the initial side project, how that turned into a more
ambitious idea, manufacturing and testing a physical product, setting up a
company, spreadsheets, setting up the digital infrastructure for the business,
marketing and ads, burn-out, launching, and reaching out for help as a solo
entrepreneur.</p>
<h1 data-number="1" id="the-initial-idea-august-2024"><span class="header-section-number">1</span> The initial idea (August 2024)</h1>
<p>In the summer of 2024, with nothing to do after having finished reading “Babel”
by R. F. Kuang (a book which happened to be about language and etymology and
that I thoroughly enjoyed), I decided to get back to learning Japanese.</p>
<p>Japanese is a challenging language to learn (at least in the West). Mostly,
that’s due to Kanji, one of the three types of characters used in written
Japanese. <a href="https://en.wikipedia.org/wiki/Hiragana">Hiragana</a> and
<a href="https://en.wikipedia.org/wiki/Katakana">Katakana</a> are phonetic scripts, where
to each symbol corresponds exactly one sound, and there are about 50 of each
(these can be learnt in about a week). On the other hand, there are about 2,136
<a href="https://en.wikipedia.org/wiki/Kanji">Kanji</a> needed for fluency<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>. Each Kanji is a
(potentially complex) symbol with one or more readings and one or more
meanings. Anyway, that means there are a lot of Kanji to memorize.</p>
<p>I’m a big fan of spaced repetition and <a href="https://apps.ankiweb.net/">Anki</a>. If
you don’t know about spaced repetition, see <a href="https://sr1.literatu.com">“How to Remember Anything
Forever-ish”</a>. I had tried to study Kanji seriously
in the past, but the resources I was using at the time, despite using them
consistently (in Anki), weren’t doing it for me. Perhaps surprisingly, there is
a big design space for Kanji learning resources. One particularly annoying
aspect of many resources is the use of mnemonics, which appeal to brute-force
more so than understanding. To me, they felt distracting and misleading, where
a completely made up story about the distinctive features of the character was
used rather than appealing to the much more useful etymological origins of the
character.</p>
<p>I guess I have a lot to say about why I think etymology-based learning for
Kanji is so useful, how it makes <em>understanding</em> Kanji possible (alongside
memorising them), and how this understanding makes learning new ones that much
easier. However, to stay on track, I’ll just refer those curious to the
<a href="https://kanjideck.com/guide">Kanjideck Guide</a> to read more about its
design<a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a>.</p>
<!--I had quit studying Japanese in 2022 out of frustration with the resources I was using.-->
<p>Resuming Japanese in 2024, I wanted to program my own Anki deck, compiling just
the right information for each Kanji card. I knew exactly what information I
found valuable, so it was just a matter of finding the right sources and
conjuring up the right HTML (Anki cards are rendered using HTML). I had a
working prototype within 2 days, and it looked gorgeous<a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a>:</p>
<table>
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<thead>
<tr>
<th style="text-align: center;">Fig 1. Kanji: Talk</th>
<th style="text-align: center;">Fig 2. Kanji: Past</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><img src="/images/kanjideck/back_79.webp" alt="Fig 1. A digital Kanjideck card for Talk" /></td>
<td style="text-align: center;"><img src="/images/kanjideck/back_106.webp" alt="Fig 2. A digital Kanjideck card for Past" /></td>
</tr>
</tbody>
</table>
<p>It looked so nice, in fact, that I thought <em>“what if”</em>?</p>
<h2 data-number="1.1" id="what-if"><span class="header-section-number">1.1</span> What if ?</h2>
<p>The digital Anki deck was working fantastically well and the design turned out
beautiful. I wanted to print some cards into the physical realm and experiment
studying with a physical resource<a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a>.
Namely, I wanted to try the <a href="https://en.wikipedia.org/wiki/Leitner_system">Leitner
System</a>, a well-known system for
physical spaced repetition.</p>
<p>I thought that printing custom cards would require a lot of upfront orders
(this turned out to be false, see next section), and started entertaining the idea of
making the resource I had created more widely available and start a small
business<a href="#fn5" class="footnote-ref" id="fnref5" role="doc-noteref"><sup>5</sup></a>.</p>
<p>I had heard about <a href="https://www.kickstarter.com/">Kickstarter</a> in passing – a
crowd-funding platform which allows people to raise money in pre-orders, but
only charges customers if there are enough pre-orders to kickstart the business.</p>
<p>I then decided I’d run a Kickstarter to sell my Japanese Kanji deck in both
physical and digital versions, and gather enough up-front orders to be able to
print the decks out at a reasonable price per unit.</p>
<p>I just needed a physical version of Kanjideck first! And a project title: Kanjideck.</p>
<h1 data-number="2" id="manufacturing-physical-cards-september-2024"><span class="header-section-number">2</span> Manufacturing physical cards (September 2024)</h1>
<p>I called a few local printing companies (location: Portugal), when I was first
trying to figure out how to print the cards. Without knowing exactly who to
call, none of those I contacted were able to do playing cards specifically, and
required bulk orders in any case.</p>
<p>Eventually, I stumbled upon
<a href="https://www.makeplayingcards.com/">MakePlayingCards.com</a>, a printing business
specialized in playing cards from whom I could buy a single copy of a custom
deck, and easily consult the prices of bulk orders. They do worldwide shipping
and fulfillment, mentioning fulfillment for Kickstarter by name.</p>
<p>Based on the digital version of Kanjideck I made for Anki using HTML, I
programatically generated a PDF per card with a headless browser through
<a href="https://playwright.dev/">Playwright</a>, and converted each card from PDF to a
high-resolution PNG (fit for printing) using
<a href="https://imagemagick.org">ImageMagick</a>.</p>
<figure>
<img src="/images/kanjideck/IMG_8050.webp" alt="Fig 3. Webpage with HTML Kanjideck cards" />
<figcaption aria-hidden="true">Fig 3. Webpage with HTML Kanjideck cards</figcaption>
</figure>
<p>I ordered a test copy of 60 Kanjideck cards using their single-copy custom
print feature on September 10th. That was about 15€ at the time.</p>
<!-- ![Fig 4. Plastic-wrapped cards order](/images/kanjideck/order1.webp) -->
<p>While waiting for the cards to arrive, I started learning the 3D modeling tool
<a href="https://www.blender.org/">Blender</a>. I had seen many Kickstarter videos which
used pretty amazing animations to showcase their product. I was decided to
attempt this myself. A few days in I was able to model the cards and render
them in some fairly OK scenes:</p>
<table>
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<thead>
<tr>
<th style="text-align: center;">Fig 5. Blender render</th>
<th style="text-align: center;">Fig 6. Blender render</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><img src="/images/kanjideck/fifth_render.webp" alt="Fig 5. Blender render of Kanjideck cards" /></td>
<td style="text-align: center;"><img src="/images/kanjideck/r9in.webp" alt="Fig 6. Another blender render of Kanjideck cards" /></td>
</tr>
</tbody>
</table>
<p>I kept improving with time, but eventually realized I was not going to be able
to do an animated video which looked good enough to serve as the video
showcasing the project on the Kickstarter page.</p>
<p>In the meantime, the cards arrived from the manufacturer. These were the very
first prototype:</p>
<table>
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<thead>
<tr>
<th style="text-align: center;">Fig 7. First prototype</th>
<th style="text-align: center;">Fig 8. First prototype<a href="#fn6" class="footnote-ref" id="fnref6" role="doc-noteref"><sup>6</sup></a></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><img src="/images/kanjideck/9455B77F-7ABB-441F-8841-01ECFA3A6A24.webp" alt="Fig 7. First prototype" /></td>
<td style="text-align: center;"><img src="/images/kanjideck/IMG_8121.webp" alt="Fig 8. First prototype" /></td>
</tr>
</tbody>
</table>
<p>I kept daily driving the Anki deck, improving the cards information and layout,
and designing the product. Two other important things I tackled at this time were:</p>
<ul>
<li><p>Meta cards for the physical deck, including a tutorial, reference cards for
Hiragana and Katakana, a reference card for verb and adjective conjugation,
and markers for physical spaced repetition (to make a kind of Leitner box
using them to separate which cards are in which level)</p></li>
<li><p>The box design to package the cards. The Blender skills I had developed ended
up being very helpful when designing the deck boxes, as I was able to lay out
my design on a 3D model with accurate dimensions and preview it.</p></li>
</ul>
<p>The second order, on October 19th, included three copies of the same deck
of cards, properly packaged, using various different sizes/textures for the
cards and for the boxes. The price for printing each single deck of 90 cards with
a rigid box was close to 50€, without shipping. The values are much more
reasonable when buying at scale, but for that I need the backing through Kickstarter:</p>
<figure>
<img src="/images/kanjideck/order2.webp" alt="Fig 9. Ordering different types of cards" />
<figcaption aria-hidden="true">Fig 9. Ordering different types of cards</figcaption>
</figure>
<p>This order proved invaluable to really get a feel for the different types available
and choose the best fit for the Japanese-style cards. The linen material came
on top for the cards, but not for the box. Here are the three packages when
they arrived<a href="#fn7" class="footnote-ref" id="fnref7" role="doc-noteref"><sup>7</sup></a>:</p>
<figure>
<img src="/images/kanjideck/IMG_8449.webp" alt="Fig 10. Three Kanjidecks just arrived" />
<figcaption aria-hidden="true">Fig 10. Three Kanjidecks just arrived</figcaption>
</figure>
<p>I iterated on the design a few more times, then tested all three physical boxes
(for JLPT-5, JLPT-4, and JLPT-3 decks). Originally, I had three decks where
each tier contained all cards from all previous tiers. That was a bad idea and
at some point I pivoted to having each of the three decks correspond to a
single JLPT level.</p>
<p>In the end, the final physical decks look like this:</p>
<figure>
<img src="/images/kanjideck/three_kd.webp" alt="Fig 11.1. Final Kanjidecks for JLPT-5, JLPT-4, and JLPT-3" />
<figcaption aria-hidden="true">Fig 11.1. Final Kanjidecks for JLPT-5, JLPT-4, and JLPT-3</figcaption>
</figure>
<figure>
<img src="/images/kanjideck/IMG_4824.webp" alt="Fig 11.2. Final Kanjideck JLPT-4" />
<figcaption aria-hidden="true">Fig 11.2. Final Kanjideck JLPT-4</figcaption>
</figure>
<figure>
<img src="/images/kanjideck/IMG_4791.webp" alt="Fig 11.3. Final Kanjideck JLPT-3" />
<figcaption aria-hidden="true">Fig 11.3. Final Kanjideck JLPT-3</figcaption>
</figure>
<h1 data-number="3" id="starting-a-company-in-the-u.s.-october-2024"><span class="header-section-number">3</span> Starting a Company in the U.S. (October 2024)</h1>
<p>I was dismayed when I found out that Kickstarters can only be run from <a href="https://help.kickstarter.com/hc/en-us/articles/115005128594-Who-can-use-Kickstarter">a few
specific
countries</a>.
Portugal’s not in that list! Kickstarter <a href="https://help.kickstarter.com/hc/en-us/articles/4415123219995">suggests</a> one
could open a business in the United States (a supported country) using <a href="https://stripe.com/en-pt/atlas/">Stripe Atlas</a>.
That’s what I ended up doing.</p>
<p>The exact details of how to setup a company through Stripe Atlas are now
unfortunately forgotten<a href="#fn8" class="footnote-ref" id="fnref8" role="doc-noteref"><sup>8</sup></a>. I
just have to say that it is remarkable how they will handle everything for you
and deliver you the business legal documents after a few days. At the time,
that cost $300. I also opened a US bank account with
<a href="https://mercury.com/">Mercury</a> as per Stripe’s recommendation, which went (and has been) fantastically good.</p>
<p>(On a side note, Mercury are famously known in the Haskell circles for, well,
<a href="https://serokell.io/blog/haskell-in-production-mercury">using Haskell in
production</a>. They are
also sponsoring all my work on the <a href="/posts/2026-01-07-haskell-debugger-for-ghc914.html">new and improved Haskell
debugger</a>!).</p>
<figure>
<img src="/images/kanjideck/IMG_8411.webp" alt="Fig 12. Incorporating my Company with Stripe Atlas" />
<figcaption aria-hidden="true">Fig 12. Incorporating my Company with Stripe Atlas</figcaption>
</figure>
<h2 data-number="3.1" id="accounting-and-taxes"><span class="header-section-number">3.1</span> Accounting and Taxes</h2>
<p>Having a company comes with some responsibilities. The kind which you typically
delegate, unless of course you’re hell bent on doing everything yourself to
keep expenses down. Notably, one has to keep books and eventually report taxes
according to them (and they better be correct!).</p>
<p>Luckily, some years prior, I decided to keep my personal finances using a
proper ledger with double-entry bookkeeping, accounting accounts, and the
standard reports (balance statement, income sheet, cash flow). Mostly, what I
studied applies to personal finance just as well as accounting for a simple
business, so I knew roughly what to do with the books from the start and picked
the rest up as I went.</p>
<p>Perhaps interestingly, I keep my books using <a href="https://plaintextaccounting.org/">Plain Text
Accounting</a> (PTA), a discipline of
bookkeeping which uses plain text files and CLI-friendly software to read and
operate on them. My PTA tool of choice is <a href="https://hledger.org/">hledger</a> (a
great tool that also happens to be written in Haskell). That said, the
transactions and postings formats are quite similar across the existing PTA
tools, so the documentation and guides on accounting with a particular tool
typically generalise well to PTA tools at large. I recommend <a href="https://docs.google.com/document/d/100tGcA4blh6KSXPRGCZpUlyxaRUwFHEvnz_k9DyZFn4/edit?tab=t.0#heading=h.uqoebvl2qxjs">Beancount’s “The
Double-Entry Counting
Method”</a>
for those curious about double-entry bookkeeping, Plain Text Accounting, or just both.</p>
<p>Secondly, the books are used to produce reports from which you should have
sufficient and correct information to fill in the Tax Reports. Now, I was used
to filing taxes in Portugal using the government’s official website form –
many fields can come pre-filled in, and the ones you fill in yourself are
validated for consistency with one another. I never thought much of it until I
had to file taxes for my foreign owned LLC in the United States.</p>
<p>Tax reports in the U.S. are submitted by faxing the forms to a government
number. Filing them feels a bit like playing <a href="https://keeptalkinggame.com">“Keep Talking and Nobody
Explodes”</a>, a fantastic game where one player is
given a bomb to defuse and the other a manual with (contrived) instructions on
how to do so (but can’t see the bomb!)<a href="#fn9" class="footnote-ref" id="fnref9" role="doc-noteref"><sup>9</sup></a>. In this case, you get to see both <a href="https://www.irs.gov/pub/irs-pdf/f5472.pdf">the
bomb</a> and <a href="https://www.irs.gov/pub/irs-pdf/f5472.pdf">the
instructions</a>, but the difficulty is
Nightmare<a href="#fn10" class="footnote-ref" id="fnref10" role="doc-noteref"><sup>10</sup></a>, and there are <a href="https://www.irs.gov/pub/irs-pdf/f1120.pdf">hidden
bombs</a>, and <a href="https://www.irs.gov/pub/irs-pdf/i1120.pdf">hidden
instructions</a>. Good luck! You should
<em>probably</em> pay someone to do it.</p>
<h1 data-number="4" id="spreadsheets-and-pricing-november-2024"><span class="header-section-number">4</span> Spreadsheets and Pricing (November 2024)</h1>
<p>How do you price a product? (Really, how? Do recommend some theory if you can).</p>
<p>Moreover, Kickstarter projects have to set a goal for how many dollars the
project must raise in pledges for it to be deemed successful. When that goal is
achieved, the pledged money is charged to the clients and the “Rewards” (which
you can think of like a pre-order) must be fulfilled. If the project doesn’t
reach the goal, no money is charged and no Rewards are to be delivered. This is
<a href="https://help.kickstarter.com/hc/en-us/articles/115005047893-Why-is-funding-all-or-nothing">Kickstarter’s all-or-nothing funding</a> model.</p>
<p>With that in mind, my challenge was to:</p>
<ul>
<li>Price three different products, considering discounts and bundles;</li>
<li>With a manufacturing cost dependent on the variable amount of units sold of each type;</li>
<li>Across the world, with variable VAT/sales tax and shipping per country.</li>
</ul>
<p>I’m going to skip ahead to the better and refined final iteration of my
spreadsheet, which I used to make the final decisions about the price and Kickstarter goal:</p>
<figure>
<img src="/images/kanjideck/spreadsheet.webp" alt="Fig 13. Final costs and profits spreadsheet" />
<figcaption aria-hidden="true">Fig 13. Final costs and profits spreadsheet</figcaption>
</figure>
<p>I’m not a spreadsheet expert by any means (though I know how to implement a poor man’s one in a <em>single line</em> of Haskell<a href="#fn11" class="footnote-ref" id="fnref11" role="doc-noteref"><sup>11</sup></a>),
so don’t take this as a necessarily good way of approaching this problem. In
fact, if you know how I could’ve done this better I’ll gladly take some pointers.</p>
<p>My strategy was to have one row per deck type, with a different row for the
early bird discounted deck (EBN5) vs. the N5 deck vs. the N5+N4 combination.
Rows are grouped by regions which have similar VATs (picking a worst-case-ish
approximation for the region) and the same shipping. For each deck I table in
green the revenue from each sale of one unit (i.e. unit price and shipping
charged) and in red the costs of selling that unit (i.e. manufacturing,
shipping cost, Kickstarter fee, Stripe fee, and VAT). In blue are key derived
metrics per unit (i.e. profit, profit %, and how much shipping I’m charging as
a % of the unit price).</p>
<p>Note: In Kickstarter, there is no way to differentiate pricing per region, so some
differentiation which takes into account e.g. VAT is made via the shipping
charged, which, in contrast, is per country.<a href="#fn12" class="footnote-ref" id="fnref12" role="doc-noteref"><sup>12</sup></a></p>
<p>To manage the variable number of orders per deck, I set a baseline: 250 copies
of the JLPT-5 deck (90 cards), 250 copies of the JLPT-4 deck (177 cards), and
100 copies of the JLPT-3 deck (390 cards). Those amounts were sufficient to
have a positive margin. The Kickstarter funding goal was derived roughly from
the price charged for those orders summed. In a separate cell, I had a
multiplier which I tweaked to interactively experiment and see what my margins
could look like if I sold more than that baseline. FWIW, the numbers in the
spreadsheet image are for the baseline exactly.</p>
<h1 data-number="5" id="digital-infrastructure-december-2024"><span class="header-section-number">5</span> Digital Infrastructure (December 2024)</h1>
<p>I got a domain <a href="https://kanjideck.com">kanjideck.com</a> and, at the start of
December, started hosting a handful of services on a simple
<a href="https://www.hetzner.com/">Hetzner</a> machine. The whole machine is configured
from scratch using <a href="https://nixos.org/">NixOS</a> and I can build the full machine
derivation on my macOS machine and then copy and apply it to the remote
machine. Some services I’m now self-hosting for the business:</p>
<ul>
<li><a href="https://plausible.io/">Plausible</a>, analytics for the Kanjideck website and this blog</li>
<li><a href="https://listmonk.app/">Listmonk</a>, for managing mailing lists (many
recommended having a mailing list of interested people to build good initial
momentum when the Kickstarter launches, so I did)</li>
<li><a href="https://github.com/grafana/grafana">Grafana</a>, for monitoring the status of my services</li>
<li><a href="https://github.com/fail2ban/fail2ban">fail2ban</a>, after noticing just how many attempts there were to log into my mail server</li>
<li><a href="https://nixos-mailserver.readthedocs.io/">NixOS Mailserver</a>, for self-hosting my own mail server</li>
<li><code>scrollsent</code>, a small custom service which “wraps” listmonk and receives the
mailing-list subscribe requests instead<a href="#fn13" class="footnote-ref" id="fnref13" role="doc-noteref"><sup>13</sup></a>.</li>
</ul>
<p>Wait, what?! Are you self-hosting e-mail? Is that not insane?!</p>
<p>TL;DR: Yes.</p>
<p>Originally, despite setting everything up s.t. my e-mails get 10/10 on
<a href="https://www.mail-tester.com/">mail-tester.com</a>, too many e-mails went straight
to spam. I kept up at it, and encouraged people on the website to confirm their
subscription by checking their spam inbox. I think this improved my mail
server’s deliverability, as more e-mails (as far as I could tell) were being
delivered after many confirmed subscriptions.</p>
<p>I use it reliably to get e-mail. When sending direct e-mail using my mail
client there’s no feedback whatsoever on deliverability (right?), except if
they’re answered. Replying to e-mails seems OK.</p>
<p>But, sending promotional e-mails in bulk? I was very wrong to think I had
succeeded in setting everything up perfectly and building reputation… it does
not matter! See Murphy’s Law section below.</p>
<p>During this time, I also started working on the
<a href="https://kanjideck.com">kanjideck.com</a> website, on the <a href="https://kanjideck.com/guide">guide to using the
cards</a> and on the <a href="https://www.kickstarter.com/projects/rromes/kanjideck">Kickstarter
page</a>.</p>
<table>
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<thead>
<tr>
<th style="text-align: center;">Fig 14. Landing page in December</th>
<th style="text-align: center;">Fig 15. Plausible analytics on website</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><img src="/images/kanjideck/IMG_8594.webp" alt="Fig 14. Landing page in December" /></td>
<td style="text-align: center;"><img src="/images/kanjideck/IMG_8928.webp" alt="Fig 15. Plausible analytics on website" /></td>
</tr>
</tbody>
</table>
<h1 data-number="6" id="marketing-and-ads-january-2025"><span class="header-section-number">6</span> Marketing and Ads (January 2025)</h1>
<p>Marketing is challenging.</p>
<p>I got started with the mindset of a one-man-band who is determined to learn
everything that’s necessary. I started an Instagram page to promote the project
and started paying for ads shortly after to drive people to my website. The
goal was to build a mailing list which would help create momentum on launch
day.</p>
<p>Social media management is not for me (more generally, social media isn’t).
Creating new content regularly to Feed The Beast wasn’t fun and the effort
never really seemed to pay off. I suppose that if you’re able to create
engaging content then perhaps the algorithm will reward you (you’re at its
mercy!), but posting simple photographs or short videos about a resource for
Japanese study never made it past 10 likes naturally.</p>
<p>The alternative is to pay Meta, Google, TikTok, Reddit, etc.</p>
<p>I should devote an entire section to just how awful it is to work with Meta
Ads. It is atrociously buggy, and they try to shove AI down your throat at
every single turn of the road. It is truly baffling how the Core Product of a
trillion-dollar company is this bad. If you suffer through this horrendous
experience, you get to watch your hard earned money being drained by Meta for
often questionable results<a href="#fn14" class="footnote-ref" id="fnref14" role="doc-noteref"><sup>14</sup></a>.</p>
<figure>
<img src="/images/kanjideck/horrendous_meta.webp" alt="Fig 16. Meta AI variations of your Ad original image (also, half of them are broken)" />
<figcaption aria-hidden="true">Fig 16. Meta AI variations of your Ad original image (also, half of them are broken)</figcaption>
</figure>
<p>The worst part is that Meta has, in my experience, the best results by far out
of the alternatives. All my attempts with Google, TikTok, and Reddit were an
even bigger waste of money. For instance, today I tried running an Ad on
Reddit again: it was easy to setup, but it blew past my $50 budget in an hour
and went on to consume $78 for a total of 47 link clicks and 0 purchases.</p>
<figure>
<img src="/images/kanjideck/reddit_bad.webp" alt="Fig 17. Reddit burns through 150% of my daily budget in an hour" />
<figcaption aria-hidden="true">Fig 17. Reddit burns through 150% of my daily budget in an hour</figcaption>
</figure>
<p>Spending money on ads really makes me wonder what my goal is. At least
something became clear to me: regardless of the goal, this is not how I want to
achieve it.</p>
<h1 data-number="7" id="burn-out-march-2025"><span class="header-section-number">7</span> Burn-out (March 2025)</h1>
<p>Marketing the project became wearisome. In between struggling to build momentum
for the project, creating more media content of the cards, preparing the
Kickstarter page, the money spent on ads, and the looming task of filming and
editing the project video for Kickstarter, I slowly started losing interest in
the project and being fatigued from making any decision about it. I missed the
launch deadline I set for myself, with no video anywhere near completed.</p>
<p>Add to this the instability in trade caused by the Trump tariffs, considering
my manufacturer was in China, I felt even less motivated to continue working on
the project. On April 9th, I posted to Instagram saying Kanjideck was suspended
indefinitely.</p>
<table>
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<thead>
<tr>
<th style="text-align: center;">Fig 18. Received the final prototypes</th>
<th style="text-align: center;">Fig 19. Announced suspension few days later</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><img src="/images/kanjideck/received_decks.webp" alt="Fig 18. Received the final prototypes" /></td>
<td style="text-align: center;"><img src="/images/kanjideck/tariffs.webp" alt="Fig 19. Announced suspension few days later" /></td>
</tr>
</tbody>
</table>
<h1 data-number="8" id="reaching-out-for-help-october-2025"><span class="header-section-number">8</span> Reaching out for help (October 2025)</h1>
<p>I think I eventually came to the realization that I couldn’t, nor needed, to do
all of this alone.</p>
<p>My sister’s an excellent artist. Here’s a recent painting of hers:</p>
<figure>
<img src="/images/kanjideck/IMG_7260.webp" alt="Fig 20. S/Título - Catarina Mesquita" />
<figcaption aria-hidden="true">Fig 20. S/Título - Catarina Mesquita</figcaption>
</figure>
<p>I floated the idea of having her film and edit the video for the Kickstarter at
some point and she was happy to help me. Moreover, she would handle all of the
social media content and management. That took a huge burden off of my hands,
and I was suddenly free to tackle the parts of the project I was enthusiastic
about (like finishing the explanations of how to study with
Kanjideck, finalizing the prices, and actually launching!).</p>
<p>After some iterations of filming me, the cards, and a lot of time editing, in
December 2025 we had a fantastic Kickstarter video for Kanjideck:</p>
<iframe width="100%" height="315" src="https://www.youtube-nocookie.com/embed/5z3gNS9OrpA?si=iannuE4qbo-DEu0m" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen>
</iframe>
<p>Also then, my partner started taking care of making Ad creatives (all of which
were significantly better looking than mine). And my mom wrote a few draft
e-mails in preparation for the launch!</p>
<p>(Seriously, I wouldn’t have been able to ever launch were it not for all your
help!)</p>
<h1 data-number="9" id="launching-on-kickstarter-january-2026"><span class="header-section-number">9</span> Launching on Kickstarter (January 2026)</h1>
<p>Kanjideck <a href="https://www.kickstarter.com/projects/rromes/kanjideck">launched on Kickstarter</a> on the 27th of January.</p>
<p>A few days prior to the launch, I sent two e-mails announcing the date and time
at which the project would be live. Backing early would ensure an early bird
discount and help the project gain momentum. The funding goal is $55,000.</p>
<p>On launch day at 13:00 GMT+0 we sent e-mails to everyone subscribed, posted on social media, and opened the Kickstarter!</p>
<p>In the first hour we received about $1,500 in pledges and until the end of the
first day we had raised about $5,000 in total. On the second we raised
about $2,500, and on the third $1,100. That’s still far from the all-or-nothing
goal! It’s certainly not clear, but I still believe it might be possible to
reach the funding goal before the campaign ends (on February 26).</p>
<figure>
<img src="/images/kanjideck/backers.webp" alt="Fig 21. Kickstarter pledges" />
<figcaption aria-hidden="true">Fig 21. Kickstarter pledges</figcaption>
</figure>
<p>As I’m writing this post, the Kickstarter page displays $8,808 raised from 136 backers:</p>
<figure>
<img src="/images/kanjideck/kickstarter_3.webp" alt="Fig 22. At 16% of the goal on the 3rd day" />
<figcaption aria-hidden="true">Fig 22. At 16% of the goal on the 3rd day</figcaption>
</figure>
<p>(And, a week later, we’re at $15K (28%) from 254 backers…!)</p>
<p>There’s of course more to do until the campaign is over, and especially more to
do afterwards if the campaign is successful. But I’ll leave that for a follow
up post.</p>
<p>In the meantime, I’ll continue studying. I’m at 1130 Kanji learned over 434
consecutive days, but there’s still about a thousand more to go!</p>
<!-- ![Fig 23. Anki heatmap shows all a full year of reviews](/images/kanjideck/anki_heatmap.webp) -->
<h2 data-number="9.1" id="murphys-law"><span class="header-section-number">9.1</span> Murphy’s Law</h2>
<p>To go over a few of the things that did go wrong near the launch:</p>
<ul>
<li><p>Right when I sent the first round of e-mails ever to my subscribers, Google
was having an <a href="https://www.google.com/appsstatus/dashboard/incidents/NNnDkY9CJ36annsfytjQ">incident</a>
where a bug caused misclassification of most e-mails as spam</p></li>
<li><p>Remember when I said that hosting my own mail server had gone wrong?
When I sent the second round of e-mails, on the day before the launch, to my
1400 subscribers, I immediately received some 300 “undelivered mail”
notifications justified by Microsoft having blocklisted my mail server’s IP.</p>
<p>I hastily migrated my mailing list to <a href="https://sendgrid.com/en-us">SendGrid</a>
to make sure I would have proper deliverability on the launch day.</p></li>
<li><p>On the day I launched, Kickstarter had an outage and <a href="https://status.kickstarter.com/incidents/w6kv8yt78w2j">was
down</a> for about an
hour</p></li>
</ul>
<p>That sounds amusingly unlucky, but on the other hand it might just be that,
when it was my product on the line, I noticed all the internet issues that I
wouldn’t typically care about.</p>
<h1 data-number="10" id="conclusion"><span class="header-section-number">10</span> Conclusion</h1>
<p>It was worth it.</p>
<figure>
<img src="/images/kanjideck/anki.webp" alt="Fig 23. Our cat named Anki" />
<figcaption aria-hidden="true">Fig 23. Our cat named Anki</figcaption>
</figure>
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>Listed by the
Japanese Ministry of Education as <a href="https://en.wikipedia.org/wiki/J%C5%8Dy%C5%8D_kanji">Jōyō
kanji</a><a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2"><p>There are more design questions: whether or not to use
<a href="https://pt.wikipedia.org/wiki/Rōmaji">Rōmaji</a>, what readings to include, what
examples, how to display the character, and the aesthetics of the design
themselves are important<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn3"><p>From here on I started daily driving this Anki deck and doing some tweaks to
the displayed information and to how it was laid out. A few weeks in it had
reached a fixpoint. I’m still using it today, every day!<a href="#fnref3" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn4"><p>Physical books and studying with a notebook
is still my preference, even though in the long run Anki is unbeatable at
managing the large amount of cards to review. I still use Anki daily.<a href="#fnref4" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn5"><p>Open-source is a big part of my life (including my day job), and even
though for now Kanjideck is available only in the <a href="https://www.kickstarter.com/projects/rromes/kanjideck">Kickstarter
page</a>, I intend to make
the source for building the digital version available as soon as I can clean it
up.<a href="#fnref5" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn6"><p>In this picture you may also find some scribbles that refer to a board game I tried to design using the Kanjideck cards exclusively! Nothing came out of it (yet?).<a href="#fnref6" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn7"><p>Here you may also notice a typo in the boxes, using ぉ rather than を<a href="#fnref7" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn8"><p>I do remember cycling in a hurry to catch the last
slot for making a new Passport (a requirement for opening a US company).<a href="#fnref8" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn9"><p>If you haven’t played it, I heartily
recommend it<a href="#fnref9" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn10"><p>it “isn’t even remotely fair”<a href="#fnref10" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn11"><p><code>loeb x = xs where xs = fmap ($xs) x</code>, see the fantastic Dan Piponi’s <a href="http://blog.sigfpe.com/2006/11/from-l-theorem-to-spreadsheet.html">From Löb’s Theorem to
Spreadsheet
Evaluation</a><a href="#fnref11" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn12"><p>An alternative here, that would result
in less approximations, would be to charge VAT and shipping per customer after
the Kickstarter campaign is finished. I opted for charging everything upfront
as I don’t think it’s always clear to many customers that there will be
(sometimes considerably large) additional charges after the campaign ends otherwise.<a href="#fnref12" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn13"><p>Listmonk has some limitations I had to work around to get better e-mail scores.
Namely, being able to configure the e-mail sent for the subscription confirmation request.<a href="#fnref13" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn14"><p>For example, if you don’t restrict the countries to
which ads are shown, your entire budget can be blown in one go and your website
gets a 99% bounce-rate giant wave of visitors with zero conversions<a href="#fnref14" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
]]></summary>
</entry>
<entry>
    <title>Haskell Debugger for GHC 9.14</title>
    <link href="http://alt-romes.github.io/posts/2026-01-07-haskell-debugger-for-ghc914.html" />
    <id>http://alt-romes.github.io/posts/2026-01-07-haskell-debugger-for-ghc914.html</id>
    <published>2026-01-07T00:00:00Z</published>
    <updated>2026-01-07T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This post was first published inline to the <a href="https://discourse.haskell.org/">Haskell
Discourse</a>, where there was some <a href="https://discourse.haskell.org/t/the-haskell-debugger-for-ghc-9-14/13499">discussion
about the debugger</a>:</p>
<h1 data-number="1" id="the-haskell-debugger-for-ghc-9.14"><span class="header-section-number">1</span> The Haskell Debugger for GHC 9.14</h1>
<p><strong>The Haskell Debugger is ready to use with GHC-9.14!</strong></p>
<p>The installation, configuration, and talks can be found in <a href="https://well-typed.github.io/haskell-debugger">the official
website</a>. The tl;dr first step
is installing the debugger:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> ghc <span class="at">--version</span> <span class="co"># MUST BE GHC 9.14</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="ex">The</span> Glorious Glasgow Haskell Compilation System, version 9.14.1</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cabal install haskell-debugger <span class="dt">\</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>    <span class="at">--allow-newer</span><span class="op">=</span>base,time,containers,ghc,ghc-bignum,template-haskell <span class="dt">\</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>    <span class="at">--enable-executable-dynamic</span> <span class="co"># ON WINDOWS, DO NOT PASS --enable-executable-dynamic</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="ex">...</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> ~/.local/bin/hdb <span class="at">--version</span> <span class="co"># VERIFY IT&#39;S THE LATEST!</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="ex">Haskell</span> Debugger, version 0.11.0.0</span></code></pre></div>
<p>The second step is configuring your editor to use the debugger via the <strong>D</strong>ebug <strong>A</strong>dapter <strong>P</strong>rotocol (DAP).
- For VSCode, install <a href="https://marketplace.visualstudio.com/items?itemName=Well-Typed.haskell-debugger-extension">the haskell debugger extension</a>.
- For Neovim, install <code>nvim-dap</code> and <a href="https://codeberg.org/mfussenegger/nvim-dap/wiki/Debug-Adapter-installation#haskell-hdb">configure it for haskell-debugger</a>
- For other editors, consult your DAP documentation and let others know how!</p>
<p>Bug reports and discussions are welcome in the <a href="https://github.com/well-typed/haskell-debugger">haskell-debugger issue
tracker</a>.</p>
<p>My MuniHac 2025 talk also walks through the installation, usage, and design of
the debugger. Do note much has been improved since the talk was given, and much
more will still improve.</p>
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/urYtE15ryA0?si=6LtSEfXfCOSJFG11" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen>
</iframe>
<h2 data-number="1.1" id="a-little-bit-more-info"><span class="header-section-number">1.1</span> A little bit more info</h2>
<p>The debugger work is sponsored by Mercury. It’s the project in which I’ve spent
most of my full working days (for almost a full year now), with the invaluable
help from my team at Well-Typed.</p>
<p>The debugger is meant to work both on trivial files and on large and complex
codebases<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>.
It is a GHC application so <em>all features are supported</em>. Like HLS, it also uses
<code>hie-bios</code> to automatically configure the session based on your cabal or stack
project.</p>
<p>Robustness is a main goal of the debugger. If anything doesn’t work, or if you
have performance issues, or something crashes, please don’t hesitate to submit
a bug. We’ve got a small but respectable testsuite, and have tested performance
by debugging GHC itself, but there’s much still to be fixed and improved.</p>
<p><strong>Roadmap</strong>: There’s a lot to do. I’m currently working on callstacks and
multi-threaded support. Do let me know what features would be most important to
you, so I can also factor that into the future planning.</p>
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>Although, for large codebases, the usability is still rough around
the edges because of possibly long bytecode compilation times, and library code
not being interpreted. We’ve made considerable progress to improve this with
the <a href="https://discourse.haskell.org/t/rfc-introduce-a-serialisable-bytecode-format-and-corresponding-bytecode-way/12678">bytecode artifacts work</a><a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>]]></summary>
</entry>
<entry>
    <title>Lazy Linearity for a Core Functional Language (POPL 2026)</title>
    <link href="http://alt-romes.github.io/posts/2025-11-26-lazy-linearity-popl26.html" />
    <id>http://alt-romes.github.io/posts/2025-11-26-lazy-linearity-popl26.html</id>
    <published>2025-11-26T00:00:00Z</published>
    <updated>2025-11-26T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’m very proud to announce that <a href="https://doi.org/10.1145/3776711">Lazy Linearity for a Core Functional
Language</a>, a paper by myself and <a href="https://web.tecnico.ulisboa.pt/bernardo.toninho/">Bernardo
Toninho</a>, will be published
at <a href="https://popl26.sigplan.org/track/POPL-2026-popl-research-papers">POPL 26</a>! [<a href="https://doi.org/10.1145/3776711">DOI</a>, <a href="https://dl.acm.org/doi/10.1145/3776711">ACM</a>].</p>
<p>The extended version of the paper, which includes all proofs, is available
here [<a href="https://arxiv.org/abs/2511.10361">arXiv</a>, <a href="/data/papers/popl26-extended-version-2511.10361v2.pdf">PDF</a>, <a href="https://doi.org/10.1145/3776711">DOI</a>].</p>
<p><strong>The short-ish story</strong>: In 2023, for my Master’s thesis, I reached out to <a href="https://assert-false.science/arnaud/">Arnaud
Spiwack</a> to discuss how Linear Types had
been implemented in GHC. I wanted to research compiler optimisations made
possible by linearity. Arnaud was quick to tell me:</p>
<p>“<em>Well yes, but you can’t!“</em></p>
<p><em>“Even though Haskell is linearly typed, Core isn’t!”</em><a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<p>Linearity is ignored in Core because, as soon as it’s optimised,
previously valid linear programs become invalid.
<!---->
It turns out that traditional linear type systems are too syntactic, or
<em>strict</em>, about understanding linearity – but Haskell, regardless of linear
types, is lazily evaluated. Improving optimisations would have to wait.</p>
<p>Our paper presents a system which, in contrast, also accepts programs that can
only be understood as linear under non-strict evaluation. Including the vast
majority of optimised linear Core programs (with proofs!).</p>
<p>The key ideas of this paper were developed during my Master’s, but it took a
few more years of on-and-off work (supported by my employer
<a href="https://well-typed.com/">Well-Typed</a>) with Bernardo to crystalize the understanding of a
“lazy linearity” and strengthen the theoretical results.</p>
<p>Now, the proof of the pudding is in the eating. Go read it!</p>
<br>
<p style="width:100%; text-align: center">
<strong>Abstract</strong>
<p>
<section style="margin-left: 2em; margin-right: 2em; margin-bottom: 2em;">
Traditionally, in linearly typed languages, consuming a linear resource is
synonymous with its syntactic occurrence in the program. However, under the
lens of non-strict evaluation, linearity can be further understood
semantically, where a syntactic occurrence of a resource does not necessarily
entail using that resource when the program is executed. While this distinction
has been largely unexplored, it turns out to be inescapable in Haskell’s
optimising compiler, which heavily rewrites the source program in ways that
break syntactic linearity but preserve the program’s semantics. We introduce
Linear Core, a novel system which accepts the lazy semantics of linearity
statically and is suitable for lazy languages such as the Core intermediate
language of the Glasgow Haskell Compiler. We prove that Linear Core is sound,
guaranteeing linear resource usage, and that multiple optimising
transformations preserve linearity in Linear Core while failing to do so in
Core. We have implemented Linear Core as a compiler plugin to validate the
system against linearity-heavy libraries, including linear-base.
</section>
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>Core is the
intermediate compiler language to which source Haskell is desugared and to
which optimisations are applied<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>]]></summary>
</entry>
<entry>
    <title>Automatically Packaging a Haskell Library as a Swift Binary XCFramework</title>
    <link href="http://alt-romes.github.io/posts/2025-07-05-packaging-a-haskell-library-as-a-swift-binary-xcframework.html" />
    <id>http://alt-romes.github.io/posts/2025-07-05-packaging-a-haskell-library-as-a-swift-binary-xcframework.html</id>
    <published>2025-07-05T00:00:00Z</published>
    <updated>2025-07-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#announcing-xcframework" id="toc-announcing-xcframework"><span class="toc-section-number">1</span> Announcing: xcframework</a>
<ul>
<li><a href="#xcframeworks" id="toc-xcframeworks"><span class="toc-section-number">1.1</span> XCFrameworks</a></li>
<li><a href="#how-to-install-xcframework" id="toc-how-to-install-xcframework"><span class="toc-section-number">1.2</span> How to install <code>xcframework</code></a></li>
<li><a href="#how-to-use-the-xcframework-in-xcode" id="toc-how-to-use-the-xcframework-in-xcode"><span class="toc-section-number">1.3</span> How to use the XCFramework in XCode</a></li>
<li><a href="#building-simple-swift-package" id="toc-building-simple-swift-package"><span class="toc-section-number">1.4</span> Building simple Swift package</a></li>
<li><a href="#must-use-cabal-foreign-library-stanza" id="toc-must-use-cabal-foreign-library-stanza"><span class="toc-section-number">1.5</span> Must use Cabal Foreign Library stanza</a></li>
<li><a href="#conclusion" id="toc-conclusion"><span class="toc-section-number">1.6</span> Conclusion</a></li>
</ul></li>
</ul>
</div>
<p>I’ve written about <em>Haskell x Swift</em> interoperability before.
<a href="2024-04-02-calling-haskell-from-swift.html">Calling Haskell from Swift</a> is
about marshalling and the foreign function interface. But <a href="2023-11-10-creating-a-macos-app-with-haskell-and-swift.html">Creating a macOS app
with Haskell and Swift</a> tells the
much messier tale of hijacking XCode to vodoo together the Haskell library, its
headers, and two handfuls of other magic ingredients into one buildable SwiftUI
application.</p>
<p>Stop! Don’t click on the last link. No, it turns out that my XCode sallies
strayed very far from the yellow brick road. The IDE is confused. Recompilation
bugs abound. Complexity is through the roof juggling <code>.modulemap</code>s, <code>.xcconfig</code>
dynamic settings, and sketchy <code>.sh</code> scripts.</p>
<p>Let’s walk the happy path.</p>
<h1 data-number="1" id="announcing-xcframework"><span class="header-section-number">1</span> Announcing: xcframework</h1>
<p>Perhaps obvious in retrospect, the <em>demon-less</em> way to add a Haskell library to
the dependencies of a Swift application is to build an independent
Swift Package wrapping the Haskell library – something that can be done
without XCode in sight. Easy peasy:</p>
<ol type="1">
<li>Build the Haskell library using Cabal</li>
<li>Create a Swift package from the Haskell artifacts</li>
<li>Add the Swift package as a dependency to the project</li>
</ol>
<p>And it turns out that (1) and (2) can be merged together using <a href="https://well-typed.com/blog/2025/01/cabal-hooks/">Cabal
SetupHooks</a>!</p>
<p>Moreover, I’m happy to announce I’ve neatly packaged and released that build
process automation as a Haskell library called
<a href="https://hackage.haskell.org/package/xcframework">xcframework</a> on Hackage.</p>
<p>Onwards! – for what it does and how to use it.</p>
<h2 data-number="1.1" id="xcframeworks"><span class="header-section-number">1.1</span> XCFrameworks</h2>
<p>Apple introduced XCFramework bundles back in a <a href="https://developer.apple.com/videos/play/wwdc2019/416/">WWDC19
session</a>. An XCFramework
is a <a href="https://developer.apple.com/documentation/xcode/creating-a-multi-platform-binary-framework-bundle">multiplatform binary framework bundle</a>.</p>
<p>For our purposes, that means we can create a Swift Package just from a binary
linkable artifact and a couple of header files. Then, any Swift project can
depend on this binary Swift package and call the functions exposed to the
headers and make sure the bundled library will be linked in with the final
executable. Specifically, the <code>xcframework</code> Haskell library, for a given
Haskell library, bundles:</p>
<ul>
<li>The foreign shared library (<code>.dylib</code>) resulting from building with GHC/Cabal</li>
<li>The foreign export headers generated from the <code>foreign export &lt;haskell_function&gt;</code> declarations</li>
<li>The RTS headers
<ul>
<li>which are needed to initialize the RTS from Swift</li>
<li>and because they are <code>#include</code>d by the <code>foreign export</code> headers</li>
</ul></li>
<li>A <code>.modulemap</code> exporting the foreign exported functions and <code>HsFFI.h</code>
<ul>
<li>The module map basically turns the headers into a Swift module that can
be transparently <code>import</code>ed from other Swift modules.</li>
</ul></li>
</ul>
<p>And any Swift library or application can transparently depend on this
<code>.xcframework</code> and use the foreign exported Haskell functions without further
ado.</p>
<h2 data-number="1.2" id="how-to-install-xcframework"><span class="header-section-number">1.2</span> How to install <code>xcframework</code></h2>
<p>In your cabal file, change the <code>build-type</code> to <code>Hooks</code> (and set <code>cabal-version: 3.14</code> if not set already):</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode diff"><code class="sourceCode diff"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="st">- build-type:     Simple</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="va">+ build-type:     Hooks</span></span></code></pre></div>
<p>And add a <code>setup-depends</code> stanza with a dependency on <code>xcframework</code>:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>custom-setup</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  setup-depends:</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>    base        &gt;= 4.18 &amp;&amp; &lt; 5,</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>    xcframework &gt;= 0.1</span></code></pre></div>
<p>Finally, create a file called <code>SetupHooks.hs</code> in the root of your Cabal package
with the following contents, substituting the <code>_build/MyHaskellLib.xcframework</code> string for the
filepath to where the <code>.xcframework</code> should be written:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">SetupHooks</span> ( setupHooks ) <span class="kw">where</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Distribution.XCFramework.SetupHooks</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a><span class="ot">setupHooks ::</span> <span class="dt">SetupHooks</span></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>setupHooks <span class="ot">=</span> xcframeworkHooks <span class="st">&quot;_build/MyHaskellLib.xcframework&quot;</span></span></code></pre></div>
<p>Now, whenever you run <code>cabal build</code>, the built libraries will also be bundled into an <code>.xcframework</code>.</p>
<h2 data-number="1.3" id="how-to-use-the-xcframework-in-xcode"><span class="header-section-number">1.3</span> How to use the XCFramework in XCode</h2>
<p>In XCode:</p>
<ol type="1">
<li>Navigate to the target settings of your project.</li>
<li>Find under “General” the “Frameworks, Libraries, and Embedded Content” (or similar) section.</li>
<li>Click the add button and add the <code>.xcframework</code> framework outputted at the specified path by Cabal</li>
</ol>
<p>Now, in the entry Swift module, import the RTS and init/exit the RTS. For
instance, in a sample SwiftUI app:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode diff"><code class="sourceCode diff"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>  import SwiftUI</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="va">+ import Haskell.Foreign.Rts</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  </span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  @main</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>  struct MyExample: App {</span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="va">+ </span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a><span class="va">+     init() {</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a><span class="va">+         hs_init(nil, nil)</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a><span class="va">+</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a><span class="va">+         NotificationCenter.default</span></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a><span class="va">+           .addObserver(forName: NSApplication.willTerminateNotification,</span></span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a><span class="va">+                        object: nil, queue: .main) { _ in</span></span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a><span class="va">+           hs_exit()</span></span>
<span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a><span class="va">+         }</span></span>
<span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a><span class="va">+     }</span></span>
<span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a><span class="va">+ </span></span>
<span id="cb4-17"><a href="#cb4-17" aria-hidden="true" tabindex="-1"></a>      var body: some Scene {</span>
<span id="cb4-18"><a href="#cb4-18" aria-hidden="true" tabindex="-1"></a>          WindowGroup {</span>
<span id="cb4-19"><a href="#cb4-19" aria-hidden="true" tabindex="-1"></a>              ContentView()</span>
<span id="cb4-20"><a href="#cb4-20" aria-hidden="true" tabindex="-1"></a>          }</span>
<span id="cb4-21"><a href="#cb4-21" aria-hidden="true" tabindex="-1"></a>      }</span>
<span id="cb4-22"><a href="#cb4-22" aria-hidden="true" tabindex="-1"></a>  }</span></code></pre></div>
<p>Finally, in any Swift module, do <code>import Haskell.Foreign.Exports</code>. For now, the
name <code>Haskell.Foreign.Exports</code> is fixed and exports all foreign-exported
functions, but it could be improved in the future (perhaps it’s a good task to
contribute a patch for!)</p>
<p>For example, if your Haskell module looked like:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">MyLib</span> (doSomething) <span class="kw">where</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="ot">fib ::</span> <span class="dt">Integral</span> b <span class="ot">=&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> b</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>fib n <span class="ot">=</span> <span class="fu">round</span> <span class="op">$</span> phi <span class="op">**</span> <span class="fu">fromIntegral</span> n <span class="op">/</span> sq5</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>    sq5 <span class="ot">=</span> <span class="fu">sqrt</span> <span class="dv">5</span><span class="ot"> ::</span> <span class="dt">Double</span></span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>    phi <span class="ot">=</span> (<span class="dv">1</span> <span class="op">+</span> sq5) <span class="op">/</span> <span class="dv">2</span></span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a><span class="ot">doSomething ::</span> <span class="dt">IO</span> <span class="dt">Int</span></span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a>doSomething <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb5-11"><a href="#cb5-11" aria-hidden="true" tabindex="-1"></a>  <span class="fu">putStrLn</span> <span class="st">&quot;doing some thing&quot;</span></span>
<span id="cb5-12"><a href="#cb5-12" aria-hidden="true" tabindex="-1"></a>  <span class="fu">return</span> <span class="op">$</span> fib <span class="dv">42</span></span>
<span id="cb5-13"><a href="#cb5-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-14"><a href="#cb5-14" aria-hidden="true" tabindex="-1"></a>foreign export ccall<span class="ot"> doSomething ::</span> <span class="dt">IO</span> <span class="dt">Int</span></span></code></pre></div>
<p>In your Swift module you can now</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">Haskell</span><span class="op">.</span><span class="im">Foreign</span><span class="op">.</span><span class="im">Exports</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  <span class="op">...</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> <span class="va">x</span> <span class="op">=</span> doSomething<span class="op">()</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>  <span class="op">...</span></span></code></pre></div>
<h2 data-number="1.4" id="building-simple-swift-package"><span class="header-section-number">1.4</span> Building simple Swift package</h2>
<p>The <code>.xcframework</code> can also be easily used in a standalone swift package built
with <code>swift build</code>.</p>
<p>In your <code>Package.swift</code>, add <code>MyHaskellLib.xcframework</code> as a binary target and
make it a dependency of your main target. For instance, a simple library would
look like:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co">// swift-tools-version: 6.1</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">PackageDescription</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="va">package</span> <span class="op">=</span> Package<span class="op">(</span></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>    name<span class="op">:</span> <span class="st">&quot;MySwiftLib&quot;</span><span class="op">,</span></span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>    platforms<span class="op">:</span> <span class="op">[</span></span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a>        <span class="op">.</span>macOS<span class="op">(.</span>v15<span class="op">)</span></span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a>    <span class="op">],</span></span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a>    products<span class="op">:</span> <span class="op">[</span></span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a>        <span class="op">.</span>library<span class="op">(</span>name<span class="op">:</span> <span class="st">&quot;MySwiftLib&quot;</span><span class="op">,</span> targets<span class="op">:</span> <span class="op">[</span><span class="st">&quot;MySwiftLib&quot;</span><span class="op">])</span></span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a>    <span class="op">],</span></span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a>    targets<span class="op">:</span> <span class="op">[</span></span>
<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a>        <span class="op">.</span>target<span class="op">(</span>name<span class="op">:</span> <span class="st">&quot;MySwiftLib&quot;</span><span class="op">,</span> dependencies<span class="op">:</span> <span class="op">[</span><span class="st">&quot;MyHaskellLib&quot;</span><span class="op">],</span> path<span class="op">:</span> <span class="st">&quot;Swift&quot;</span><span class="op">),</span></span>
<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a>        <span class="op">.</span>binaryTarget<span class="op">(</span></span>
<span id="cb7-15"><a href="#cb7-15" aria-hidden="true" tabindex="-1"></a>            name<span class="op">:</span> <span class="st">&quot;MyHaskellLib&quot;</span><span class="op">,</span></span>
<span id="cb7-16"><a href="#cb7-16" aria-hidden="true" tabindex="-1"></a>            path<span class="op">:</span> <span class="st">&quot;haskell/_build/MyHaskellLib.xcframework&quot;</span></span>
<span id="cb7-17"><a href="#cb7-17" aria-hidden="true" tabindex="-1"></a>        <span class="op">)</span></span>
<span id="cb7-18"><a href="#cb7-18" aria-hidden="true" tabindex="-1"></a>    <span class="op">]</span></span>
<span id="cb7-19"><a href="#cb7-19" aria-hidden="true" tabindex="-1"></a><span class="op">)</span></span></code></pre></div>
<p>Now you can use the <code>Haskell.Foreign.Exports</code> import in any module in the
package as explained above, for instance in <code>Swift/MySwiftLib.hs</code>:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">Foundation</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">Haskell</span><span class="op">.</span><span class="im">Foreign</span><span class="op">.</span><span class="im">Exports</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="kw">struct</span> Fib <span class="op">{</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">var</span> <span class="va">val</span><span class="op">:</span> Int64</span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="kw">func</span> <span class="fu">mkFib</span><span class="op">()</span> -&gt; <span class="fu">Fib</span> <span class="op">{</span></span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">x</span> <span class="op">=</span> doSomething<span class="op">()</span></span>
<span id="cb8-10"><a href="#cb8-10" aria-hidden="true" tabindex="-1"></a>    <span class="kw">return</span> Fib<span class="op">(</span>val<span class="op">:</span> x<span class="op">)</span></span>
<span id="cb8-11"><a href="#cb8-11" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>Build the Swift package using <code>swift build</code> in the project root.</p>
<h2 data-number="1.5" id="must-use-cabal-foreign-library-stanza"><span class="header-section-number">1.5</span> Must use Cabal Foreign Library stanza</h2>
<p>Unfortunately, while I don’t figure out how to link the right amount of things
into the <code>.xcframework</code> after building a normal <code>library</code> component in Cabal,
the <code>foreign export</code>s must be exported from a <code>foreign-library</code> Cabal stanza:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>foreign-library myexample</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>    type: native-shared</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>    options: standalone</span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>    other-modules:    MyLib</span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>    build-depends:    base ^&gt;=4.20.0.0</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>    hs-source-dirs:   src</span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a>    default-language: GHC2021</span></code></pre></div>
<p>To clarify the instructions, I put together <a href="https://github.com/alt-romes/hs-xcframework-simple-demo/">a small demo
project</a> with a
working setup – if you want to try it out. Remember to build the Cabal library first!</p>
<h2 data-number="1.6" id="conclusion"><span class="header-section-number">1.6</span> Conclusion</h2>
<p>Building the Haskell library as an independent Swift Package is a much more
robust way of adding a Haskell dependency to a Swift application.</p>
<p>The <code>xcframework</code> Haskell library makes it easy to create XCFrameworks from
Haskell packages by leveraging the <code>SetupHooks</code> <a href="https://hackage-content.haskell.org/package/Cabal-hooks/docs/Distribution-Simple-SetupHooks.html">very nicely designed
API</a>.</p>
<p>While this work further lowers the bar for integrating Haskell and Swift,
marshaling and sharing high-level datatypes remains challenging. <a href="2024-04-02-calling-haskell-from-swift.html">Calling
Haskell from Swift</a> explored the
basics of using more interesting types across the FFI, but I’m also working on
a more automated approach using TH and GHC plugins.</p>
<p>Finally, I’m looking forward to <a href="https://github.com/alt-romes/haskell-swift">bug reports</a> if you try it out.</p>
]]></summary>
</entry>
<entry>
    <title>Implementing Unsure Calculator in 100 lines of Haskell</title>
    <link href="http://alt-romes.github.io/posts/2025-04-25-unsure-calculator-in-100-lines-of-haskell.html" />
    <id>http://alt-romes.github.io/posts/2025-04-25-unsure-calculator-in-100-lines-of-haskell.html</id>
    <published>2025-04-25T00:00:00Z</published>
    <updated>2025-04-25T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#unsure-calculator" id="toc-unsure-calculator"><span class="toc-section-number">1</span> Unsure Calculator</a>
<ul>
<li><a href="#sampling-it-up" id="toc-sampling-it-up"><span class="toc-section-number">1.1</span> Sampling it up</a></li>
<li><a href="#calculator-expressions" id="toc-calculator-expressions"><span class="toc-section-number">1.2</span> Calculator Expressions</a></li>
<li><a href="#showing-up" id="toc-showing-up"><span class="toc-section-number">1.3</span> Showing up</a></li>
<li><a href="#conclusion" id="toc-conclusion"><span class="toc-section-number">1.4</span> Conclusion</a></li>
</ul></li>
</ul>
</div>
<h1 data-number="1" id="unsure-calculator"><span class="header-section-number">1</span> Unsure Calculator</h1>
<p>The recently trendy <a href="https://filiph.github.io/unsure/">Unsure Calculator</a> makes
reasoning about numbers with some uncertainty just as easy as calculating with
specific numbers.</p>
<p>The key idea is to add a new “range” operator (written <code>~</code>) to the vocabulary
of a standard calculator. The range <code>x~y</code> denotes that a real value is uncertain, but
we are 95% sure that it falls between <code>x</code> and <code>y</code><a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>.</p>
<blockquote>
<p>Reading the notation is easy: when you see 10~15, you say: “ten to fifteen”.</p>
</blockquote>
<p>Arithmetic operations and friends (e.g. <code>sin</code>, or <code>log</code>)
transparently operate on ranges and literal numbers alike.
Calculation results in a plot with a range of values that
the input expression can take, and with what frequency.</p>
<!--```txt-->
<!--     above | ▒▒▒▒-->
<!--       236 | ▒▒▒-->
<!--       221 | ▒▒▒▒-->
<!--       205 | ▒▒▒▒▒▒-->
<!--       190 | ▒▒▒▒▒▒▒▒▒-->
<!--       175 | ▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--       159 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--       144 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--       129 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--       114 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--        98 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--        83 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ (79)-->
<!--        68 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--        52 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--        37 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--        22 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--         6 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--        -9 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒-->
<!--       -24 | ▒▒▒▒▒▒▒▒▒▒-->
<!--       -39 | ▒▒▒▒▒▒▒-->
<!--       -55 | ▒▒▒▒▒-->
<!--       -70 | ▒▒▒-->
<!--     below | ▒▒▒▒-->
<!--```-->
<p>The motivation behind the original article is neat, so I’ll just recommend you
read it <a href="https://filiph.github.io/unsure/">there</a> to learn how and why you’d use such a calculator. Here’s a
real life example they used:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>1400~1700 * 0.55~0.65 - 600~700 - 100~200 - 30 - 20</span></code></pre></div>
<p>Now, let’s implement it.</p>
<h2 data-number="1.1" id="sampling-it-up"><span class="header-section-number">1.1</span> Sampling it up</h2>
<p>Summon a <a href="https://www.youtube.com/watch?v=qZ4O-1VYv4c">probability monad</a> from the void<a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a>.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Dist</span> a <span class="kw">where</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Return</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> <span class="dt">Dist</span> a</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Bind</span><span class="ot">   ::</span> <span class="dt">Dist</span> b <span class="ot">-&gt;</span> (b <span class="ot">-&gt;</span> <span class="dt">Dist</span> a) <span class="ot">-&gt;</span> <span class="dt">Dist</span> a</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Normal</span><span class="ot"> ::</span> <span class="dt">Double</span> <span class="ot">-&gt;</span> <span class="dt">Double</span> <span class="ot">-&gt;</span> <span class="dt">Dist</span> <span class="dt">Double</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monad</span>       <span class="dt">Dist</span> <span class="kw">where</span> (<span class="op">&gt;&gt;=</span>) <span class="ot">=</span> <span class="dt">Bind</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Applicative</span> <span class="dt">Dist</span> <span class="kw">where</span> <span class="fu">pure</span>  <span class="ot">=</span> <span class="dt">Return</span>; (<span class="op">&lt;*&gt;</span>) <span class="ot">=</span> ap</span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Functor</span>     <span class="dt">Dist</span> <span class="kw">where</span> <span class="fu">fmap</span>  <span class="ot">=</span> liftM</span></code></pre></div>
<p>The monad instance is free: <code>pure = Return</code> and <code>(&gt;&gt;=) = Bind</code>. The <code>Normal</code>
constructor denotes a normal distribution given the standard deviation and
mean. With do-notation we can easily construct a complex tree mixing <code>Return</code>s,
<code>Bind</code>s, and <code>Normal</code>s. For instance:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>d = do</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>  s &lt;- Normal 0 1</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>  return (5 + s)</span></code></pre></div>
<p>desugars to</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>d = Bind (Normal 0 1) (\s -&gt; Return (5 + s))</span></code></pre></div>
<p>Then, embue meaning onto a <code>Dist a</code> by allowing an <code>a</code> to be sampled according to the distribution the <code>Dist</code> represents.
We use <code>StdGen</code> from <code>random</code> as a source of uniform pseudo-randomness:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">sample ::</span> <span class="dt">StdGen</span> <span class="ot">-&gt;</span> <span class="dt">Dist</span> a <span class="ot">-&gt;</span> a</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>sample g d <span class="ot">=</span> <span class="kw">case</span> d <span class="kw">of</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Return</span> x <span class="ot">-&gt;</span> x</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Normal</span> mean std_dev <span class="ot">-&gt;</span> n1 <span class="op">*</span> std_dev <span class="op">+</span> mean</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">where</span> ((u1, u2), _) <span class="ot">=</span> uniformR ((<span class="dv">0</span>,<span class="dv">0</span>), (<span class="dv">1</span>,<span class="dv">1</span>)) g</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>          (n1,  _)      <span class="ot">=</span> boxMuller u1 u2</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Bind</span> d f <span class="ot">-&gt;</span> sample g1 (f (sample g2 d))</span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">where</span> (g1, g2) <span class="ot">=</span> splitGen g</span></code></pre></div>
<p>Sampling a distribution is simple:</p>
<ul>
<li>For a constant <code>x</code>, return <code>x</code></li>
<li>For a normal distribution, use the <a href="https://en.wikipedia.org/wiki/Box–Muller_transform">Box Muller
transform</a> to transform a
pair of <em>uniformly</em> distributed random numbers in <code>[0, 1]</code> into a pair of
<em>normally</em> distributed random numbers. Then, scale according to the normal
distribution parameters (<code>mean</code>, <code>std_dev</code>).</li>
<li>For <code>Bind</code>, sample <code>a</code> from <code>Dist a</code>, feed it to the continuation, and then sample from the resulting <code>Dist b</code>.
Do make sure the PRN generator is <a href="https://hackage-content.haskell.org/package/random-1.3.1/docs/System-Random.html#v:splitGen">split</a>.</li>
</ul>
<p>Box-Muller is implemented very literally as:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>boxMuller u1 u2 <span class="ot">=</span> (r <span class="op">*</span> <span class="fu">cos</span> t, r <span class="op">*</span> <span class="fu">sin</span> t) <span class="kw">where</span> r <span class="ot">=</span> <span class="fu">sqrt</span> (<span class="op">-</span><span class="dv">2</span> <span class="op">*</span> <span class="fu">log</span> u1)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>                                               t <span class="ot">=</span> <span class="dv">2</span> <span class="op">*</span> <span class="fu">pi</span> <span class="op">*</span> u2</span></code></pre></div>
<p>We can try sampling the example above:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>&gt; sample (mkStdGen 3) (Bind (Normal 0 1) (\s -&gt; Return (5+s)))</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>5.079952851990287</span></code></pre></div>
<p>And we can also use <code>sequence . repeat</code> to generate an infinite list of samples:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>&gt; take 5 $ sample (mkStdGen 4) $ sequence $ repeat $ (Bind (Normal 0 1) (\s -&gt; Return (5+s)))</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>[4.133071135842417,5.270868355973887,6.9698645379055355,3.8369680071523447,4.2986629449038425]</span></code></pre></div>
<h2 data-number="1.2" id="calculator-expressions"><span class="header-section-number">1.2</span> Calculator Expressions</h2>
<p>Conjure up an eDSL for calculator expressions:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Expr</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">Num</span> <span class="dt">Double</span></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Add</span> <span class="dt">Expr</span> <span class="dt">Expr</span>   <span class="op">|</span> <span class="dt">Mul</span> <span class="dt">Expr</span> <span class="dt">Expr</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Abs</span> <span class="dt">Expr</span>        <span class="op">|</span> <span class="dt">Signum</span> <span class="dt">Expr</span></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Negate</span> <span class="dt">Expr</span>     <span class="op">|</span> <span class="dt">Div</span> <span class="dt">Expr</span> <span class="dt">Expr</span></span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Exp</span> <span class="dt">Expr</span>        <span class="op">|</span> <span class="dt">Log</span> <span class="dt">Expr</span></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Sin</span> <span class="dt">Expr</span>        <span class="op">|</span> <span class="dt">Cos</span> <span class="dt">Expr</span></span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Range</span> <span class="dt">Expr</span> <span class="dt">Expr</span></span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a>(<span class="op">~</span>) <span class="ot">=</span> <span class="dt">Range</span></span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-12"><a href="#cb9-12" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Num</span> <span class="dt">Expr</span> <span class="kw">where</span></span>
<span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a>  (<span class="op">+</span>) <span class="ot">=</span> <span class="dt">Add</span>; (<span class="op">*</span>) <span class="ot">=</span> <span class="dt">Mul</span></span>
<span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a>  <span class="fu">negate</span> <span class="ot">=</span> <span class="dt">Negate</span>; <span class="fu">abs</span> <span class="ot">=</span> <span class="dt">Abs</span></span>
<span id="cb9-15"><a href="#cb9-15" aria-hidden="true" tabindex="-1"></a>  <span class="fu">signum</span> <span class="ot">=</span> <span class="dt">Signum</span>; <span class="fu">fromInteger</span> <span class="ot">=</span> <span class="dt">Num</span> <span class="op">.</span> <span class="fu">fromInteger</span></span>
<span id="cb9-16"><a href="#cb9-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-17"><a href="#cb9-17" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Fractional</span> <span class="dt">Expr</span> <span class="kw">where</span></span>
<span id="cb9-18"><a href="#cb9-18" aria-hidden="true" tabindex="-1"></a>  (<span class="op">/</span>) <span class="ot">=</span> <span class="dt">Div</span>; <span class="fu">fromRational</span> <span class="ot">=</span> <span class="dt">Num</span> <span class="op">.</span> <span class="fu">fromRational</span></span>
<span id="cb9-19"><a href="#cb9-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-20"><a href="#cb9-20" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Floating</span> <span class="dt">Expr</span> <span class="kw">where</span></span>
<span id="cb9-21"><a href="#cb9-21" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pi</span> <span class="ot">=</span> <span class="dt">Num</span> <span class="fu">pi</span>; <span class="fu">exp</span> <span class="ot">=</span> <span class="dt">Exp</span>; <span class="fu">log</span> <span class="ot">=</span> <span class="dt">Log</span>; <span class="fu">sin</span> <span class="ot">=</span> <span class="dt">Sin</span>; <span class="fu">cos</span> <span class="ot">=</span> <span class="dt">Cos</span></span></code></pre></div>
<p>By defining <code>~</code> to be <code>Range</code> and overloading math we can immediately write</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>1400~1700 * 0.55~0.65 - 600~700</span></code></pre></div>
<p>to mean</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>Add (Mul (Range 1400 1700) (Range 0.55 0.65)) (Negate (Range 600 700)))</span></code></pre></div>
<p>Breathe life into expressions by allowing them to be evaluated to a distribution
that can later be sampled. This is where the <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code>
instances for <code>Dist</code> come into play:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ot">eval ::</span> <span class="dt">Expr</span> <span class="ot">-&gt;</span> <span class="dt">Dist</span> <span class="dt">Double</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>eval e <span class="ot">=</span> <span class="kw">case</span> e <span class="kw">of</span></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Num</span> d       <span class="ot">-&gt;</span> <span class="fu">return</span> d</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Add</span> e1 e2   <span class="ot">-&gt;</span> (<span class="op">+</span>) <span class="op">&lt;$&gt;</span> eval e1 <span class="op">&lt;*&gt;</span> eval e2</span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Mul</span> e1 e2   <span class="ot">-&gt;</span> (<span class="op">*</span>) <span class="op">&lt;$&gt;</span> eval e1 <span class="op">&lt;*&gt;</span> eval e2</span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Negate</span> e    <span class="ot">-&gt;</span> <span class="fu">negate</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Abs</span> e       <span class="ot">-&gt;</span> <span class="fu">abs</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Signum</span> e    <span class="ot">-&gt;</span> <span class="fu">signum</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Div</span> e1 e2   <span class="ot">-&gt;</span> (<span class="op">/</span>) <span class="op">&lt;$&gt;</span> eval e1 <span class="op">&lt;*&gt;</span> eval e2</span>
<span id="cb12-10"><a href="#cb12-10" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Exp</span> e       <span class="ot">-&gt;</span> <span class="fu">exp</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Log</span> e       <span class="ot">-&gt;</span> <span class="fu">log</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-12"><a href="#cb12-12" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Sin</span> e       <span class="ot">-&gt;</span> <span class="fu">sin</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-13"><a href="#cb12-13" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Cos</span> e       <span class="ot">-&gt;</span> <span class="fu">cos</span> <span class="op">&lt;$&gt;</span> eval e</span>
<span id="cb12-14"><a href="#cb12-14" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Range</span> e1 e2 <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb12-15"><a href="#cb12-15" aria-hidden="true" tabindex="-1"></a>    a <span class="ot">&lt;-</span> eval e1</span>
<span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a>    b <span class="ot">&lt;-</span> eval e2</span>
<span id="cb12-17"><a href="#cb12-17" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> mean <span class="ot">=</span> (a <span class="op">+</span> b) <span class="op">/</span> <span class="dv">2</span></span>
<span id="cb12-18"><a href="#cb12-18" aria-hidden="true" tabindex="-1"></a>        std_dev <span class="ot">=</span> (b <span class="op">-</span> a) <span class="op">/</span> <span class="dv">4</span></span>
<span id="cb12-19"><a href="#cb12-19" aria-hidden="true" tabindex="-1"></a>    <span class="dt">Normal</span> mean std_dev</span></code></pre></div>
<p>Most cases just recursively <code>eval</code> the sub-expressions into <code>Dist Double</code>s and
then lift a math operation on <code>Double</code>s into the probability monad.
The interesting case is <code>Range</code>, which uses the evaluated sub-expressions, referring to
the lower and upper range bound, to compute the standard deviation and mean of
the normal distribution – a <code>Dist</code> is returned by applying the “primitive”
<code>Normal</code> constructor accordingly.</p>
<p>We can take a few samples of the first example in this post:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>&gt; take 10 $ sample (mkStdGen 5) $ sequence $ repeat $ eval (1400~1700 * 0.55~0.65 - 600~700 - 100~200 - 30 - 20)</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>[8.808397505000045,-20.049171720836654,12.753715226577157,-22.77067243260501,-70.3671725933005,-11.610935890955716,157.612422580839,75.61254061496092,88.04359089198991,-37.280109436085866]</span></code></pre></div>
<p>Even though we are taking samples from the distribution constructed by that compound expression, we cannot make too much sense of these numbers.
We need to plot them in a histogram, just like the original calculator does, to make this useful.</p>
<h2 data-number="1.3" id="showing-up"><span class="header-section-number">1.3</span> Showing up</h2>
<p>I’ll spare the nitty-gritty details, but, lastly, we define a <code>Show</code> instance
for <code>Expr</code> that plots a number of samples from the distribution resulting from
the given expression. In order:</p>
<ul>
<li>Eval the expression <code>e</code> into a <code>Dist Double</code></li>
<li>Take 25000 samples</li>
<li>Group each sample into the interval it is closest to (in <code>collapseIntervals</code>)</li>
<li>Compute the ratio of samples in each box over the total number of samples, to display as a percentage</li>
<li>For each box, plot a line (in <code>line</code> and <code>showRow</code>)</li>
</ul>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Show</span> <span class="dt">Expr</span> <span class="kw">where</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">show</span> e <span class="ot">=</span> <span class="fu">concatMap</span> showRow intervals <span class="kw">where</span></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>    samples <span class="ot">=</span> <span class="fu">take</span> <span class="dv">25000</span> <span class="op">.</span> sample (mkStdGen <span class="dv">0</span>) <span class="op">.</span> <span class="fu">sequence</span> <span class="op">.</span> <span class="fu">repeat</span> <span class="op">.</span> eval</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a>    intervals <span class="ot">=</span> collapseIntervals <span class="dv">40</span> (samples e)</span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>    line p <span class="ot">=</span> <span class="fu">replicate</span> spaces <span class="ch">&#39; &#39;</span> <span class="op">++</span> <span class="fu">replicate</span> normalized <span class="ch">&#39;:&#39;</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>      <span class="kw">where</span> spaces <span class="ot">=</span> <span class="dv">35</span> <span class="op">-</span> normalized</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a>            normalized <span class="ot">=</span> <span class="fu">round</span> ((p<span class="op">/</span>max_prob) <span class="op">*</span> <span class="dv">30</span>)</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a>            max_prob <span class="ot">=</span> <span class="fu">maximum</span> <span class="op">$</span> <span class="fu">map</span> <span class="fu">snd</span> intervals</span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a>    showRow (<span class="fu">elem</span>, prob) <span class="ot">=</span> line prob <span class="op">++</span> <span class="st">&quot; | &quot;</span> <span class="op">++</span> printf <span class="st">&quot;%.1f (%.1f&quot;</span> <span class="fu">elem</span> (prob<span class="op">*</span><span class="dv">100</span>) <span class="op">++</span> <span class="st">&quot;%)\n&quot;</span></span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a><span class="ot">collapseIntervals ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> [<span class="dt">Double</span>] <span class="ot">-&gt;</span> [(<span class="dt">Double</span>, <span class="dt">Double</span>)]</span>
<span id="cb14-12"><a href="#cb14-12" aria-hidden="true" tabindex="-1"></a>collapseIntervals n (<span class="fu">sort</span> <span class="ot">-&gt;</span> samples) <span class="ot">=</span></span>
<span id="cb14-13"><a href="#cb14-13" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (low, high) <span class="ot">=</span> (<span class="fu">head</span> samples, <span class="fu">last</span> samples)</span>
<span id="cb14-14"><a href="#cb14-14" aria-hidden="true" tabindex="-1"></a>      step  <span class="ot">=</span> (high <span class="op">-</span> low) <span class="op">/</span> <span class="fu">fromIntegral</span> n</span>
<span id="cb14-15"><a href="#cb14-15" aria-hidden="true" tabindex="-1"></a>      boxes <span class="ot">=</span> [low, low<span class="op">+</span>step <span class="op">..</span> high] </span>
<span id="cb14-16"><a href="#cb14-16" aria-hidden="true" tabindex="-1"></a>      total <span class="ot">=</span> <span class="fu">fromIntegral</span> (<span class="fu">length</span> samples)</span>
<span id="cb14-17"><a href="#cb14-17" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> M.toList <span class="op">$</span> M.map (<span class="op">/</span>total) <span class="op">$</span> M.fromListWith (<span class="op">+</span>)</span>
<span id="cb14-18"><a href="#cb14-18" aria-hidden="true" tabindex="-1"></a>        [ (minimumBy (<span class="fu">compare</span> <span class="ot">`on`</span> \box <span class="ot">-&gt;</span> <span class="fu">abs</span> (box <span class="op">-</span> s)) boxes, <span class="dv">1</span>)</span>
<span id="cb14-19"><a href="#cb14-19" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> s <span class="ot">&lt;-</span> samples ]</span></code></pre></div>
<p>Let’s try to print out the first example now, by simply typing in GHCi:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>&gt; 1400~1700 * 0.55~0.65 - 600~700 - 100~200 - 30 - 20</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>                                    | -188.2 (0.0%)</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>                                    | -162.2 (0.0%)</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>                                    | -149.2 (0.0%)</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>                                    | -136.1 (0.1%)</span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a>                                    | -123.1 (0.1%)</span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>                                    | -110.1 (0.1%)</span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>                                  : | -97.1 (0.2%)</span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a>                                 :: | -84.1 (0.4%)</span>
<span id="cb15-11"><a href="#cb15-11" aria-hidden="true" tabindex="-1"></a>                                 :: | -71.1 (0.6%)</span>
<span id="cb15-12"><a href="#cb15-12" aria-hidden="true" tabindex="-1"></a>                               :::: | -58.1 (1.1%)</span>
<span id="cb15-13"><a href="#cb15-13" aria-hidden="true" tabindex="-1"></a>                            ::::::: | -45.1 (1.7%)</span>
<span id="cb15-14"><a href="#cb15-14" aria-hidden="true" tabindex="-1"></a>                            ::::::: | -32.1 (1.8%)</span>
<span id="cb15-15"><a href="#cb15-15" aria-hidden="true" tabindex="-1"></a>                        ::::::::::: | -19.0 (2.9%)</span>
<span id="cb15-16"><a href="#cb15-16" aria-hidden="true" tabindex="-1"></a>                    ::::::::::::::: | -6.0 (3.8%)</span>
<span id="cb15-17"><a href="#cb15-17" aria-hidden="true" tabindex="-1"></a>                  ::::::::::::::::: | 7.0 (4.3%)</span>
<span id="cb15-18"><a href="#cb15-18" aria-hidden="true" tabindex="-1"></a>              ::::::::::::::::::::: | 20.0 (5.3%)</span>
<span id="cb15-19"><a href="#cb15-19" aria-hidden="true" tabindex="-1"></a>          ::::::::::::::::::::::::: | 33.0 (6.1%)</span>
<span id="cb15-20"><a href="#cb15-20" aria-hidden="true" tabindex="-1"></a>        ::::::::::::::::::::::::::: | 46.0 (6.7%)</span>
<span id="cb15-21"><a href="#cb15-21" aria-hidden="true" tabindex="-1"></a>     :::::::::::::::::::::::::::::: | 59.0 (7.4%)</span>
<span id="cb15-22"><a href="#cb15-22" aria-hidden="true" tabindex="-1"></a>     :::::::::::::::::::::::::::::: | 72.0 (7.5%)</span>
<span id="cb15-23"><a href="#cb15-23" aria-hidden="true" tabindex="-1"></a>     :::::::::::::::::::::::::::::: | 85.0 (7.5%)</span>
<span id="cb15-24"><a href="#cb15-24" aria-hidden="true" tabindex="-1"></a>       :::::::::::::::::::::::::::: | 98.0 (7.0%)</span>
<span id="cb15-25"><a href="#cb15-25" aria-hidden="true" tabindex="-1"></a>         :::::::::::::::::::::::::: | 111.1 (6.6%)</span>
<span id="cb15-26"><a href="#cb15-26" aria-hidden="true" tabindex="-1"></a>            ::::::::::::::::::::::: | 124.1 (5.8%)</span>
<span id="cb15-27"><a href="#cb15-27" aria-hidden="true" tabindex="-1"></a>              ::::::::::::::::::::: | 137.1 (5.3%)</span>
<span id="cb15-28"><a href="#cb15-28" aria-hidden="true" tabindex="-1"></a>                  ::::::::::::::::: | 150.1 (4.3%)</span>
<span id="cb15-29"><a href="#cb15-29" aria-hidden="true" tabindex="-1"></a>                      ::::::::::::: | 163.1 (3.3%)</span>
<span id="cb15-30"><a href="#cb15-30" aria-hidden="true" tabindex="-1"></a>                       :::::::::::: | 176.1 (2.9%)</span>
<span id="cb15-31"><a href="#cb15-31" aria-hidden="true" tabindex="-1"></a>                          ::::::::: | 189.1 (2.2%)</span>
<span id="cb15-32"><a href="#cb15-32" aria-hidden="true" tabindex="-1"></a>                            ::::::: | 202.1 (1.7%)</span>
<span id="cb15-33"><a href="#cb15-33" aria-hidden="true" tabindex="-1"></a>                              ::::: | 215.1 (1.2%)</span>
<span id="cb15-34"><a href="#cb15-34" aria-hidden="true" tabindex="-1"></a>                                ::: | 228.2 (0.8%)</span>
<span id="cb15-35"><a href="#cb15-35" aria-hidden="true" tabindex="-1"></a>                                 :: | 241.2 (0.6%)</span>
<span id="cb15-36"><a href="#cb15-36" aria-hidden="true" tabindex="-1"></a>                                  : | 254.2 (0.3%)</span>
<span id="cb15-37"><a href="#cb15-37" aria-hidden="true" tabindex="-1"></a>                                  : | 267.2 (0.2%)</span>
<span id="cb15-38"><a href="#cb15-38" aria-hidden="true" tabindex="-1"></a>                                    | 280.2 (0.1%)</span>
<span id="cb15-39"><a href="#cb15-39" aria-hidden="true" tabindex="-1"></a>                                    | 293.2 (0.0%)</span>
<span id="cb15-40"><a href="#cb15-40" aria-hidden="true" tabindex="-1"></a>                                    | 306.2 (0.0%)</span>
<span id="cb15-41"><a href="#cb15-41" aria-hidden="true" tabindex="-1"></a>                                    | 319.2 (0.0%)</span>
<span id="cb15-42"><a href="#cb15-42" aria-hidden="true" tabindex="-1"></a>                                    | 332.2 (0.0%)</span></code></pre></div>
<p>Success! This looks very similar to the original histogram for the same expression.
Let’s also try Drake’s equation as described in the original article:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>&gt; 1.5~3 * 0.9~1.0 * 0.1~0.4 * 0.1~1.0 * 0.1~1.0 * 0.1~0.2 * 304~10000</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>                                    | -307.0 (0.0%)</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>                                    | -193.4 (0.0%)</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>                                    | -155.5 (0.0%)</span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>                                    | -117.7 (0.0%)</span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a>                                    | -79.8 (0.1%)</span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a>                                  : | -42.0 (0.6%)</span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a>                       :::::::::::: | -4.1 (8.3%)</span>
<span id="cb16-10"><a href="#cb16-10" aria-hidden="true" tabindex="-1"></a>     :::::::::::::::::::::::::::::: | 33.7 (20.9%)</span>
<span id="cb16-11"><a href="#cb16-11" aria-hidden="true" tabindex="-1"></a>        ::::::::::::::::::::::::::: | 71.6 (19.1%)</span>
<span id="cb16-12"><a href="#cb16-12" aria-hidden="true" tabindex="-1"></a>              ::::::::::::::::::::: | 109.4 (14.6%)</span>
<span id="cb16-13"><a href="#cb16-13" aria-hidden="true" tabindex="-1"></a>                    ::::::::::::::: | 147.3 (10.5%)</span>
<span id="cb16-14"><a href="#cb16-14" aria-hidden="true" tabindex="-1"></a>                        ::::::::::: | 185.2 (7.4%)</span>
<span id="cb16-15"><a href="#cb16-15" aria-hidden="true" tabindex="-1"></a>                           :::::::: | 223.0 (5.3%)</span>
<span id="cb16-16"><a href="#cb16-16" aria-hidden="true" tabindex="-1"></a>                              ::::: | 260.9 (3.6%)</span>
<span id="cb16-17"><a href="#cb16-17" aria-hidden="true" tabindex="-1"></a>                               :::: | 298.7 (2.6%)</span>
<span id="cb16-18"><a href="#cb16-18" aria-hidden="true" tabindex="-1"></a>                                ::: | 336.6 (1.9%)</span>
<span id="cb16-19"><a href="#cb16-19" aria-hidden="true" tabindex="-1"></a>                                 :: | 374.4 (1.4%)</span>
<span id="cb16-20"><a href="#cb16-20" aria-hidden="true" tabindex="-1"></a>                                  : | 412.3 (0.9%)</span>
<span id="cb16-21"><a href="#cb16-21" aria-hidden="true" tabindex="-1"></a>                                  : | 450.1 (0.7%)</span>
<span id="cb16-22"><a href="#cb16-22" aria-hidden="true" tabindex="-1"></a>                                  : | 488.0 (0.5%)</span>
<span id="cb16-23"><a href="#cb16-23" aria-hidden="true" tabindex="-1"></a>                                    | 525.9 (0.3%)</span>
<span id="cb16-24"><a href="#cb16-24" aria-hidden="true" tabindex="-1"></a>                                    | 563.7 (0.3%)</span>
<span id="cb16-25"><a href="#cb16-25" aria-hidden="true" tabindex="-1"></a>                                    | 601.6 (0.2%)</span>
<span id="cb16-26"><a href="#cb16-26" aria-hidden="true" tabindex="-1"></a>                                    | 639.4 (0.1%)</span>
<span id="cb16-27"><a href="#cb16-27" aria-hidden="true" tabindex="-1"></a>                                    | 677.3 (0.1%)</span>
<span id="cb16-28"><a href="#cb16-28" aria-hidden="true" tabindex="-1"></a>                                    | 715.1 (0.1%)</span>
<span id="cb16-29"><a href="#cb16-29" aria-hidden="true" tabindex="-1"></a>                                    | 753.0 (0.1%)</span>
<span id="cb16-30"><a href="#cb16-30" aria-hidden="true" tabindex="-1"></a>                                    | 790.8 (0.0%)</span>
<span id="cb16-31"><a href="#cb16-31" aria-hidden="true" tabindex="-1"></a>                                    | 828.7 (0.0%)</span>
<span id="cb16-32"><a href="#cb16-32" aria-hidden="true" tabindex="-1"></a>                                    | 866.5 (0.0%)</span>
<span id="cb16-33"><a href="#cb16-33" aria-hidden="true" tabindex="-1"></a>                                    | 904.4 (0.0%)</span>
<span id="cb16-34"><a href="#cb16-34" aria-hidden="true" tabindex="-1"></a>                                    | 942.3 (0.0%)</span>
<span id="cb16-35"><a href="#cb16-35" aria-hidden="true" tabindex="-1"></a>                                    | 980.1 (0.0%)</span>
<span id="cb16-36"><a href="#cb16-36" aria-hidden="true" tabindex="-1"></a>                                    | 1018.0 (0.0%)</span>
<span id="cb16-37"><a href="#cb16-37" aria-hidden="true" tabindex="-1"></a>                                    | 1055.8 (0.0%)</span>
<span id="cb16-38"><a href="#cb16-38" aria-hidden="true" tabindex="-1"></a>                                    | 1093.7 (0.0%)</span>
<span id="cb16-39"><a href="#cb16-39" aria-hidden="true" tabindex="-1"></a>                                    | 1169.4 (0.0%)</span>
<span id="cb16-40"><a href="#cb16-40" aria-hidden="true" tabindex="-1"></a>                                    | 1207.2 (0.0%)</span></code></pre></div>
<p>That’s it!</p>
<h2 data-number="1.4" id="conclusion"><span class="header-section-number">1.4</span> Conclusion</h2>
<p>A few final remarks:</p>
<ul>
<li>This is a neat and simple implementation. It highlights some of Haskell’s strengths in an interesting task.</li>
<li>Since our calculator implementation is embeded in Haskell, we
can leverage the GHCi REPL – most importantly, we can do variable binding and
define functions with no additional implementation cost.</li>
<li>You can try the <a href="https://gist.github.com/alt-romes/58346dee164a91ddab48c5a111d1b5ea">full program</a> (exactly 100 lines) on your machine by loading it with <code>cabal repl &lt;file.hs&gt;</code> and typing unsure expressions at will.</li>
</ul>
<!--- This could almost certainly use a closed form implementation -->
<!--- It'd be good to not display too many 0.0% boxes -->
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>More precisely, the range denotes a normal distribution where each end is two standard deviations from the mean.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2"><p><a href="https://mlg.eng.cam.ac.uk/pub/pdf/SciGhaGor15.pdf">Practical Probabilistic Programming with Monads</a>.
Our version is much simpler than the paper’s because we don’t care about
conditional probabilities and because we only ever use normal distributions.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
]]></summary>
</entry>
<entry>
    <title>Planning Weekly Workouts in 100 lines of Haskell</title>
    <link href="http://alt-romes.github.io/posts/2024-08-14-planning-a-workout-week-with-100-lines-of-haskell.html" />
    <id>http://alt-romes.github.io/posts/2024-08-14-planning-a-workout-week-with-100-lines-of-haskell.html</id>
    <published>2024-08-14T00:00:00Z</published>
    <updated>2024-08-14T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#a-workout-planner-in-100-lines-of-haskell" id="toc-a-workout-planner-in-100-lines-of-haskell"><span class="toc-section-number">1</span> A workout planner in 100 lines of Haskell</a></li>
</ul>
</div>
<p>I have recently started doing some outdoors bodyweight workouts.
I also want to start running again, but I’m recovering from a minor knee injury
until the start of next month.</p>
<p>Tonight I decided to put together a weekly schedule to start following next
month. The first pen and paper versions were fine, but I wasn’t completely
satisfied. The next logical step was to write a quick program to see what
possible plans I was missing.</p>
<p>The schedule must satisfy a few constraints, but the core of it is that I should
do, every week, on one axis, one <em>short run</em> (high-intensity) and one <em>long run</em>
(long distance), and, on the other axis, have two <em>pull days</em> (as in pull-ups),
two <em>push days</em> (as in push-ups), and two <em>leg days</em> (as in squats).</p>
<p>Finding a weekly workout that satisfies certain constraints is an
answer-set-programming kind of problem, best solved by some kind of logic
programming. Rather than turning to Prolog or
<a href="https://potassco.org/clingo/">Clingo</a>, I decided to just stick to Haskell and
use the logic-programming monad from <a href="https://hackage.haskell.org/package/logict">logict</a>!</p>
<h1 data-number="1" id="a-workout-planner-in-100-lines-of-haskell"><span class="header-section-number">1</span> A workout planner in 100 lines of Haskell</h1>
<p>What follows is mostly just the demonstration of using <code>logict</code> applied to this
particular problem. I believe the <code>weeklySchedule</code> function can be easily understood
in general, even by anyone unfamiliar with Haskell and/or logic programming –
and that’s the meat of this short post and program.</p>
<p>Note that the program is a
<a href="https://cabal.readthedocs.io/en/latest/index.html">cabal</a> shell script which
can be run by executing the script file (as in <code>./ScheduleExercise</code>, as long as
<code>cabal</code> is in path). It is standalone, and exactly 100 lines (with comments,
shebangs and everything). Feel free to try and modify it!</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#!/usr/bin/env cabal</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="co">{- cabal:</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="co">build-depends: base, logict</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="co">-}</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Control.Applicative</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Control.Monad</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Control.Monad.Logic</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Data.List</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Data.Maybe</span></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a>workout <span class="ot">=</span> [<span class="st">&quot;Push day&quot;</span>, <span class="st">&quot;Pull day&quot;</span>, <span class="st">&quot;Leg day&quot;</span>, <span class="st">&quot;No workout&quot;</span>]</span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>running <span class="ot">=</span> [<span class="st">&quot;Long run&quot;</span>, <span class="st">&quot;Short run&quot;</span>, <span class="st">&quot;No run&quot;</span>]</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>weekdays <span class="ot">=</span> [<span class="st">&quot;Seg.&quot;</span>, <span class="st">&quot;Ter.&quot;</span>, <span class="st">&quot;Qua.&quot;</span>, <span class="st">&quot;Qui.&quot;</span>, <span class="st">&quot;Sex.&quot;</span>, <span class="st">&quot;Sab.&quot;</span>, <span class="st">&quot;Dom.&quot;</span>]</span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a><span class="ot">weeklySchedule ::</span> <span class="dt">Logic</span> [(<span class="dt">String</span>, [<span class="dt">String</span>])]</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a>weeklySchedule <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- For every weekday, pick an element from `workout` and one from `running`</span></span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- that satisfy the &quot;nested&quot; conditions</span></span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a>  p <span class="ot">&lt;-</span> forM weekdays <span class="op">$</span> \d <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a>    w <span class="ot">&lt;-</span> choose workout</span>
<span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a>    r <span class="ot">&lt;-</span> choose running</span>
<span id="cb1-23"><a href="#cb1-23" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-24"><a href="#cb1-24" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- No running on leg day</span></span>
<span id="cb1-25"><a href="#cb1-25" aria-hidden="true" tabindex="-1"></a>    w <span class="op">==</span> <span class="st">&quot;Leg day&quot;</span> <span class="op">==&gt;</span> r <span class="op">==</span> <span class="st">&quot;No run&quot;</span></span>
<span id="cb1-26"><a href="#cb1-26" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-27"><a href="#cb1-27" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Short intervals run is after an outdoor pull/push workout</span></span>
<span id="cb1-28"><a href="#cb1-28" aria-hidden="true" tabindex="-1"></a>    r <span class="op">==</span> <span class="st">&quot;Short run&quot;</span> <span class="op">==&gt;</span> w <span class="op">/=</span> <span class="st">&quot;No workout&quot;</span></span>
<span id="cb1-29"><a href="#cb1-29" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-30"><a href="#cb1-30" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Workout on Monday outdoors always, not legs</span></span>
<span id="cb1-31"><a href="#cb1-31" aria-hidden="true" tabindex="-1"></a>    d <span class="op">==</span> <span class="st">&quot;Seg.&quot;</span> <span class="op">==&gt;</span> w <span class="op">/=</span> <span class="st">&quot;No workout&quot;</span></span>
<span id="cb1-32"><a href="#cb1-32" aria-hidden="true" tabindex="-1"></a>    d <span class="op">==</span> <span class="st">&quot;Seg.&quot;</span> <span class="op">==&gt;</span> w <span class="op">/=</span> <span class="st">&quot;Leg day&quot;</span></span>
<span id="cb1-33"><a href="#cb1-33" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-34"><a href="#cb1-34" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Pull day during the week?</span></span>
<span id="cb1-35"><a href="#cb1-35" aria-hidden="true" tabindex="-1"></a>    w <span class="op">==</span> <span class="st">&quot;Pull day&quot;</span> <span class="op">==&gt;</span> (d <span class="op">/=</span> <span class="st">&quot;Sab.&quot;</span> <span class="op">&amp;&amp;</span> d <span class="op">/=</span> <span class="st">&quot;Dom.&quot;</span>)</span>
<span id="cb1-36"><a href="#cb1-36" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-37"><a href="#cb1-37" aria-hidden="true" tabindex="-1"></a>    <span class="fu">pure</span> [w,r]</span>
<span id="cb1-38"><a href="#cb1-38" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-39"><a href="#cb1-39" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Now, pick the set `p` of (weekdays X exercises) that satisfy the following conditions:</span></span>
<span id="cb1-40"><a href="#cb1-40" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-41"><a href="#cb1-41" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- One long run, one short run</span></span>
<span id="cb1-42"><a href="#cb1-42" aria-hidden="true" tabindex="-1"></a>  exactly <span class="dv">1</span> <span class="st">&quot;Long run&quot;</span> p</span>
<span id="cb1-43"><a href="#cb1-43" aria-hidden="true" tabindex="-1"></a>  exactly <span class="dv">1</span> <span class="st">&quot;Short run&quot;</span> p</span>
<span id="cb1-44"><a href="#cb1-44" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-45"><a href="#cb1-45" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Two push, two pull, two leg</span></span>
<span id="cb1-46"><a href="#cb1-46" aria-hidden="true" tabindex="-1"></a>  exactly <span class="dv">2</span> <span class="st">&quot;Push day&quot;</span> p</span>
<span id="cb1-47"><a href="#cb1-47" aria-hidden="true" tabindex="-1"></a>  exactly <span class="dv">2</span> <span class="st">&quot;Pull day&quot;</span> p</span>
<span id="cb1-48"><a href="#cb1-48" aria-hidden="true" tabindex="-1"></a>  exactly <span class="dv">2</span> <span class="st">&quot;Leg day&quot;</span> p</span>
<span id="cb1-49"><a href="#cb1-49" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-50"><a href="#cb1-50" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Long run on weekend</span></span>
<span id="cb1-51"><a href="#cb1-51" aria-hidden="true" tabindex="-1"></a>  onDay <span class="st">&quot;Long run&quot;</span> <span class="st">&quot;Sab.&quot;</span> p <span class="op">&lt;|&gt;</span> onDay <span class="st">&quot;Long run&quot;</span> <span class="st">&quot;Dom.&quot;</span> p</span>
<span id="cb1-52"><a href="#cb1-52" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-53"><a href="#cb1-53" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Run spaced out at least 2 days</span></span>
<span id="cb1-54"><a href="#cb1-54" aria-hidden="true" tabindex="-1"></a>  daysBetween <span class="dv">2</span> <span class="st">&quot;Short run&quot;</span> <span class="st">&quot;Long run&quot;</span> p</span>
<span id="cb1-55"><a href="#cb1-55" aria-hidden="true" tabindex="-1"></a>  daysBetween <span class="dv">2</span> <span class="st">&quot;Long run&quot;</span> <span class="st">&quot;Short run&quot;</span> p</span>
<span id="cb1-56"><a href="#cb1-56" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-57"><a href="#cb1-57" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Space out workouts at least 2 days</span></span>
<span id="cb1-58"><a href="#cb1-58" aria-hidden="true" tabindex="-1"></a>  spacedOut <span class="st">&quot;Push day&quot;</span> <span class="dv">2</span> p</span>
<span id="cb1-59"><a href="#cb1-59" aria-hidden="true" tabindex="-1"></a>  spacedOut <span class="st">&quot;Pull day&quot;</span> <span class="dv">2</span> p</span>
<span id="cb1-60"><a href="#cb1-60" aria-hidden="true" tabindex="-1"></a>  spacedOut <span class="st">&quot;Leg day&quot;</span> <span class="dv">2</span> p</span>
<span id="cb1-61"><a href="#cb1-61" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-62"><a href="#cb1-62" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- No leg day before short run</span></span>
<span id="cb1-63"><a href="#cb1-63" aria-hidden="true" tabindex="-1"></a>  daysBetween <span class="dv">1</span> <span class="st">&quot;Leg day&quot;</span> <span class="st">&quot;Short run&quot;</span> p</span>
<span id="cb1-64"><a href="#cb1-64" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- No leg day before a long run</span></span>
<span id="cb1-65"><a href="#cb1-65" aria-hidden="true" tabindex="-1"></a>  daysBetween <span class="dv">1</span> <span class="st">&quot;Leg day&quot;</span> <span class="st">&quot;Long run&quot;</span>  p</span>
<span id="cb1-66"><a href="#cb1-66" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-67"><a href="#cb1-67" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- At least one of the runs without a leg day after please</span></span>
<span id="cb1-68"><a href="#cb1-68" aria-hidden="true" tabindex="-1"></a>  daysBetween <span class="dv">1</span> <span class="st">&quot;Short run&quot;</span> <span class="st">&quot;Leg day&quot;</span> p <span class="op">&lt;|&gt;</span> daysBetween <span class="dv">1</span> <span class="st">&quot;Long run&quot;</span> <span class="st">&quot;Leg day&quot;</span> p</span>
<span id="cb1-69"><a href="#cb1-69" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-70"><a href="#cb1-70" aria-hidden="true" tabindex="-1"></a>  <span class="fu">return</span> (<span class="fu">zip</span> weekdays p)</span>
<span id="cb1-71"><a href="#cb1-71" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-72"><a href="#cb1-72" aria-hidden="true" tabindex="-1"></a><span class="co">--------------------------------------------------------------------------------</span></span>
<span id="cb1-73"><a href="#cb1-73" aria-hidden="true" tabindex="-1"></a><span class="co">-- Logic utils</span></span>
<span id="cb1-74"><a href="#cb1-74" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-75"><a href="#cb1-75" aria-hidden="true" tabindex="-1"></a>choose <span class="ot">=</span> <span class="fu">foldr</span> ((<span class="op">&lt;|&gt;</span>) <span class="op">.</span> <span class="fu">pure</span>) empty</span>
<span id="cb1-76"><a href="#cb1-76" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-77"><a href="#cb1-77" aria-hidden="true" tabindex="-1"></a>exactly n s p <span class="ot">=</span> guard (<span class="fu">length</span> (<span class="fu">filter</span> (s <span class="ot">`elem`</span>) p) <span class="op">==</span> n)</span>
<span id="cb1-78"><a href="#cb1-78" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-79"><a href="#cb1-79" aria-hidden="true" tabindex="-1"></a>onDay s d p <span class="ot">=</span> guard (s <span class="ot">`elem`</span> getDay d p) <span class="kw">where</span></span>
<span id="cb1-80"><a href="#cb1-80" aria-hidden="true" tabindex="-1"></a>  getDay s p <span class="ot">=</span> p <span class="op">!!</span> fromMaybe <span class="fu">undefined</span> (elemIndex s weekdays)</span>
<span id="cb1-81"><a href="#cb1-81" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-82"><a href="#cb1-82" aria-hidden="true" tabindex="-1"></a><span class="co">-- space out as at least n days</span></span>
<span id="cb1-83"><a href="#cb1-83" aria-hidden="true" tabindex="-1"></a>spacedOut a n p <span class="ot">=</span> guard (<span class="fu">all</span> (<span class="op">&gt;</span>n) dists) <span class="kw">where</span></span>
<span id="cb1-84"><a href="#cb1-84" aria-hidden="true" tabindex="-1"></a>  dists <span class="ot">=</span> <span class="fu">zipWith</span> (<span class="op">-</span>) (<span class="fu">drop</span> <span class="dv">1</span> is) is</span>
<span id="cb1-85"><a href="#cb1-85" aria-hidden="true" tabindex="-1"></a>  is <span class="ot">=</span> findIndices (a <span class="ot">`elem`</span>) (<span class="fu">take</span> <span class="dv">14</span> <span class="op">$</span> <span class="fu">cycle</span> p <span class="co">{- cycle week around -}</span>)</span>
<span id="cb1-86"><a href="#cb1-86" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-87"><a href="#cb1-87" aria-hidden="true" tabindex="-1"></a>daysBetween n a b p <span class="ot">=</span></span>
<span id="cb1-88"><a href="#cb1-88" aria-hidden="true" tabindex="-1"></a>  forM_ (<span class="fu">take</span> <span class="dv">14</span> (<span class="fu">cycle</span> p) <span class="ot">`zip`</span> [<span class="dv">1</span><span class="op">..</span>]) <span class="op">$</span> \(x,i) <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb1-89"><a href="#cb1-89" aria-hidden="true" tabindex="-1"></a>    a <span class="ot">`elem`</span> x <span class="op">==&gt;</span> <span class="fu">all</span> (b <span class="ot">`notElem`</span>) (<span class="fu">take</span> n <span class="op">$</span> <span class="fu">drop</span> i (<span class="fu">take</span> <span class="dv">14</span> (<span class="fu">cycle</span> p)))</span>
<span id="cb1-90"><a href="#cb1-90" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-91"><a href="#cb1-91" aria-hidden="true" tabindex="-1"></a>(<span class="op">==&gt;</span>) a b <span class="ot">=</span> guard (<span class="fu">not</span> a <span class="op">||</span> b)</span>
<span id="cb1-92"><a href="#cb1-92" aria-hidden="true" tabindex="-1"></a><span class="kw">infixr</span> <span class="dv">0</span> <span class="op">==&gt;</span></span>
<span id="cb1-93"><a href="#cb1-93" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-94"><a href="#cb1-94" aria-hidden="true" tabindex="-1"></a><span class="co">--------------------------------------------------------------------------------</span></span>
<span id="cb1-95"><a href="#cb1-95" aria-hidden="true" tabindex="-1"></a><span class="co">-- Main</span></span>
<span id="cb1-96"><a href="#cb1-96" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-97"><a href="#cb1-97" aria-hidden="true" tabindex="-1"></a>printSched <span class="ot">=</span> <span class="fu">mapM</span> (\(d, ls) <span class="ot">-&gt;</span> <span class="fu">putStrLn</span> (d <span class="op">++</span> <span class="st">&quot; &quot;</span> <span class="op">++</span> intercalate <span class="st">&quot;, &quot;</span> ls))</span>
<span id="cb1-98"><a href="#cb1-98" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-99"><a href="#cb1-99" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span> <span class="kw">do</span> <span class="kw">let</span> r <span class="ot">=</span> observeAll weeklySchedule</span>
<span id="cb1-100"><a href="#cb1-100" aria-hidden="true" tabindex="-1"></a>          <span class="fu">mapM</span> (<span class="fu">const</span> (<span class="fu">putStrLn</span> <span class="st">&quot;&quot;</span>) <span class="op">&lt;=&lt;</span> printSched) r</span></code></pre></div>
<p>The heavy lifting is done by the <a href="https://hackage.haskell.org/package/logict"><code>logict</code></a> package.
It allows us to consider alternative values as solutions to logic statements.
The possible alternatives are separated by <code>&lt;|&gt;</code>, and <code>observeAll</code> returns
a list with all valid alternatives. A trivial example:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>x <span class="ot">=</span> <span class="fu">pure</span> <span class="st">&quot;a&quot;</span> <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;b&quot;</span> <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;c&quot;</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="fu">print</span> (observeAll x)</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="dt">Result</span><span class="op">:</span> [<span class="st">&quot;a&quot;</span>, <span class="st">&quot;b&quot;</span>, <span class="st">&quot;c&quot;</span>]</span></code></pre></div>
<p>If the alternative is <code>empty</code>, it is not an answer and therefore not included in the result.
The <code>guard</code> combinator takes a boolean and returns <code>empty</code> if it is false,
therefore constraining the solution.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>x <span class="ot">=</span> <span class="fu">pure</span> <span class="st">&quot;a&quot;</span> <span class="op">&lt;|&gt;</span> empty <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;c&quot;</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="fu">print</span> (observeAll x)</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="dt">Result</span><span class="op">:</span> [<span class="st">&quot;a&quot;</span>, <span class="st">&quot;c&quot;</span>]</span></code></pre></div>
<p>Finally, we can use the monadic <code>do</code> notation to combine sets of alternatives.
Put together with <code>guard</code>, we can write slightly more interesting programs:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>x <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>  y <span class="ot">&lt;-</span> <span class="fu">pure</span> <span class="st">&quot;a&quot;</span> <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;b&quot;</span> <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;c&quot;</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  z <span class="ot">&lt;-</span> <span class="fu">pure</span> <span class="st">&quot;a&quot;</span> <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;b&quot;</span> <span class="op">&lt;|&gt;</span> <span class="fu">pure</span> <span class="st">&quot;c&quot;</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  guard (y <span class="op">/=</span> z)</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>  <span class="fu">return</span> (y,z)</span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="fu">print</span> (observeAll x)</span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a><span class="dt">Result</span><span class="op">:</span> [(<span class="st">&quot;a&quot;</span>,<span class="st">&quot;b&quot;</span>),(<span class="st">&quot;a&quot;</span>,<span class="st">&quot;c&quot;</span>),(<span class="st">&quot;b&quot;</span>,<span class="st">&quot;a&quot;</span>),(<span class="st">&quot;b&quot;</span>,<span class="st">&quot;c&quot;</span>),(<span class="st">&quot;c&quot;</span>,<span class="st">&quot;a&quot;</span>),(<span class="st">&quot;c&quot;</span>,<span class="st">&quot;b&quot;</span>)]</span></code></pre></div>
<p>All in all, the body of <code>weeklySchedule</code> uses just these principles plus a few
domain-specific combinators I wrote in the <code>Logic utils</code> section of the code
(which themselves use also only these principles from <code>logict</code>, plus some
laziness-coolness). The program entry point (<code>main</code>) prints out the
schedule.</p>
<p>And by the way, these are the workout schedules satisfying all those constraints:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>Seg. Pull day, No run</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>Ter. Push day, Short run</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>Qua. No workout, No run</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>Qui. Leg day, No run</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>Sex. Pull day, No run</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>Sab. Push day, Long run</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>Dom. Leg day, No run</span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a>Seg. Pull day, No run</span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a>Ter. Leg day, No run</span>
<span id="cb5-11"><a href="#cb5-11" aria-hidden="true" tabindex="-1"></a>Qua. Push day, No run</span>
<span id="cb5-12"><a href="#cb5-12" aria-hidden="true" tabindex="-1"></a>Qui. Pull day, Short run</span>
<span id="cb5-13"><a href="#cb5-13" aria-hidden="true" tabindex="-1"></a>Sex. Leg day, No run</span>
<span id="cb5-14"><a href="#cb5-14" aria-hidden="true" tabindex="-1"></a>Sab. Push day, No run</span>
<span id="cb5-15"><a href="#cb5-15" aria-hidden="true" tabindex="-1"></a>Dom. No workout, Long run</span>
<span id="cb5-16"><a href="#cb5-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-17"><a href="#cb5-17" aria-hidden="true" tabindex="-1"></a>Seg. Pull day, No run</span>
<span id="cb5-18"><a href="#cb5-18" aria-hidden="true" tabindex="-1"></a>Ter. Leg day, No run</span>
<span id="cb5-19"><a href="#cb5-19" aria-hidden="true" tabindex="-1"></a>Qua. Push day, No run</span>
<span id="cb5-20"><a href="#cb5-20" aria-hidden="true" tabindex="-1"></a>Qui. Pull day, Short run</span>
<span id="cb5-21"><a href="#cb5-21" aria-hidden="true" tabindex="-1"></a>Sex. Leg day, No run</span>
<span id="cb5-22"><a href="#cb5-22" aria-hidden="true" tabindex="-1"></a>Sab. No workout, No run</span>
<span id="cb5-23"><a href="#cb5-23" aria-hidden="true" tabindex="-1"></a>Dom. Push day, Long run</span></code></pre></div>
]]></summary>
</entry>
<entry>
    <title>Calling Haskell from Swift</title>
    <link href="http://alt-romes.github.io/posts/2024-04-02-calling-haskell-from-swift.html" />
    <id>http://alt-romes.github.io/posts/2024-04-02-calling-haskell-from-swift.html</id>
    <published>2024-04-02T00:00:00Z</published>
    <updated>2024-04-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#introduction" id="toc-introduction"><span class="toc-section-number">1</span> Introduction</a></li>
<li><a href="#marshaling-inputs-and-outputs" id="toc-marshaling-inputs-and-outputs"><span class="toc-section-number">2</span> Marshaling Inputs and Outputs</a>
<ul>
<li><a href="#haskells-perspective" id="toc-haskells-perspective"><span class="toc-section-number">2.1</span> Haskell’s Perspective</a></li>
<li><a href="#swifts-perspective" id="toc-swifts-perspective"><span class="toc-section-number">2.2</span> Swift’s Perspective</a></li>
</ul></li>
<li><a href="#metaprogramming-at-the-boundaries" id="toc-metaprogramming-at-the-boundaries"><span class="toc-section-number">3</span> Metaprogramming at the boundaries</a>
<ul>
<li><a href="#haskells-perspective-1" id="toc-haskells-perspective-1"><span class="toc-section-number">3.1</span> Haskell’s perspective</a></li>
<li><a href="#swifts-perspective-1" id="toc-swifts-perspective-1"><span class="toc-section-number">3.2</span> Swift’s perspective</a></li>
</ul></li>
<li><a href="#remarks" id="toc-remarks"><span class="toc-section-number">4</span> Remarks</a></li>
</ul>
</div>
<p>This is the second installment of the in-depth series of blog-posts on
developing native macOS and iOS applications using both Haskell and
Swift/SwiftUI. This post covers how to call (non-trivial) Haskell functions from
Swift by using a foreign function calling-convention strategy similar to that
described by <a href="https://well-typed.com/blog/2023/03/purgatory/">Calling Purgatory from Heaven: Binding to Rust in
Haskell</a> that requires argument
and result marshaling.</p>
<p>You may find the other blog posts in this series interesting:</p>
<ol type="1">
<li><a href="2023-11-10-creating-a-macos-app-with-haskell-and-swift.html">Creating a macOS app with Haskell and Swift</a></li>
</ol>
<p>The series of blog posts is further accompanied by a <a href="https://github.com/alt-romes/haskell-x-swift-project-steps">github
repository</a> where
each commit matches a step of this tutorial. If in doubt regarding any step,
check the matching commit to make it clearer.</p>
<p>This write-up has been cross-posted to <a href="https://well-typed.com/blog/">Well-Typed’s Blog</a>.</p>
<h1 data-number="1" id="introduction"><span class="header-section-number">1</span> Introduction</h1>
<p>We’ll pick up from where the last post ended – we have set up an XCode project
that includes our headers generated from Haskell modules with <code>foreign export</code>s
and linking against the foreign library declared in the cabal file. We have
already been able to call a very simple Haskell function on integers from Swift
via Haskell’s C foreign export feature and Swift’s C interoperability.</p>
<p>This part concerns itself with calling idiomatic Haskell functions, which
typically involve user-defined datatypes as inputs and outputs, from Swift.
Moreover, these functions should be made available to Swift transparently, such
that Swift calls them as it does other idiomatic functions, with user defined
structs and classes.</p>
<p>For the running example, the following not-very-interesting function will
suffice to showcase the method we will use to expose this function from Haskell
to Swift, which easily scales to other complex data types and functions.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">User</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">User</span> {<span class="ot"> name ::</span> <span class="dt">String</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>         ,<span class="ot"> age  ::</span> <span class="dt">Int</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>         }</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="ot">birthday ::</span> <span class="dt">User</span> <span class="ot">-&gt;</span> <span class="dt">User</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>birthday user <span class="ot">=</span> user{age <span class="ot">=</span> user<span class="op">.</span>age <span class="op">+</span> <span class="dv">1</span>}</span></code></pre></div>
<p>The Swift side should wrap Haskell’s <code>birthday</code>:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> User <span class="op">{</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">name</span><span class="op">:</span> String</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">age</span><span class="op">:</span> Int</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="co">// birthday(user: User(name: &quot;Anton&quot;, age: 33)) = User(name: &quot;Anton&quot;, age: 34)</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a><span class="kw">func</span> <span class="fu">birthday</span><span class="op">(</span><span class="va">user</span><span class="op">:</span> <span class="dt">User</span><span class="op">)</span> -&gt; <span class="fu">User</span> <span class="op">{</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>    <span class="co">// Calls Haskell function...</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>To support this workflow, we need a way to <strong>convert the User datatype from
Haskell to Swift</strong>, and vice versa. We are going to <strong>serialize (most) inputs
and outputs</strong> of a function. Even though the serialization as it will be
described may seem complex, it can be automated with Template Haskell and Swift
Macros and packed into a neat interface – which I’ve done in
<a href="https://github.com/alt-romes/haskell-swift">haskell-swift</a>.</p>
<!-- -- though, in a follow up post, I will also dive a -->
<!-- bit into coercing in-memory representations of a datatype in between Haskell and -->
<!-- Swift -- which, unlike serializing the datatypes, is very fragile, but -->
<!-- educational. -->
<p>As a preliminary step, we add the <code>User</code> data type and <code>birthday</code> function to
<code>haskell-framework/src/MyLib.hs</code>, and the Swift equivalents to
<code>SwiftHaskell/ContentView.swift</code> from the <a href="https://github.com/alt-romes/haskell-x-swift-project-steps"><code>haskell-x-swift-project-steps</code></a> example project.</p>
<h1 data-number="2" id="marshaling-inputs-and-outputs"><span class="header-section-number">2</span> Marshaling Inputs and Outputs</h1>
<p>Marshaling the inputs and outputs of a function, from the Swift perspective,
means to serialize the input values into strings, and receive the output value as
a string which is then decoded into a Swift value. The Haskell perspective is
dual.</p>
<p>Marshaling/serializing is a very robust solution to foreign language interoperability.
While there is a small overhead of encoding and decoding at a function call, it
almost automatically extends to, and enables, all sorts of data to be
transported across the language boundary, without it being vulnerable to
compiler implementation details and memory representation incompatibilities.</p>
<p>We will use the same marshaling strategy that <a href="https://well-typed.com/blog/2023/03/purgatory">Calling Purgatory from Heaven: Binding to Rust in Haskell</a> does.
In short, the idiomatic Haskell function is wrapped by a low-level one which
deserializes the Haskell values from the argument buffers, and serializes the
function result to a buffer that the caller provides. More specifically,</p>
<ul>
<li><p>For each argument of the original function, we have a <code>Ptr CChar</code> and <code>Int</code> – a string of characters and the size of that string (a.k.a <code>CStringLen</code>)</p></li>
<li><p>For the result of the original function, we have two additional arguments, <code>Ptr CChar</code> and <code>Ptr Int</code> –
an empty buffer in memory, and a pointer to the size of that buffer, both allocated by the caller.</p></li>
<li><p>For each argument, we parse the C string into a Haskell value that serves as an argument to the original function.</p></li>
<li><p>We call the original function</p></li>
<li><p>We overwrite the memory location containing the original size of the buffer with the <em>required</em> size of the buffer to fit the result (which may be smaller or larger than the actual size).
If the buffer is large enough we write the result to it.</p></li>
<li><p>From the Swift side, we read the amount of bytes specified in the memory
location that now contains the <em>required</em> size. If it turns out that the
<em>required size</em> is larger than the buffer’s size, we need to retry the
function call with a larger buffer.</p>
<ul>
<li>This means we might end up doing the work twice, if the original buffer size
is not big enough. Some engineering work might allow us to re-use the
result, but we’ll stick with retrying from scratch for simplicity.</li>
</ul></li>
</ul>
<p>We will use <code>JSON</code> as the serialization format: this choice is motivated
primarily by convenience because Swift can derive JSON instances for datatypes
out of the box (without incurring in extra dependencies), and in Haskell we can
use <code>aeson</code> to the same effect. In practice, it could be best to use a format
such as CBOR or Borsh which are binary formats optimised for compactness and
serialization performance.</p>
<h2 data-number="2.1" id="haskells-perspective"><span class="header-section-number">2.1</span> Haskell’s Perspective</h2>
<p>Extending the <code>User</code> example requires <code>User</code> to be decodable, which can be done automatically by adding to the <code>User</code> declaration:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> stock <span class="dt">Generic</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> anyclass (<span class="dt">ToJSON</span>, <span class="dt">FromJSON</span>)</span></code></pre></div>
<p>With the appropriate extensions and importing the necessary modules in <code>MyLib</code>:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE DerivingStrategies, DeriveAnyClass #-}</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- ...</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">GHC.Generics</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Data.Aeson</span></span></code></pre></div>
<p>The <code>MyForeignLib</code> module additionally must import</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Foreign.Ptr</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Foreign.Storable</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Foreign.Marshal</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Data.Aeson</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Data.ByteString</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Data.ByteString.Unsafe</span></span></code></pre></div>
<p>Now, let’s (foreign) export a function <code>c_birthday</code> that wraps
<code>birthday</code> above in <code>haskell-framework/flib/MyForeignLib.hs</code>, using the
described method.</p>
<p>First, the type definition of the function receives the buffer with the <code>User</code> argument, and a
buffer to write the <code>User</code> result to. We cannot use tuples because they are not
supported in foreign export declarations, but the intuition is that the first
two arguments represent the original <code>User</code> input, and the two latter arguments
represent the returned <code>User</code>.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ot">c_birthday ::</span> <span class="dt">Ptr</span> <span class="dt">CChar</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Ptr</span> <span class="dt">CChar</span> <span class="ot">-&gt;</span> <span class="dt">Ptr</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</span></code></pre></div>
<p>Then, the implementation – decode the argument, encode the result, write
result size to the given memory location and the result itself to the buffer, if
it fits.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>c_birthday cstr clen result size_ptr <span class="ot">=</span> <span class="kw">do</span></span></code></pre></div>
<p>We transform the <code>(Ptr CChar, Int)</code> pair into a <code>ByteString</code> using
<code>unsafePackCStringLen</code>, and decode a <code>User</code> from the <code>ByteString</code> using
<code>decodeStrict</code>:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- (1) Decode C string</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Just</span> user <span class="ot">&lt;-</span> decodeStrict <span class="op">&lt;$&gt;</span> unsafePackCStringLen (cstr, clen)</span></code></pre></div>
<p>We apply the original <code>birthday</code> function to the decoded <code>user</code>. In our example,
this is a very boring function, but in reality this is likely a complex
idiomatic Haskell function that we want to expose to.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- (2) Apply `birthday`</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> user_new <span class="ot">=</span> birthday user</span></code></pre></div>
<p>We encode the <code>new_user :: User</code> as a <code>ByteString</code>, and use
<code>unsafeUseAsCStringLen</code> to get a pointer to the bytestring data and its length.
Finally, we get the size of the result buffer, write the actual size of the
result to the given memory location, and, if the actual size fits the buffer,
copy the bytes from the bytestring to the given buffer.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- (3) Encode result</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>  unsafeUseAsCStringLen (toStrict <span class="op">$</span> encode user_new) <span class="op">$</span> \(ptr,len) <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- (3.2) What is the size of the result buffer?</span></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>    size_avail <span class="ot">&lt;-</span> peek size_ptr</span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- (3.3) Write actual size to the int ptr.</span></span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>    poke size_ptr len</span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- (3.4) If sufficient, we copy the result bytes to the given result buffer</span></span>
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a>    <span class="kw">if</span> size_avail <span class="op">&lt;</span> len</span>
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a>       <span class="kw">then</span> <span class="kw">do</span></span>
<span id="cb10-13"><a href="#cb10-13" aria-hidden="true" tabindex="-1"></a>         <span class="co">-- We need @len@ bytes available</span></span>
<span id="cb10-14"><a href="#cb10-14" aria-hidden="true" tabindex="-1"></a>         <span class="co">-- The caller has to retry</span></span>
<span id="cb10-15"><a href="#cb10-15" aria-hidden="true" tabindex="-1"></a>         <span class="fu">return</span> ()</span>
<span id="cb10-16"><a href="#cb10-16" aria-hidden="true" tabindex="-1"></a>       <span class="kw">else</span> <span class="kw">do</span></span>
<span id="cb10-17"><a href="#cb10-17" aria-hidden="true" tabindex="-1"></a>         moveBytes result ptr len</span></code></pre></div>
<p>If the written <em>required</em> size is larger than the given buffer, the caller will
retry.</p>
<p>Of course, we must export this as a C function.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>foreign export ccall<span class="ot"> c_birthday ::</span> <span class="dt">Ptr</span> <span class="dt">CChar</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Ptr</span> <span class="dt">CChar</span> <span class="ot">-&gt;</span> <span class="dt">Ptr</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</span></code></pre></div>
<p>This makes the <code>c_birthday</code> function wrapper available to Swift in the generated
header and at link time in the dynamic library.</p>
<h2 data-number="2.2" id="swifts-perspective"><span class="header-section-number">2.2</span> Swift’s Perspective</h2>
<p>In Swift, we want to be able to call the functions exposed from Haskell via
their C wrappers from a wrapper that feels idiomatic in Swift. In our example,
that means wrapping a call to <code>c_birthday</code> in a new Swift <code>birthday</code> function.</p>
<p>In <code>ContentView.swift</code>, we make <code>User</code> JSON-encodable/decodable by conforming to
the <code>Codable</code> protocol:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> User<span class="op">:</span> <span class="dt">Codable</span> <span class="op">{</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>    <span class="co">// ...</span></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>Then, we implement the Swift side of <code>birthday</code> which <em>simply</em> calls
<code>c_birthday</code> – the whole logic of <code>birthday</code> is handled by the Haskell side
function (recall that <code>birthday</code> could be incredibly complex, and other
functions exposed by Haskell will indeed be).</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">func</span> <span class="fu">birthday</span><span class="op">(</span><span class="va">user</span><span class="op">:</span> <span class="dt">User</span><span class="op">)</span> -&gt; <span class="fu">User</span> <span class="op">{</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>    <span class="co">// ...</span></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>Note: in the implementation, a couple of blocks have to be wrapped with a <code>do { ... } catch X { ... }</code> but I omit them in this text. You can see the commit
relevant to the Swift function wrapper implementation in the repo with all of
these details included.</p>
<p>First, we encode the Swift argument into JSON using the <code>Data</code> type (plus its
length) that will serve as arguments to the foreign C function.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="va">enc</span> <span class="op">=</span> JSONEncoder<span class="op">()</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="va">dec</span> <span class="op">=</span> JSONDecoder<span class="op">()</span></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> <span class="va">data</span><span class="op">:</span> Data <span class="op">=</span> <span class="cf">try</span> enc<span class="op">.</span>encode<span class="op">(</span>user<span class="op">)</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="va">data_len</span> <span class="op">=</span> Int64<span class="op">(</span>data<span class="op">.</span>count<span class="op">)</span></span></code></pre></div>
<p>However, a Swift <code>Data</code> value, which represents the JSON as binary data, cannot
be passed directly to C as a pointer. For that, we must use
<code>withUnsafeMutableBytes</code> to get an <code>UnsafeMutableRawBufferPointer</code> out of the
<code>Data</code> – that we can pass to the C foreign function. <code>withUnsafeMutableBytes</code>
receives a closure that uses an <code>UnsafeMutableRawBufferPointer</code> in its scope and
returns the value returned by the closure. Therefore we can return the result of
calling it on the user <code>Data</code> we encoded right away:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="kw">return</span> data<span class="op">.</span>withUnsafeMutableBytes <span class="op">{</span> <span class="op">(</span>rawPtr<span class="op">:</span> UnsafeMutableRawBufferPointer<span class="op">)</span> <span class="cf">in</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>    <span class="co">// here goes the closure that can use the raw pointer,</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>    <span class="co">// the code for which we describe below</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>We allocate a buffer for the C foreign function to insert the result of
calling the Haskell function, and also allocate memory to store the size of the
buffer. We use <code>withUnsafeTemporaryAllocation</code> to allocate a buffer that can be
used in the C foreign function call. As for <code>withUnsafeMutableBytes</code>, this
function also takes a closure and returns the value returned by the closure:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="co">// The data buffer size</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="va">buf_size</span> <span class="op">=</span> <span class="dv">1024048</span> <span class="co">// 1024KB</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a><span class="co">// A size=1 buffer to store the length of the result buffer</span></span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a><span class="kw">return</span> withUnsafeTemporaryAllocation<span class="op">(</span>of<span class="op">:</span> Int<span class="op">.</span><span class="kw">self</span><span class="op">:</span> <span class="dv">1</span><span class="op">)</span> <span class="op">{</span> size_ptr <span class="cf">in</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>    <span class="co">// Store the buffer size in this memory location</span></span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a>    size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">=</span> buf_size</span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a>    <span class="co">// Allocate the buffer for the result (we need to wrap this in a do { ...} catch for reasons explained below)</span></span>
<span id="cb16-10"><a href="#cb16-10" aria-hidden="true" tabindex="-1"></a>    <span class="cf">do</span> <span class="op">{</span></span>
<span id="cb16-11"><a href="#cb16-11" aria-hidden="true" tabindex="-1"></a>        <span class="kw">return</span> withUnsafeTemporaryAllocation<span class="op">(</span>byteCount<span class="op">:</span> buf_size<span class="op">,</span> alignment<span class="op">:</span><span class="dv">1</span><span class="op">)</span> <span class="op">{</span> res_ptr <span class="cf">in</span></span>
<span id="cb16-12"><a href="#cb16-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-13"><a href="#cb16-13" aria-hidden="true" tabindex="-1"></a>            <span class="co">// Continues from here ...</span></span>
<span id="cb16-14"><a href="#cb16-14" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
<span id="cb16-15"><a href="#cb16-15" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span> <span class="cf">catch</span> <span class="co">// We continue here in due time ...</span></span>
<span id="cb16-16"><a href="#cb16-16" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>We are now nested deep within 3 closures: one binds the pointer to the
argument’s data, the other the pointer to the buffer size, and the other the
result buffer pointer. This means we can now call the C foreign function
wrapping the Haskell function:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>c_birthday<span class="op">(</span>rawPtr<span class="op">.</span>baseAddress<span class="op">,</span> data_len<span class="op">,</span> res_ptr<span class="op">.</span>baseAddress<span class="op">,</span> size_ptr<span class="op">.</span>baseAddress<span class="op">)</span></span></code></pre></div>
<p>Recalling that the Haskell side will update the size pointed to by <code>size_ptr</code> to
the size required to serialize the encoded result, we need to check if
this required size exceeds the buffer we allocated, or read the data otherwise:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> <span class="kw">let</span> <span class="va">required_size</span> <span class="op">=</span> size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">{</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>    <span class="cf">if</span> required_size <span class="op">&gt;</span> buf_size <span class="op">{</span></span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>        <span class="co">// Need to try again</span></span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>        <span class="kw">throw</span> HsFFIError<span class="op">.</span>requiredSizeIs<span class="op">(</span>required_size<span class="op">)</span></span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-8"><a href="#cb18-8" aria-hidden="true" tabindex="-1"></a><span class="kw">return</span> dec<span class="op">.</span>decode<span class="op">(</span>User<span class="op">.</span><span class="kw">self</span><span class="op">,</span> from<span class="op">:</span> Data<span class="op">(</span>bytesNoCopy<span class="op">:</span> res_ptr<span class="op">.</span>baseAddress<span class="op">!,</span></span>
<span id="cb18-9"><a href="#cb18-9" aria-hidden="true" tabindex="-1"></a>                    count<span class="op">:</span> size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">??</span> <span class="dv">0</span><span class="op">,</span> deallocator<span class="op">:</span> <span class="op">.</span>none<span class="op">))</span></span></code></pre></div>
<p>where <code>HsFFIError</code> is a custom error defined as</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="kw">enum</span> HsFFIError<span class="op">:</span> <span class="dt">Error</span> <span class="op">{</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>    <span class="cf">case</span> requiredSizeIs<span class="op">(</span>Int<span class="op">)</span></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>We must now fill in the <code>catch</code> block to retry the foreign function call with a
buffer of the right size:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="op">}</span> <span class="cf">catch</span> HsFFIError<span class="op">.</span>requiredSizeIs<span class="op">(</span><span class="kw">let</span> <span class="va">required_size</span><span class="op">)</span> <span class="op">{</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">return</span> withUnsafeTemporaryAllocation<span class="op">(</span>byteCount<span class="op">:</span> required_size<span class="op">,</span> alignment<span class="op">:</span><span class="dv">1</span><span class="op">)</span></span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>    <span class="op">{</span> res_ptr <span class="cf">in</span></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a>        size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">=</span> required_size</span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a>        c_birthday<span class="op">(</span>rawPtr<span class="op">.</span>baseAddress<span class="op">,</span> data_len<span class="op">,</span> res_ptr<span class="op">.</span>baseAddress<span class="op">,</span> size_ptr<span class="op">.</span>baseAddress<span class="op">)</span></span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a>        <span class="kw">return</span> dec<span class="op">.</span>decode<span class="op">(</span>User<span class="op">.</span><span class="kw">self</span><span class="op">,</span> from<span class="op">:</span> Data<span class="op">(</span>bytesNoCopy<span class="op">:</span> res_ptr<span class="op">.</span>baseAddress<span class="op">!,</span></span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a>                    count<span class="op">:</span> size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">??</span> <span class="dv">0</span><span class="op">,</span> deallocator<span class="op">:</span> <span class="op">.</span>none<span class="op">))</span></span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>That seems like a lot of work to call a function from Haskell! However, despite
this being a lot of code, not a whole lot is happening: we simply serialize the
argument, allocate a buffer for the result, and deserialize the result into it.
In the worst case, if the serialized result does not fit (the serialized data
has over 1M characters), then we <em>naively</em> compute the function a
second time (it should not be terribly complicated to avoid this work by caching
the result and somehow resuming the serialization with the new buffer).
Furthermore, there is a lot of bureocracy in getting the raw pointers to send
off to Haskell land – the good news is that all of this can be automated away
behind automatic code generation with Template Haskell and Swift Macros.</p>
<details>
<summary>
Expand for the complete function
</summary>
<div class="sourceCode" id="cb21"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">func</span> <span class="fu">birthday</span> <span class="op">(</span><span class="va">user</span> <span class="op">:</span> <span class="dt">User</span><span class="op">)</span> -&gt; <span class="fu">User</span> <span class="op">{</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">enc</span> <span class="op">=</span> JSONEncoder<span class="op">()</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">dec</span> <span class="op">=</span> JSONDecoder<span class="op">()</span></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a>    <span class="cf">do</span> <span class="op">{</span></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a>        <span class="kw">var</span> <span class="va">data</span> <span class="op">:</span> Data <span class="op">=</span> <span class="cf">try</span> enc<span class="op">.</span>encode<span class="op">(</span>user<span class="op">)</span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span> <span class="va">data_len</span> <span class="op">=</span> Int64<span class="op">(</span>data<span class="op">.</span>count<span class="op">)</span></span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a>        <span class="kw">return</span> <span class="cf">try</span> data<span class="op">.</span>withUnsafeMutableBytes <span class="op">{</span> <span class="op">(</span>rawPtr<span class="op">:</span>UnsafeMutableRawBufferPointer<span class="op">)</span> <span class="cf">in</span></span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a>            <span class="co">// Allocate buffer for result</span></span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a>            <span class="kw">let</span> <span class="va">buf_size</span> <span class="op">=</span> <span class="dv">1024000</span></span>
<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a>            <span class="kw">return</span> <span class="cf">try</span> withUnsafeTemporaryAllocation<span class="op">(</span>of<span class="op">:</span> Int<span class="op">.</span><span class="kw">self</span><span class="op">,</span> capacity<span class="op">:</span> <span class="dv">1</span><span class="op">)</span> <span class="op">{</span> size_ptr <span class="cf">in</span></span>
<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a>                size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">=</span> buf_size</span>
<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a>                <span class="cf">do</span> <span class="op">{</span></span>
<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a>                    <span class="kw">return</span> <span class="cf">try</span> withUnsafeTemporaryAllocation<span class="op">(</span>byteCount<span class="op">:</span> buf_size<span class="op">,</span> alignment<span class="op">:</span> <span class="dv">1</span><span class="op">)</span> <span class="op">{</span></span>
<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a> res_ptr <span class="cf">in</span></span>
<span id="cb21-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-19"><a href="#cb21-19" aria-hidden="true" tabindex="-1"></a>                        c_birthday<span class="op">(</span>rawPtr<span class="op">.</span>baseAddress<span class="op">,</span> data_len<span class="op">,</span> res_ptr<span class="op">.</span>baseAddress<span class="op">,</span> size_ptr<span class="op">.</span>baseAddress<span class="op">)</span></span>
<span id="cb21-20"><a href="#cb21-20" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-21"><a href="#cb21-21" aria-hidden="true" tabindex="-1"></a>                        <span class="cf">if</span> <span class="kw">let</span> <span class="va">required_size</span> <span class="op">=</span> size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">{</span></span>
<span id="cb21-22"><a href="#cb21-22" aria-hidden="true" tabindex="-1"></a>                            <span class="cf">if</span> required_size <span class="op">&gt;</span> buf_size <span class="op">{</span></span>
<span id="cb21-23"><a href="#cb21-23" aria-hidden="true" tabindex="-1"></a>                                <span class="kw">throw</span> HsFFIError<span class="op">.</span>requiredSizeIs<span class="op">(</span>required_size<span class="op">)</span></span>
<span id="cb21-24"><a href="#cb21-24" aria-hidden="true" tabindex="-1"></a>                            <span class="op">}</span></span>
<span id="cb21-25"><a href="#cb21-25" aria-hidden="true" tabindex="-1"></a>                        <span class="op">}</span></span>
<span id="cb21-26"><a href="#cb21-26" aria-hidden="true" tabindex="-1"></a>                        <span class="kw">return</span> <span class="cf">try</span> dec<span class="op">.</span>decode<span class="op">(</span>User<span class="op">.</span><span class="kw">self</span><span class="op">,</span> from<span class="op">:</span> Data<span class="op">(</span>bytesNoCopy<span class="op">:</span> res_ptr<span class="op">.</span>baseAddress<span class="op">!,</span> count<span class="op">:</span> size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">??</span> <span class="dv">0</span><span class="op">,</span> deallocator<span class="op">:</span> <span class="op">.</span>none<span class="op">))</span></span>
<span id="cb21-27"><a href="#cb21-27" aria-hidden="true" tabindex="-1"></a>                    <span class="op">}</span></span>
<span id="cb21-28"><a href="#cb21-28" aria-hidden="true" tabindex="-1"></a>                <span class="op">}</span> <span class="cf">catch</span> HsFFIError<span class="op">.</span>requiredSizeIs<span class="op">(</span><span class="kw">let</span> <span class="va">required_size</span><span class="op">)</span> <span class="op">{</span></span>
<span id="cb21-29"><a href="#cb21-29" aria-hidden="true" tabindex="-1"></a>                    print<span class="op">(</span><span class="st">&quot;Retrying with required size: </span><span class="er">\(</span><span class="st">required_size)&quot;</span><span class="op">)</span></span>
<span id="cb21-30"><a href="#cb21-30" aria-hidden="true" tabindex="-1"></a>                    <span class="kw">return</span> <span class="cf">try</span> withUnsafeTemporaryAllocation<span class="op">(</span>byteCount<span class="op">:</span> required_size<span class="op">,</span> alignment<span class="op">:</span></span>
<span id="cb21-31"><a href="#cb21-31" aria-hidden="true" tabindex="-1"></a> <span class="dv">1</span><span class="op">)</span> <span class="op">{</span> res_ptr <span class="cf">in</span></span>
<span id="cb21-32"><a href="#cb21-32" aria-hidden="true" tabindex="-1"></a>                        size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">=</span> required_size</span>
<span id="cb21-33"><a href="#cb21-33" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-34"><a href="#cb21-34" aria-hidden="true" tabindex="-1"></a>                        c_birthday<span class="op">(</span>rawPtr<span class="op">.</span>baseAddress<span class="op">,</span> data_len<span class="op">,</span> res_ptr<span class="op">.</span>baseAddress<span class="op">,</span> size_ptr<span class="op">.</span>baseAddress<span class="op">)</span></span>
<span id="cb21-35"><a href="#cb21-35" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-36"><a href="#cb21-36" aria-hidden="true" tabindex="-1"></a>                        <span class="kw">return</span> <span class="cf">try</span> dec<span class="op">.</span>decode<span class="op">(</span>User<span class="op">.</span><span class="kw">self</span><span class="op">,</span> from<span class="op">:</span> Data<span class="op">(</span>bytesNoCopy<span class="op">:</span> res_ptr<span class="op">.</span>baseAddress<span class="op">!,</span> count<span class="op">:</span> size_ptr<span class="op">.</span>baseAddress<span class="op">?.</span>pointee <span class="op">??</span> <span class="dv">0</span><span class="op">,</span> deallocator<span class="op">:</span> <span class="op">.</span>none<span class="op">))</span></span>
<span id="cb21-37"><a href="#cb21-37" aria-hidden="true" tabindex="-1"></a>                    <span class="op">}</span></span>
<span id="cb21-38"><a href="#cb21-38" aria-hidden="true" tabindex="-1"></a>                <span class="op">}</span></span>
<span id="cb21-39"><a href="#cb21-39" aria-hidden="true" tabindex="-1"></a>            <span class="op">}</span></span>
<span id="cb21-40"><a href="#cb21-40" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
<span id="cb21-41"><a href="#cb21-41" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span> <span class="cf">catch</span> <span class="op">{</span></span>
<span id="cb21-42"><a href="#cb21-42" aria-hidden="true" tabindex="-1"></a>        print<span class="op">(</span><span class="st">&quot;Error decoding JSON probably: </span><span class="er">\(</span><span class="st">error)&quot;</span><span class="op">)</span></span>
<span id="cb21-43"><a href="#cb21-43" aria-hidden="true" tabindex="-1"></a>        <span class="kw">return</span> User<span class="op">(</span>name<span class="op">:</span> <span class="st">&quot;&quot;</span><span class="op">,</span> age<span class="op">:</span> <span class="dv">0</span><span class="op">)</span></span>
<span id="cb21-44"><a href="#cb21-44" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb21-45"><a href="#cb21-45" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
</details>
<p>We can test that this is working by replacing <code>ContentView</code> with:</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> ContentView<span class="op">:</span> <span class="dt">View</span> <span class="op">{</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> <span class="va">body</span><span class="op">:</span> some View <span class="op">{</span></span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a>        VStack <span class="op">{</span></span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a>            <span class="kw">let</span> <span class="va">user</span> <span class="op">=</span> birthday<span class="op">(</span>user<span class="op">:</span> User<span class="op">(</span>name<span class="op">:</span> <span class="st">&quot;Ellie&quot;</span><span class="op">,</span> age<span class="op">:</span> <span class="dv">24</span><span class="op">))</span></span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a>            Text<span class="op">(</span><span class="st">&quot;Post-birthday, </span><span class="er">\(</span><span class="st">user.name) is: </span><span class="er">\(</span><span class="st">user.age)!&quot;</span><span class="op">)</span></span>
<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
<span id="cb22-7"><a href="#cb22-7" aria-hidden="true" tabindex="-1"></a>        <span class="op">.</span>padding<span class="op">()</span></span>
<span id="cb22-8"><a href="#cb22-8" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb22-9"><a href="#cb22-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>And you should see:</p>
<figure>
<img src="/images/calling-haskell-from-swift/ss1.jpeg" alt="Fig 1. Swift app displays result of calling idiomatic Haskell function via idiomatic Swift wrapper" />
<figcaption aria-hidden="true">Fig 1. Swift app displays result of calling idiomatic Haskell function via idiomatic Swift wrapper</figcaption>
</figure>
<h1 data-number="3" id="metaprogramming-at-the-boundaries"><span class="header-section-number">3</span> Metaprogramming at the boundaries</h1>
<p>I want to give a quick preview of what is made possible by using compile-time
code generation features (Template Haskell in Haskell, Swift Macros in Swift).
This foreign function code generation API is exposed by the
<a href="https://github.com/alt-romes/haskell-swift">haskell-swift</a> project, namely the
<code>swift-ffi</code> Haskell library and <code>haskell-ffi</code> Swift package (since it is out of
the scope of this tutorial, I will not cover how exactly the compile-time
code-generation code works, but instead use the API provided by these
libraries).</p>
<p>With these top-level foreign interaction facilities, coupled with the build tool also
provided by <a href="https://github.com/alt-romes/haskell-swift">haskell-swift</a>, one can
easily bootstrap and develop programs mixing Haskell and Swift.</p>
<p>Let us consider the same example where we define an idiomatic <code>birthday :: User -&gt; User</code> function in Haskell and want to be able to call it from Swift as
<code>birthday(user: User) -&gt; User</code></p>
<h2 data-number="3.1" id="haskells-perspective-1"><span class="header-section-number">3.1</span> Haskell’s perspective</h2>
<p>To expose the <code>birthday</code> function to Swift, we simply use the <code>foreignExportSwift</code>
Template Haskell function. The whole module could look like this:</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE TemplateHaskell #-}</span></span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">MyLib</span> <span class="kw">where</span></span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-4"><a href="#cb23-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- ...</span></span>
<span id="cb23-5"><a href="#cb23-5" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Swift.FFI</span></span>
<span id="cb23-6"><a href="#cb23-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-7"><a href="#cb23-7" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">User</span></span>
<span id="cb23-8"><a href="#cb23-8" aria-hidden="true" tabindex="-1"></a> <span class="ot">=</span> <span class="dt">User</span> {<span class="ot"> name ::</span> <span class="dt">String</span></span>
<span id="cb23-9"><a href="#cb23-9" aria-hidden="true" tabindex="-1"></a>        ,<span class="ot"> age  ::</span> <span class="dt">Int</span></span>
<span id="cb23-10"><a href="#cb23-10" aria-hidden="true" tabindex="-1"></a>        }</span>
<span id="cb23-11"><a href="#cb23-11" aria-hidden="true" tabindex="-1"></a>        <span class="kw">deriving</span> stock    <span class="dt">Generic</span></span>
<span id="cb23-12"><a href="#cb23-12" aria-hidden="true" tabindex="-1"></a>        <span class="kw">deriving</span> anyclass <span class="dt">FromJSON</span></span>
<span id="cb23-13"><a href="#cb23-13" aria-hidden="true" tabindex="-1"></a>        <span class="kw">deriving</span> anyclass <span class="dt">ToJSON</span></span>
<span id="cb23-14"><a href="#cb23-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-15"><a href="#cb23-15" aria-hidden="true" tabindex="-1"></a><span class="ot">birthday ::</span> <span class="dt">User</span> <span class="ot">-&gt;</span> <span class="dt">User</span></span>
<span id="cb23-16"><a href="#cb23-16" aria-hidden="true" tabindex="-1"></a>birthday <span class="dt">User</span>{age<span class="ot">=</span>x, name<span class="ot">=</span>y} <span class="ot">=</span> <span class="dt">User</span>{age<span class="ot">=</span>x<span class="op">+</span><span class="dv">1</span>, name<span class="ot">=</span>y}</span>
<span id="cb23-17"><a href="#cb23-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-18"><a href="#cb23-18" aria-hidden="true" tabindex="-1"></a><span class="op">$</span>(foreignExportSwift &#39;birthday)</span></code></pre></div>
<p>The key bit is the last <code>foreignExportSwift</code> call which will expose a C function
with the marshalling-based calling convention we outlined above.</p>
<h2 data-number="3.2" id="swifts-perspective-1"><span class="header-section-number">3.2</span> Swift’s perspective</h2>
<p>On the Swift side, we want to use the dual <code>@ForeignImportHaskell</code> macro which
generates a Swift function wrapper which in turn invokes the C function exposed
by Haskell with the above marshalling strategy. The Swift file could
look like:</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">HaskellFFI</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> User<span class="op">:</span> <span class="dt">Codable</span> <span class="op">{</span></span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">name</span><span class="op">:</span> String</span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> <span class="va">age</span><span class="op">:</span> Int</span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a><span class="at">@ForeignImportHaskell</span></span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a><span class="kw">func</span> <span class="fu">birthday</span><span class="op">(</span><span class="va">cconv</span><span class="op">:</span> <span class="dt">HsCallJSON</span><span class="op">,</span> <span class="va">user</span><span class="op">:</span> <span class="dt">User</span><span class="op">)</span> -&gt; <span class="fu">User</span> <span class="op">{</span> stub<span class="op">()</span> <span class="op">}</span></span></code></pre></div>
<p>where <code>birthday</code> could be called e.g. as:</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a>birthday<span class="op">(</span>user<span class="op">:</span> User<span class="op">(</span>name<span class="op">:</span> <span class="st">&quot;Pierre&quot;</span><span class="op">,</span> age<span class="op">:</span> <span class="dv">55</span><span class="op">))</span></span></code></pre></div>
<h1 data-number="4" id="remarks"><span class="header-section-number">4</span> Remarks</h1>
<p>The strategy of marshaling for foreign language boundary crossing is very robust
and still performant, and is a great fit for the kind of mixed-language
application we want to develop robustly.</p>
<p>Even though marshaling is required for robustly traversing the foreign language
boundary, I will also explore, in a subsequent post, calling Haskell from Swift
by instead coercing the memory representation of a Haskell value into a Swift
one – this will mostly be a (very unsafe) and not-at-all robust curiosity, but
it will give me an excuse to write a bit about low-level details in Haskell!</p>
<p>In yet another post, I also intend to introduce the <code>hxs</code> tool for bootstrapping
Haskell x Swift projects and the libraries that make it so much easier to export
Haskell functions and import them from Swift.</p>
<p>The <a href="https://github.com/alt-romes/haskell-x-swift-project-steps">haskell-x-swift-project-steps</a>
git repository has a commit matching the steps of this guide, so if anything is
unclear you can just let the code speak by itself in checking the commits.</p>
<p>This project, blog post, and research regarding Swift interoperability with
Haskell is being partially sponsored by <a href="https://well-typed.com/">Well-Typed</a>,
and is otherwise carried out in my own free time. If you’d also like to sponsor my
work on Swift x Haskell interoperability with the goal of developing native
macOS/iOS/etc applications, visit <a href="https://github.com/sponsors/alt-romes">my GitHub sponsors page</a>.</p>
]]></summary>
</entry>
<entry>
    <title>Computed Properties for Haskell Records</title>
    <link href="http://alt-romes.github.io/posts/2023-11-30-computed-properties-for-haskell-records.html" />
    <id>http://alt-romes.github.io/posts/2023-11-30-computed-properties-for-haskell-records.html</id>
    <published>2023-11-30T00:00:00Z</published>
    <updated>2023-11-30T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#records-in-haskell" id="toc-records-in-haskell"><span class="toc-section-number">1</span> Records in Haskell</a>
<ul>
<li><a href="#overloaded-record-dot" id="toc-overloaded-record-dot"><span class="toc-section-number">1.1</span> Overloaded Record Dot</a></li>
<li><a href="#named-field-puns" id="toc-named-field-puns"><span class="toc-section-number">1.2</span> Named Field Puns</a></li>
</ul></li>
<li><a href="#computed-properties" id="toc-computed-properties"><span class="toc-section-number">2</span> Computed Properties</a></li>
<li><a href="#conclusion" id="toc-conclusion"><span class="toc-section-number">3</span> Conclusion</a></li>
</ul>
</div>
<h1 data-number="1" id="records-in-haskell"><span class="header-section-number">1</span> Records in Haskell</h1>
<p>Haskell has so-called record types, which are also commonly known as structs,
for instance, in C, Swift, and Rust. To define a square, one would write:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Point</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">Point</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>    {<span class="ot"> x ::</span> <span class="dt">Int</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>    ,<span class="ot"> y ::</span> <span class="dt">Int</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>    }</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Square</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">Square</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>    {<span class="ot"> topLeft     ::</span> <span class="dt">Point</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>    ,<span class="ot"> bottomRight ::</span> <span class="dt">Point</span></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a>    }</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>mySquare <span class="ot">=</span> <span class="dt">Square</span>{ topLeft <span class="ot">=</span> <span class="dt">Point</span>{x <span class="ot">=</span> <span class="dv">0</span>, y <span class="ot">=</span> <span class="dv">0</span>}</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>                 , bottomRight <span class="ot">=</span> <span class="dt">Point</span>{x <span class="ot">=</span> <span class="dv">2</span>, y <span class="ot">=</span> <span class="dv">2</span>} }</span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>mySquareWidth <span class="ot">=</span> x (bottomRight mySquare) <span class="op">-</span> x (topLeft mySquare)</span></code></pre></div>
<p>In Haskell record types are just syntactic sugar for ordinary product types
paired with functions that get and set these fields.
In essence, the above is not fundamentally different from having the following
standard product types and functions:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Point</span> <span class="ot">=</span> <span class="dt">Point</span> <span class="dt">Int</span> <span class="dt">Int</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Square</span> <span class="ot">=</span> <span class="dt">Square</span> <span class="dt">Point</span> <span class="dt">Point</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>x,<span class="ot"> y ::</span> <span class="dt">Point</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>x (<span class="dt">Point</span> px _) <span class="ot">=</span> px</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>y (<span class="dt">Point</span> _ py) <span class="ot">=</span> py</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>topLeft,<span class="ot"> bottomRight ::</span> <span class="dt">Square</span> <span class="ot">-&gt;</span> <span class="dt">Point</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>topLeft (<span class="dt">Square</span> tl _) <span class="ot">=</span> tl</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>bottomRight (<span class="dt">Square</span> _ br) <span class="ot">=</span> br</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a><span class="co">-- And setters...</span></span></code></pre></div>
<h2 data-number="1.1" id="overloaded-record-dot"><span class="header-section-number">1.1</span> Overloaded Record Dot</h2>
<p>However, by turning on the <code>OverloadedRecordDot</code> syntax extension, you can
use more syntactic sugar to project the fields of a record instead of using the
field name as a standard function:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE OverloadedRecordDot #-}</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>mySquareWidth <span class="ot">=</span> mySquare<span class="op">.</span>bottomRight<span class="op">.</span>x <span class="op">-</span> mySquare<span class="op">.</span>topLeft<span class="op">.</span>x</span></code></pre></div>
<p>which is neat!
I like <code>OverloadedRecordDot</code>. It looks clean and feels more like using proper
property of the record data type. It is also less ambiguous for an LSP to
suggest the record properties of a data type by typing after the <code>.</code>, than it is
to suggest functions to apply to the record type argument.</p>
<h2 data-number="1.2" id="named-field-puns"><span class="header-section-number">1.2</span> Named Field Puns</h2>
<p>Since I’m already writing about records, I’ll mention another extension I quite
enjoy: <code>NamedFieldPuns</code>.</p>
<p>Traditionally, when matching on a record, you can list the field names and bind
variables to the value associated with that field. Continuing the above example:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">area ::</span> <span class="dt">Square</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>area <span class="dt">Square</span>{topLeft <span class="ot">=</span> tl, bottomRight <span class="ot">=</span> br}</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=</span> (br<span class="op">.</span>x <span class="op">-</span> tl<span class="op">.</span>x) <span class="op">*</span> (br<span class="op">.</span>y <span class="op">-</span> tl<span class="op">.</span>y)</span></code></pre></div>
<p>We know, however, that naming things is hard and best avoided. With
<code>NamedFieldPuns</code>, instead of declaring the variable to be bound to the right of
the field name, we have the field name be the variable bound to its value:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">area ::</span> <span class="dt">Square</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>area <span class="dt">Square</span>{topLeft, bottomRight}</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=</span> (bottomRight<span class="op">.</span>x <span class="op">-</span> topLeft<span class="op">.</span>x) <span class="op">*</span> (bottomRight<span class="op">.</span>y <span class="op">-</span> topLeft<span class="op">.</span>y)</span></code></pre></div>
<p>There are more record-related extensions, such as <code>RecordWildCards</code> or
<code>OverloadedRecordUpdate</code>, which I will not get into, but that can also make life
smoother when working with records.</p>
<h1 data-number="2" id="computed-properties"><span class="header-section-number">2</span> Computed Properties</h1>
<p>Computed properties are a (not-particularly-exclusive-to) Swift concept I’ve
recently come accross while working on my <a href="2023-11-10-creating-a-macos-app-with-haskell-and-swift.html">interoperability between Haskell and
Swift project</a>.</p>
<p>Here is a definition from the <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/properties/">Swift book section on (computed)
properties</a>:</p>
<blockquote>
<p><em>Properties</em> associate values with a particular class, structure, or
enumeration. Stored properties store constant and variable values as part of
an instance, whereas computed properties calculate (rather than store) a
value. Computed properties are provided by classes, structures, and
enumerations. Stored properties are provided only by classes and structures.</p>
</blockquote>
<p>And a Swift example, where the <code>volume</code> is a property computed from the <code>width</code>,
the <code>height</code> and the <code>depth</code> of a <code>Cuboid</code>:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> Cuboid <span class="op">{</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> <span class="va">width</span> <span class="op">=</span> <span class="fl">0.0</span><span class="op">,</span> height <span class="op">=</span> <span class="fl">0.0</span><span class="op">,</span> depth <span class="op">=</span> <span class="fl">0.0</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> <span class="va">volume</span><span class="op">:</span> Double <span class="op">{</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>        <span class="kw">return</span> width <span class="op">*</span> height <span class="op">*</span> depth</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>C# also has a notion of <a href="https://learn.microsoft.com/en-us/dotnet/csharp/properties#computed-properties">computed properties</a>.
In Java, simple class methods computing a result from class properties can also
be seen as some sort of computed property, or, really, class methods in any
object oriented language.</p>
<p>In Haskell, as basically everything else, you can think of computed properties
as… just functions. But there is one key element to computed properties that
makes them different from just functions – them being called using dot syntax
at a value of a record type just like any other property, and the evoking the
idea of describing a <em>property</em> of the record type.</p>
<p>Can we have that kind of computed properties in Haskell? Well, of course!</p>
<p>Following the examples in previous sections, consider the <code>area</code> function to be
conceptually a <em>computed property</em> of a rectangle, as it uses the two <code>Square</code>
properties (<code>topLeft</code> and <code>bottomRight</code>) to compute a new one. Ultimately, we
want to be able to type:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> mySquare<span class="op">.</span>area</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="dv">6</span></span></code></pre></div>
<p>To achieve this, we need to emulate the behaviour of field accessors. The key
insight is to use the <code>HasField</code> class just like default field accessors do.
<code>HasField</code> enables so-called <a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/hasfield.html">record field selector
polymorphism</a>
and allows us to not only define functions to operate on any record type with eg a
field named <code>name</code>, it allows us to define field accessors for non-record types,
and, ultimately, allows us to create computed properties. The ability to
define our own instances of <code>HasField</code> is also documented in the user guide
under <a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/hasfield.html#virtual-record-fields">virtual record fields</a>.</p>
<p>To make the <code>area</code> function a field accessor, thereby making it a
record-dot-enabled-computed-property, we instance <code>HasField</code> using the field
name <code>area</code> (which is a defined as a type-level string in the first argument to
<code>HasField</code>):</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE GHC2021, OverloadedRecordDot, DataKinds #-}</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">GHC.Records</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">HasField</span> <span class="st">&quot;area&quot;</span> <span class="dt">Square</span> <span class="dt">Int</span> <span class="kw">where</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>    getField <span class="ot">=</span> area</span></code></pre></div>
<p>You can now write <code>some_square.area</code> to compute the area of the square based on
its record properties.</p>
<p>Here’s an example of a full program defining another computed property and printing it:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE GHC2021, OverloadedRecordDot, DataKinds #-}</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">GHC.Records</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">User</span> <span class="ot">=</span> <span class="dt">User</span></span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> birthYear ::</span> <span class="dt">Int</span></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> name ::</span> <span class="dt">String</span></span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">HasField</span> <span class="st">&quot;age&quot;</span> <span class="dt">User</span> <span class="dt">Int</span> <span class="kw">where</span> getField <span class="ot">=</span> age</span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-12"><a href="#cb9-12" aria-hidden="true" tabindex="-1"></a><span class="ot">age ::</span> <span class="dt">User</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a>age u <span class="ot">=</span> <span class="dv">2023</span> <span class="op">-</span> u<span class="op">.</span>birthYear</span>
<span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-15"><a href="#cb9-15" aria-hidden="true" tabindex="-1"></a><span class="ot">user ::</span> <span class="dt">User</span></span>
<span id="cb9-16"><a href="#cb9-16" aria-hidden="true" tabindex="-1"></a>user <span class="ot">=</span> <span class="dt">User</span>{birthYear<span class="ot">=</span><span class="dv">1995</span>, name<span class="ot">=</span><span class="st">&quot;Robert&quot;</span>}</span>
<span id="cb9-17"><a href="#cb9-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-18"><a href="#cb9-18" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span> <span class="fu">print</span> user<span class="op">.</span>age</span></code></pre></div>
<h1 data-number="3" id="conclusion"><span class="header-section-number">3</span> Conclusion</h1>
<p>This has been a whirlwhind thought kind of post. I am not currently using this
in any project. I thought “I suppose we can also have this neat properties
sugar” and tried it, this is only my exposition of the idea.</p>
<p>In my opinion, this could be handy as some functions can really be better thought of as
properties of a datatype, and doing so doesn’t preclude you from also using it
as a function in cases where it reads more naturally (and of course, pass it on
to higher order functions). LSP based autocompletion of (computed) properties after the dot might be another positive factor.
It is probably also a Haskell anti-pattern for some!</p>
<p>I’m left wondering:
is anyone out there doing this?</p>
]]></summary>
</entry>
<entry>
    <title>Creating a macOS app with Haskell and Swift</title>
    <link href="http://alt-romes.github.io/posts/2023-11-10-creating-a-macos-app-with-haskell-and-swift.html" />
    <id>http://alt-romes.github.io/posts/2023-11-10-creating-a-macos-app-with-haskell-and-swift.html</id>
    <published>2023-11-10T00:00:00Z</published>
    <updated>2023-11-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#hello-swift-its-haskell" id="toc-hello-swift-its-haskell"><span class="toc-section-number">1</span> Hello, Swift, it’s Haskell!</a>
<ul>
<li><a href="#setting-up-the-swiftui-app" id="toc-setting-up-the-swiftui-app"><span class="toc-section-number">1.1</span> Setting up the SwiftUI app</a></li>
<li><a href="#setting-up-a-haskell-foreign-library" id="toc-setting-up-a-haskell-foreign-library"><span class="toc-section-number">1.2</span> Setting up a Haskell foreign library</a></li>
<li><a href="#linking-the-haskell-library-with-the-executable" id="toc-linking-the-haskell-library-with-the-executable"><span class="toc-section-number">1.3</span> Linking the Haskell library with the executable</a></li>
<li><a href="#the-rts-must-be-initialized" id="toc-the-rts-must-be-initialized"><span class="toc-section-number">1.4</span> The RTS must be initialized</a></li>
</ul></li>
<li><a href="#remarks" id="toc-remarks"><span class="toc-section-number">2</span> Remarks</a>
<ul>
<li><a href="#further-reading" id="toc-further-reading"><span class="toc-section-number">2.1</span> Further Reading</a></li>
</ul></li>
</ul>
</div>
<p>This is the first part of an in-depth guide into developing a native
applications for Apple platforms (macOS, iOS, etc.) using Haskell with Swift and
SwiftUI. This is the first in a series of blog posts – covering the set-up
required to call Haskell functions from Swift in an XCode project using SwiftUI.
In future installements of the series, I intend to at least discuss calling
functions with idiomatic Haskell types with Swift ones (both with and without
marshaling), SwiftUI observation, and iOS development which requires GHC to
produce code for the iOS compilation target.</p>
<p>At the time of writing I’m using XCode 15, Cabal 3.10, and GHC 9.8. There will
be some features I use that are only available in these recent versions,
however, the general idea of interoperability between Haskell and Swift stands
on its own regardless – the now 7 year
old <a href="https://github.com/nanotech/swift-haskell-tutorial/tree/master">swift-haskell-tutorial</a> is still similarly relevant and greatly informed
my approach, despite the end result being considerably different.</p>
<p>The end goal is to create a multi-(apple)-platform application whose UI is
programmed in Swift using SwiftUI while the data and logic of the application is
implemented in Haskell which is called from Swift.</p>
<p>The series of blog posts is further accompanied by a github repository where
each commit matches a step of this tutorial. If in doubt regarding any step,
simply checking the matching commit for absolute confidence you are
understanding the practical step correctly. <a href="https://github.com/alt-romes/haskell-x-swift-project-steps">Visit this link to the haskell-x-swift-project-steps repository</a>!
Furthermore, I’m writing a build tool that will facilitate setting up and
building a project like this without having to go through all the manual steps: <a href="https://github.com/alt-romes/haskell-swift">haskell-swift</a>.</p>
<p>This write-up has been cross-posted to <a href="https://well-typed.com/blog/">Well-Typed’s Blog</a>.</p>
<h1 data-number="1" id="hello-swift-its-haskell"><span class="header-section-number">1</span> Hello, Swift, it’s Haskell!</h1>
<p>In this part we are only concerned with getting our <code>Hello, World!</code> going.</p>
<ol type="1">
<li>We’ll setup a Haskell (foreign) library exporting a function <code>hs_factorial</code> that
returns the factorial of integer, using the C FFI</li>
<li>Setup a SwiftUI app that calls <code>hs_factorial</code></li>
<li>Compile the Haskell code into a shared library</li>
<li>Create a Swift module <code>HaskellFramework</code> to export the Haskell functions
(imported from the stub C header files), and setup linking against the
Haskell shared library.</li>
<li>Import <code>HaskellFramework</code> into the SwiftUI app to be able to successfully
call <code>hs_factorial</code> and display the result on the screen of the running
application.</li>
</ol>
<p>The following diagram (rendered by <a href="https://arthursonzogni.com/Diagon/#GraphDAG">Diagon</a>) describes how the Swift executable and Haskell libraries
are going to be connected from a not-too-far-away perspective. It might be
useful to consult this diagram once in a while throughout the post!
<!-- Source code of graph @ https://arthursonzogni.com/Diagon/#GraphDAG

Haskell library -> Haskell foreign library
cbits -> Haskell foreign library
cbits -> Headers (cbits)
Haskell foreign library -> Headers (stubs)
Haskell foreign library -> Shared dynamic library
Headers (stubs) -> Clang modules
Headers (cbits) -> Clang modules

gen-dynamic-settings.sh -> DynamicBuildSettings.xcconfig
RTS headers -> DynamicBuildSettings.xcconfig
Shared dynamic library -> DynamicBuildSettings.xcconfig
DynamicBuildSettings.xcconfig -> BuildSettings.xcconfig

Clang modules -> SwiftUI App
Shared dynamic library -> SwiftUI App
BuildSettings.xcconfig -> SwiftUI App
--></p>
<div class="sourceCode" id="cb1"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>┌───────────────┐┌───────────┐┌───────────────────────┐┌───────────┐</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>│Haskell library││cbits      ││gen-dynamic-settings.sh││RTS headers│</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>└┬──────────────┘└┬─────────┬┘└─────────────┬─────────┘└┬──────────┘</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>┌▽────────────────▽───────┐┌▽──────────────┐│           │</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>│Haskell foreign library  ││Headers (cbits)││           │</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>└┬───────────────────────┬┘└─────────────┬─┘│           │</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>┌▽─────────────────────┐┌▽──────────────┐│  │           │</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>│Shared dynamic library││Headers (stubs)││  │           │</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>└┬────────────────────┬┘└┬──────────────┘│  │           │</span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a> │            ┌───────│──│───────────────┘  │           │</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a> │            │┌──────│──┘                  │ ┌─────────┘</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a> │┌───────────▽▽┐┌────▽─────────────────────▽─▽┐</span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a> ││Clang modules││DynamicBuildSettings.xcconfig│</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a> │└┬────────────┘└┬────────────────────────────┘</span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a> │ │┌─────────────▽────────┐</span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a> │ ││BuildSettings.xcconfig│</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a> │ │└┬─────────────────────┘</span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a>┌▽─▽─▽──────┐</span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a>│SwiftUI App│</span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a>└───────────┘</span></code></pre></div>
<h2 data-number="1.1" id="setting-up-the-swiftui-app"><span class="header-section-number">1.1</span> Setting up the SwiftUI app</h2>
<p>Let’s set-up a simple XCode project using SwiftUI for the main interface. Fire
up XCode and create a macOS Application, named <code>SwiftHaskell</code>, using SwiftUI,
excluding tests. Choose a Personal Team rather than None - you might have to
create a (free of charge) one.</p>
<p>In the newly-created project there should exist two files: <code>SwiftHaskellApp.swift</code> and <code>ContentView.swift</code>.
We can change right away <code>ContentView.swift</code> to display the result of calling
<code>hs_factorial(5)</code>, even though <code>hs_factorial</code> is not yet in scope:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">SwiftUI</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> ContentView<span class="op">:</span> <span class="dt">View</span> <span class="op">{</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> <span class="va">body</span><span class="op">:</span> some View <span class="op">{</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>        VStack <span class="op">{</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>            Text<span class="op">(</span><span class="st">&quot;Hello, Haskell: </span><span class="er">\(</span><span class="st">hs_factorial(5))!&quot;</span><span class="op">)</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>        <span class="op">.</span>padding<span class="op">()</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>Before proceeding to the Haskell side, create a <code>New File &gt; Configuration Settings File</code> (also known as a <code>.xcconfig</code> file) named
<code>BuildSettings.xcconfig</code>. We’ll use this file to write all our build settings
textually instead of using XCode’s build settings navigator.</p>
<p>To use our <code>.xcconfig</code> file for the project settings, under <code>Info &gt; Configurations</code>
in the project tab, select the <code>BuildSettings</code> file.
For the configuration to show up in XCode, the <code>.xcconfig</code> must be in the tree
navigator (which happens by default if you created the module within XCode).
You can read more, or see exactly how to set an <code>.xcconfig</code> file as the
configuration, in this <a href="https://nshipster.com/xcconfig/">write-up on <code>xcconfig</code></a>
by NSHipster.</p>
<p>Even though we are setting the <code>.xcconfig</code> file manually (and also e.g.
initializing the XCode project), it is possible to resort to an exclusively
programatic approach using so-called XCode project generators such as
<a href="https://github.com/yonaskolb/XcodeGen">XCodeGen</a>
and <a href="https://tuist.io/">Tuist</a>.</p>
<h2 data-number="1.2" id="setting-up-a-haskell-foreign-library"><span class="header-section-number">1.2</span> Setting up a Haskell foreign library</h2>
<p>Create a folder <code>haskell-framework</code> within the XCode project, <code>cd</code> into it, and
follow from there.</p>
<p>We’re jumping straight into a full-fledged Haskell projected managed with cabal,
where we define a shared library using the <code>foreign-library</code> stanza.</p>
<p>Start with a normal cabal file with a <code>library</code> stanza that exposes <code>MyLib</code> (by
running <code>cabal init</code> within <code>haskell-framework</code>), and add the function <code>hs_factorial</code> to <code>MyLib</code> that
operates on <code>CInt</code>s:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">MyLib</span> <span class="kw">where</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Foreign.C</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ot">hs_factorial ::</span> <span class="dt">CInt</span> <span class="ot">-&gt;</span> <span class="dt">CInt</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>hs_factorial x <span class="ot">=</span> <span class="fu">product</span> [<span class="dv">1</span><span class="op">..</span>x]</span></code></pre></div>
<p>The organization of the code here isn’t terribly important. Perhaps in a
real project you could want to, for instance, only use C types like <code>CInt</code>
in the foreign library bits.</p>
<p>In the cabal file, add a <code>foreign-library</code> stanza with</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>foreign<span class="op">-</span>library haskell<span class="op">-</span>foreign<span class="op">-</span>framework</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">type</span><span class="op">:</span> native<span class="op">-</span>shared</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- This should work on Mac, despite being undefined behaviour</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- See https://www.hobson.space/posts/haskell-foreign-library/ (great read)</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>    options<span class="op">:</span> standalone</span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- We copy the C stub headers to a folder in the root.</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- If you have foreign-export declarations in the library</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- be sure to add this flag there too (so all stubs get added</span></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- to the `haskell-framework-include` folder)</span></span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a>    ghc<span class="op">-</span>options<span class="op">:</span> <span class="op">-</span>stubdir<span class="ot">=</span>haskell<span class="op">-</span>framework<span class="op">-</span>include</span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a>    other<span class="op">-</span>modules<span class="op">:</span> <span class="dt">MyForeignLib</span></span>
<span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a>    build<span class="op">-</span>depends<span class="op">:</span> base, haskell<span class="op">-</span>framework</span>
<span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a>    hs<span class="op">-</span>source<span class="op">-</span>dirs<span class="op">:</span> flib</span></code></pre></div>
<p>Unfortunately, <code>options: standalone</code> is only officially supported (and
required) by Windows, even though it is exactly what we need. However,
unofficially, a macOS distribution should be able to safely use this option
– for more information see this <a href="https://www.hobson.space/posts/haskell-foreign-library/">write-up on foreign libraries explaining why this option is
undefined for macOS</a>.
<!---->
In the future, this might work out of the box without being undefined
behaviour, or the behaviour on macOS may have changed s.t. this no longer
works… but let’s hope for the former.
<!---->
Additionally, we pass <code>-stubdir</code> for GHC to output the C stub header files to a
directory <code>haskell-framework-include</code>. Do add this automatically generated
directory to <code>.gitignore</code>.</p>
<p>Create the file <code>flib/MyForeignLib.hs</code> that declares a <code>foreign export</code> of
<code>hs_factorial</code> imported from <code>MyLib</code> and <code>foreign export</code>s it:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE ForeignFunctionInterface #-}</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">MyForeignLib</span> <span class="kw">where</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Foreign.C</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">MyLib</span> (hs_factorial)</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>foreign export ccall<span class="ot"> hs_factorial ::</span> <span class="dt">CInt</span> <span class="ot">-&gt;</span> <span class="dt">CInt</span></span></code></pre></div>
<p>It doesn’t seem that re-exporting the function from <code>MyLib</code> when it is foreign
exported from there is enough for it to be included in the shared library (might
be a bug), we do need the <code>foreign export</code> here rather than in <code>MyLib</code>.</p>
<p>Running <code>cabal build</code> should now generate a <code>haskell-framework-include</code> folder with a
<code>MyForeignLib_stub.h</code>, and a <code>libhaskell-foreign-framework.dylib</code> shared library
somewhere under <code>dist-newstyle</code> (you can <code>find . -name libhaskell-foreign-framework.dylib</code> to find it)</p>
<p>We’ll test C program against this library to check whether it works as expected.
Create <code>scripts/test-haskell-foreign-lib.sh</code> with a script that compiles a
main function in C which calls <code>hs_factorial</code>. A few notes:</p>
<ul>
<li>We need to pass the path to the built shared library (<code>$HS_FLIB_PATH</code>)
to the compiler.</li>
<li>We need to pass the path to the headers (<code>$HS_HEADERS_PATH</code>).</li>
<li>We hardcode into the executable the path to the shared library as an <code>rpath</code>
search path (just for testing purposes).
When building the macOS app, XCode will add <code>@executable_path/../Frameworks</code>
to the <code>rpath</code> search path, so we can simply copy the shared library the
Apple-blessed location (<code>Frameworks</code>).</li>
<li>We need to call <code>hs_init</code> and <code>hs_exit</code> to init the runtime system
(see the <a href="https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/ffi.html#using-the-ffi-with-ghc">relevant GHC user guide section</a>).</li>
<li>We need to compile the C library using <code>ghc</code>, as it will automatically
include and link the rts headers and library. To use a C compiler
we’d also need to find the rts headers and library of our Haskell
installation.</li>
</ul>
<div class="sourceCode" id="cb6"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">#!/usr/bin/env bash</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="bu">set</span> <span class="at">-e</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> <span class="ot">! </span><span class="bu">test</span> <span class="at">-f</span> <span class="st">&quot;haskell-framework.cabal&quot;</span><span class="kw">;</span> <span class="cf">then</span></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>    <span class="bu">echo</span> <span class="st">&quot;Run this script from the root of your project!&quot;</span></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>    <span class="bu">exit</span> 1</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a><span class="cf">fi</span></span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a><span class="va">HS_FLIB_PATH</span><span class="op">=</span><span class="va">$(</span><span class="fu">dirname</span> <span class="va">$(</span><span class="fu">find</span> . <span class="at">-name</span> libhaskell-foreign-framework.dylib<span class="va">))</span></span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a><span class="va">HS_HEADERS_PATH</span><span class="op">=</span>haskell-framework-include</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a><span class="bu">echo</span> <span class="st">&quot;</span></span>
<span id="cb6-14"><a href="#cb6-14" aria-hidden="true" tabindex="-1"></a><span class="st">#include &lt;stdio.h&gt;</span></span>
<span id="cb6-15"><a href="#cb6-15" aria-hidden="true" tabindex="-1"></a><span class="st">#include &lt;MyForeignLib_stub.h&gt;</span></span>
<span id="cb6-16"><a href="#cb6-16" aria-hidden="true" tabindex="-1"></a><span class="st">#include &lt;HsFFI.h&gt;</span></span>
<span id="cb6-17"><a href="#cb6-17" aria-hidden="true" tabindex="-1"></a><span class="st">int main(void) {</span></span>
<span id="cb6-18"><a href="#cb6-18" aria-hidden="true" tabindex="-1"></a><span class="st">    hs_init(NULL, NULL);</span></span>
<span id="cb6-19"><a href="#cb6-19" aria-hidden="true" tabindex="-1"></a><span class="st">    printf(</span><span class="dt">\&quot;</span><span class="st">%d\n</span><span class="dt">\&quot;</span><span class="st">, hs_factorial(5));</span></span>
<span id="cb6-20"><a href="#cb6-20" aria-hidden="true" tabindex="-1"></a><span class="st">    hs_exit();</span></span>
<span id="cb6-21"><a href="#cb6-21" aria-hidden="true" tabindex="-1"></a><span class="st">    return 0;</span></span>
<span id="cb6-22"><a href="#cb6-22" aria-hidden="true" tabindex="-1"></a><span class="st">}</span></span>
<span id="cb6-23"><a href="#cb6-23" aria-hidden="true" tabindex="-1"></a><span class="st">&quot;</span> <span class="op">&gt;</span> conftestmain.c</span>
<span id="cb6-24"><a href="#cb6-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-25"><a href="#cb6-25" aria-hidden="true" tabindex="-1"></a><span class="co"># We use `ghc` instead of `gcc` because otherwise we also need to provide the</span></span>
<span id="cb6-26"><a href="#cb6-26" aria-hidden="true" tabindex="-1"></a><span class="co"># include and lib path of the runtime system (Rts)</span></span>
<span id="cb6-27"><a href="#cb6-27" aria-hidden="true" tabindex="-1"></a><span class="ex">ghc</span> <span class="at">-no-hs-main</span> <span class="at">-o</span> conftest conftestmain.c <span class="dt">\</span></span>
<span id="cb6-28"><a href="#cb6-28" aria-hidden="true" tabindex="-1"></a>    <span class="at">-lhaskell-foreign-framework</span> <span class="dt">\</span></span>
<span id="cb6-29"><a href="#cb6-29" aria-hidden="true" tabindex="-1"></a>    <span class="at">-I</span><span class="st">&quot;</span><span class="va">$HS_HEADERS_PATH</span><span class="st">&quot;</span> <span class="dt">\</span></span>
<span id="cb6-30"><a href="#cb6-30" aria-hidden="true" tabindex="-1"></a>    <span class="at">-L</span><span class="st">&quot;</span><span class="va">$HS_FLIB_PATH</span><span class="st">&quot;</span> <span class="dt">\</span></span>
<span id="cb6-31"><a href="#cb6-31" aria-hidden="true" tabindex="-1"></a>    <span class="at">-optl-Wl,-rpath,</span><span class="st">&quot;</span><span class="va">$HS_FLIB_PATH</span><span class="st">&quot;</span></span>
<span id="cb6-32"><a href="#cb6-32" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-33"><a href="#cb6-33" aria-hidden="true" tabindex="-1"></a><span class="va">RESULT</span><span class="op">=</span><span class="va">$(</span><span class="ex">./conftest</span><span class="va">)</span></span>
<span id="cb6-34"><a href="#cb6-34" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-35"><a href="#cb6-35" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> <span class="bu">[</span> 120 <span class="ot">-eq</span> <span class="va">$RESULT</span> <span class="bu">]</span><span class="kw">;</span> <span class="cf">then</span></span>
<span id="cb6-36"><a href="#cb6-36" aria-hidden="true" tabindex="-1"></a>    <span class="bu">echo</span> <span class="st">&quot;Foreign library successfully called!&quot;</span></span>
<span id="cb6-37"><a href="#cb6-37" aria-hidden="true" tabindex="-1"></a><span class="cf">else</span></span>
<span id="cb6-38"><a href="#cb6-38" aria-hidden="true" tabindex="-1"></a>    <span class="bu">echo</span> <span class="st">&quot;Bad bad foreign library!&quot;</span></span>
<span id="cb6-39"><a href="#cb6-39" aria-hidden="true" tabindex="-1"></a>    <span class="bu">exit</span> 1</span>
<span id="cb6-40"><a href="#cb6-40" aria-hidden="true" tabindex="-1"></a><span class="cf">fi</span></span>
<span id="cb6-41"><a href="#cb6-41" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-42"><a href="#cb6-42" aria-hidden="true" tabindex="-1"></a><span class="fu">rm</span> <span class="at">-f</span> conftest<span class="pp">*</span></span></code></pre></div>
<p>You should get <code>Foreign library successfully called!</code> when this script is run.</p>
<h2 data-number="1.3" id="linking-the-haskell-library-with-the-executable"><span class="header-section-number">1.3</span> Linking the Haskell library with the executable</h2>
<p>Our recipe for invoking a foreign exported Haskell function in Swift:</p>
<ol type="1">
<li>Create a Swift <em>module</em> exporting Haskell functions through a module map
pointing to the headers exporting the Haskell functions.</li>
<li>Extend the <em>module search path</em> with the location of your new module map.</li>
<li>Import that module as a module in the SwiftUI code, and use the desired function.</li>
<li>At link time, the shared library with the symbols used by the program must be
linked against, and must be found in the <em>run-path</em> which can be done by copying
the shared library into the app bundled <code>Frameworks</code> folder.</li>
</ol>
<p>We create a module map file listing all the headers exporting Haskell functions
to define Swift modules where Haskell functions will live, using <a href="https://clang.llvm.org/docs/Modules.html">Clang’s module
system</a>. A module map looks something like</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">HaskellFramework</span> {</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>    header <span class="st">&quot;haskell-framework/haskell-framework-include/MyForeignLib.h&quot;</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>    export <span class="op">*</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<p>and can be imported into Swift code with <code>import HaskellFramework</code>, as long as
the module map is available as <code>module.modulemap</code> in the <em>import search path</em>.
As one might expect, importing this module brings into scope all names exported
from the listed header(s).</p>
<p>Specifically, we will use the <a href="https://clang.llvm.org/docs/Modules.html#submodule-declaration">inferred submodules</a>
feature of modules to create our module map. With inferred submodules, we can
simply define an <strong>umbrella</strong> directory with headers and get a submodule for each
header in that directory (arbitrarily nested, where a header <code>A/B/C.h</code> becomes a
submodule named <code>MainModule.A.B.C</code>)</p>
<p>In the root of the XCode project, write a <code>module.modulemap</code> file:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">HaskellFramework</span> {</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>    umbrella <span class="st">&quot;haskell-framework/haskell-framework-include&quot;</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>    </span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>    explicit <span class="kw">module</span> <span class="op">*</span> {</span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>        export <span class="op">*</span></span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a>    }</span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a>    </span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<p>The <code>umbrella</code> keyword specifies the directory where to find the header files
for our submodules, and the <code>explicit module *</code> lines are the <em>inferred
submodule</em> part, as each header will result in a declaration roughly like
<code>explicit module HeaderName { header "umbrella/HeaderName.h" ... }</code>.
In effect, our module map above will expand to:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">HaskellFramework</span> {</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>    explicit <span class="kw">module</span> <span class="dt">MyForeignLib</span> {</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>        header <span class="st">&quot;haskell-framework/haskell-framework-include/MyForeignLib.h&quot;</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>        export <span class="op">*</span></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>    }</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<p>Again, to be clear, this is what our original <code>module.modulemap</code> using the
<code>umbrella</code> keyword currently expands to, <strong>not the file we wrote</strong>.</p>
<p>Having written our <code>module.modulemap</code>, we need to extend the compiler’s <em>import
search path</em> to find this module map. As we’ve already set-up our <code>xcconfig</code>-based
configuration, this amounts to writing into <code>BuildSettings.xcconfig</code>:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="va">SWIFT_INCLUDE_PATHS</span><span class="op">=</span><span class="va">$(</span><span class="ex">PROJECT_DIR</span><span class="va">)</span></span></code></pre></div>
<p>This is equivalent to changing the <code>Swift Compiler - Search Paths &gt; Import Paths</code> build setting in XCode (in fact, by inspecting that setting on the
rightmost inspector panel, you will find the corresponding <code>xcconfig</code> name is indeed
<code>SWIFT_INCLUDE_PATHS</code> – this is also all explained in the <a href="https://nshipster.com/xcconfig/"><code>xcconfig</code>
article</a>).</p>
<p>Returning to <code>ContentView.swift</code>, where <code>hs_factorial</code> is being called, you
should be able to add at the top of the file, and have XCode successfully recognize:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="im">HaskellFramework</span><span class="op">.</span><span class="im">MyForeignLib_stub</span></span></code></pre></div>
<p>Even though the import is recognized, it will not compile successfully. The
reason is our stub header (<code>MyForeignLib_stub.h</code>) includes <code>&lt;HsFFI.h&gt;</code> which
cannot be found by XCode. We need to extend our <em>Header Search Path</em> with the
path to the RTS headers.</p>
<p>Currently, our <code>BuildSettings.xcconfig</code> can only contain statically known
information. Fortunately, we can <code>#include</code> other <code>xcconfig</code> files (that may
have been generated dynamically) in our <code>BuildSettings.xcconfig</code> (as described
by the <a href="https://nshipster.com/xcconfig/"><code>xcconfig</code> write-up</a>).
We do this by adding the following include directive in the <code>BuildSettings.xcconfig</code> file:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&quot;DynamicBuildSettings.xcconfig&quot;</span></span></code></pre></div>
<p>We will generate <code>DynamicBuildSettings.xcconfig</code> with a script
<code>haskell-framework/scripts/gen-dynamic-settings.sh</code> that calls the</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="ex">ghc-pkg</span> field rts include-dirs <span class="at">--simple-output</span></span></code></pre></div>
<p>to figure out the rts include path of the existing GHC installation.</p>
<p>We extend <code>HEADER_SEARCH_PATHS</code>, the <code>xcconfig</code> variable listing the paths where
XCode will search for headers when building, with the path to the RTS header
files:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="co">#!/usr/bin/env bash</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="bu">set</span> <span class="at">-e</span></span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> <span class="ot">! </span><span class="bu">test</span> <span class="at">-f</span> <span class="st">&quot;haskell-framework/haskell-framework.cabal&quot;</span><span class="kw">;</span> <span class="cf">then</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>    <span class="bu">echo</span> <span class="st">&quot;Run this script from the root of your XCode project!&quot;</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>    <span class="bu">exit</span> 1</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a><span class="cf">fi</span></span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a><span class="bu">echo</span> <span class="st">&quot;</span></span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a><span class="st">HEADER_SEARCH_PATHS=</span><span class="dt">\$</span><span class="st">(inherit) </span><span class="va">$(</span><span class="ex">ghc-pkg</span> field rts include-dirs <span class="at">--simple-output</span> <span class="kw">|</span> <span class="fu">tr</span> <span class="st">&#39; &#39;</span> <span class="st">&#39;\n&#39;</span> <span class="kw">|</span> <span class="fu">tail</span> <span class="at">-n1</span><span class="va">)</span></span>
<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a><span class="st">&quot;</span> <span class="op">&gt;</span> DynamicBuildSettings.xcconfig</span>
<span id="cb14-12"><a href="#cb14-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-13"><a href="#cb14-13" aria-hidden="true" tabindex="-1"></a><span class="bu">echo</span> <span class="st">&quot;Created DynamicBuildSettings.xcconfig!&quot;</span></span></code></pre></div>
<p>Do add <code>DynamicBuildSettings.xcconfig</code> to <code>.gitignore</code>.
The literal string <code>$(inherit)</code> is <code>xcconfig</code> syntax for inheriting the options
set before applying this configuration. Furthermore,
asking for the <code>include-dirs</code> of <code>rts</code> outputs two directories:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>/Users/romes/.ghcup/ghc/9.8.1/lib/ghc-9.8.1/lib/../lib/aarch64-osx-ghc-9.8.1/rts-1.0.2/include</span></code></pre></div>
<p>However, the <code>ffi</code> header is already included in a module by default in XCode
applications, so we need to cut it out of the search paths to avoid a
<code>Redefinition of module 'FFI'</code> error (<code>tr</code> combined with <code>tail -n1</code> select just
the path to the RTS headers).</p>
<p>The function is now found by XCode as the module it is defined in compiles
successfully and brings the function into scope.
However, building the program will fail with a <em>link time</em> error:
even though we instructed the compiler to find the definitions of the Haskell
functions we want to use and the module they are exported from, we have not
linked against the library where the actual symbols are defined.</p>
<p>The Haskell foreign library created in a previous section compiles to a
<em>shared dynamic library</em>. To link against it when building our Swift application
we need to pass <code>-lhaskell-foreign-framework</code> to the compilation toolchain and
instruct it on where to find this library. The first step can be done in two
compatible (as in both can co-exist) ways:</p>
<ul>
<li>Add a <code>link "haskell-foreign-framework"</code> declaration to the module map (explained <a href="https://clang.llvm.org/docs/Modules.html#link-declaration">here</a>)
<ul>
<li>There is a note about this feature not yet being widely supported in the
reference page, however, it is works to link the library in my machine
with XCode 15.</li>
</ul></li>
<li>Add the <code>-lhaskell-foreign-framework</code> flag to the <code>OTHER_LDFLAGS</code> build
setting in <code>BuildSettings.xcconfig</code>. You can do this even if you’ve also
used the link directive.</li>
</ul>
<p>After adding the <code>link</code> declaration, your <code>module.modulemap</code> should contain:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">HaskellFramework</span> {</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>    umbrella <span class="st">&quot;haskell-framework/haskell-framework-include&quot;</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>    </span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>    explicit <span class="kw">module</span> <span class="op">*</span> {</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>        export <span class="op">*</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>    }</span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a>    link <span class="st">&quot;haskell-foreign-framework&quot;</span></span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<p>Secondly, we need to add the shared library path to the <em>library search path</em>
and make it available at runtime by copying it to the <code>Frameworks</code> folder that
is bundled with the application.
By copying the library to this folder we ensure it can be found when dynamically
loaded at runtime: the library install name is relative to <code>@rpath</code>, i.e. it is
a <a href="https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/RunpathDependentLibraries.html"><em>run-path dependent library</em></a>,
and the run-path dependencies of XCode built executables are searched for in the
Frameworks folder, relatively to the executable path (<code>@executable_path/../Frameworks</code>).</p>
<blockquote>
<p>A run-path dependent library is a dependent library whose complete install
name is not known when the library is created (see How Dynamic Libraries Are
Used). Instead, the library specifies that the dynamic loader must resolve the
library’s install name when it loads the executable that depends on the
library.</p>
<p>To use run-path dependent libraries, an executable provides a list of run-path
search paths, which the dynamic loader traverses at load time to find the
libraries.</p>
</blockquote>
<p>In practice, we achieve this by extending the <code>LIBRARY_SEARCH_PATHS</code> setting
dynamically and add a “Copy” Build Phase which copies the shared library to the
listed Frameworks folder. At this time, I do not know how to do this Copy
outside of XCode – do shoot me a text if you know how. It is also unfortunate
that we have to hardcode the path to the dynamic library there, instead of
computing it at build time.</p>
<p>Find the path to the foreign library by running, in the <code>haskell-framework</code> directory:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>cabal list-bin haskell-foreign-framework</span></code></pre></div>
<p>Then, under the Build Phases tab of the project settings, add (by clicking in
the little plus sign) a <code>New Copy Files Phase</code>. Then, clicking in the plus sign of
the new listing of files to copy, add the haskell-foreign-framework
<code>.dylib</code> (the shared library) that lives at the path found by running the above
command by clicking on “Add Other”.</p>
<p>To the <code>haskell-framework/scripts/gen-dynamic-settings.sh</code>, add the following
lines before echoing to the file</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="bu">pushd</span> . <span class="op">&gt;</span> /dev/null</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="bu">cd</span> haskell-framework</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a><span class="va">FLIB_PATH</span><span class="op">=</span><span class="va">$(</span><span class="ex">cabal</span> list-bin haskell-foreign-framework<span class="va">)</span></span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a><span class="bu">popd</span> <span class="op">&gt;</span> /dev/null</span></code></pre></div>
<p>and to what is written to <code>DynamicBuildSettings.xcconfig</code> add the following line</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="va">LIBRARY_SEARCH_PATHS</span><span class="op">=</span><span class="dt">\$</span><span class="kw">(</span><span class="ex">inherit</span><span class="kw">)</span> <span class="va">$(</span><span class="fu">dirname</span> <span class="va">$FLIB_PATH)</span></span></code></pre></div>
<p>At this point, after regenerating the dynamic build settings, you should be able
to link the application successfully, and run it.</p>
<h2 data-number="1.4" id="the-rts-must-be-initialized"><span class="header-section-number">1.4</span> The RTS must be initialized</h2>
<p>Surprise! Running the application will fail at runtime, when <code>hs_factorial</code> is
called. To call Haskell functions from an executable written in another language,
one must first initialize the GHC runtime system, and terminate it when
appropriate. We need to call the functions <code>hs_init</code> and <code>hs_end</code>, exposed in
<code>HsFFI.h</code>. We will write two wrapper functions in our foreign library to invoke
instead, as suggested in the <a href="https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/ffi.html#using-the-ffi-with-ghc">FFI chapter of the GHC user guide</a>.</p>
<p>We create a <code>cbits</code> folder in the <code>haskell-framework</code> Haskell project to put our
C files and headers, and add them to the <code>foreign-library</code> stanza of the cabal
file:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>include<span class="op">-</span>dirs<span class="op">:</span> cbits</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>c<span class="op">-</span>sources<span class="op">:</span> cbits<span class="op">/</span>MyForeignLibRts.c</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>install<span class="op">-</span>includes<span class="op">:</span> MyForeignLibRts.h</span></code></pre></div>
<p>You can see what these options do in <a href="https://cabal.readthedocs.io/en/stable/cabal-package.html#pkg-field-includes">this cabal user guide section</a>.
We create <code>cbits/MyForeignLibRts.c</code> wrapping the calls to <code>hs_init</code> and
<code>hs_end</code> as described in the FFI chapter linked above:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;stdlib.h&gt;</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;stdio.h&gt;</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;HsFFI.h&gt;</span></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a>HsBool flib_init<span class="op">()</span> <span class="op">{</span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a>    printf<span class="op">(</span><span class="st">&quot;Initialising flib</span><span class="sc">\n</span><span class="st">&quot;</span><span class="op">);</span></span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a>    <span class="co">// Initialise Haskell runtime</span></span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a>    hs_init<span class="op">(</span>NULL<span class="op">,</span> NULL<span class="op">);</span></span>
<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a>    <span class="co">// Do other library initialisations here</span></span>
<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> HS_BOOL_TRUE<span class="op">;</span></span>
<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a><span class="dt">void</span> flib_end<span class="op">()</span> <span class="op">{</span></span>
<span id="cb21-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a>    printf<span class="op">(</span><span class="st">&quot;Terminating flib</span><span class="sc">\n</span><span class="st">&quot;</span><span class="op">);</span></span>
<span id="cb21-19"><a href="#cb21-19" aria-hidden="true" tabindex="-1"></a>    hs_exit<span class="op">();</span></span>
<span id="cb21-20"><a href="#cb21-20" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>It might seem that you could <code>foreign import</code> these functions into the Haskell
library and re-export them with <code>foreign export</code>, however, if they are exported
from Haskell, they themselves require the RTS to be initialised, effectively
defeating the purpose of being functions that initialise the RTS. Therefore, we
write a header file that we ship with the library for it to be included by the
Swift project. The file <code>cbits/MyForeignLibRts.h</code> contains:</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;HsFFI.h&gt;</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a>HsBool flib_init<span class="op">();</span></span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a><span class="dt">void</span> flib_end<span class="op">();</span></span></code></pre></div>
<p>Back to the Swift side, we need to augment our module map with a module mapping
to the RTS initialisation wrapper header. We add a second submodule declaration:</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a>explicit <span class="kw">module</span> <span class="dt">RTSManage</span> {</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a>   header <span class="st">&quot;haskell-framework/cbits/MyForeignLibRts.h&quot;</span></span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<p>The <code>cbits/MyForeignLibRts.c</code> symbols will be included in the shared dynamic
library.</p>
<p>You can re-buid the haskell library and re-generate the dynamic settings with a
script <code>./build-haskell</code> in the root of the XCode project:</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="co">#!/usr/bin/env bash</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a><span class="bu">set</span> <span class="at">-e</span></span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> <span class="ot">! </span><span class="bu">test</span> <span class="at">-d</span> <span class="st">&quot;SwiftHaskell.xcodeproj&quot;</span><span class="kw">;</span> <span class="cf">then</span></span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a>    <span class="bu">echo</span> <span class="st">&quot;Run this from the SwiftHaskell XCode project root!&quot;</span></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a>    <span class="bu">exit</span> 1</span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a><span class="cf">fi</span></span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-10"><a href="#cb24-10" aria-hidden="true" tabindex="-1"></a><span class="bu">pushd</span> . <span class="op">&gt;</span>/dev/null</span>
<span id="cb24-11"><a href="#cb24-11" aria-hidden="true" tabindex="-1"></a><span class="bu">cd</span> haskell-framework/</span>
<span id="cb24-12"><a href="#cb24-12" aria-hidden="true" tabindex="-1"></a><span class="ex">cabal</span> build all <span class="at">--allow-newer</span></span>
<span id="cb24-13"><a href="#cb24-13" aria-hidden="true" tabindex="-1"></a><span class="ex">./scripts/test-haskell-foreign-lib.sh</span></span>
<span id="cb24-14"><a href="#cb24-14" aria-hidden="true" tabindex="-1"></a><span class="bu">popd</span> <span class="op">&gt;</span>/dev/null</span>
<span id="cb24-15"><a href="#cb24-15" aria-hidden="true" tabindex="-1"></a><span class="ex">./haskell-framework/scripts/gen-dynamic-settings.sh</span></span>
<span id="cb24-16"><a href="#cb24-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-17"><a href="#cb24-17" aria-hidden="true" tabindex="-1"></a><span class="bu">echo</span> <span class="st">&quot;Done.&quot;</span></span>
<span id="cb24-18"><a href="#cb24-18" aria-hidden="true" tabindex="-1"></a></span></code></pre></div>
<p>Finally, in <code>SwiftHaskellApp.swift</code>, we extend the <code>@main</code> <code>App</code> by overriding
the <code>init()</code> function: calling <code>flib_init()</code> to initialise the runtime system
and setting up an observer to call <code>flib_end()</code> to end the runtime system when
the application terminates. We need only import <code>HaskellFramework.RTSManage</code> to
bring these functions into scope:</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode swift"><code class="sourceCode swift"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="at">@main</span></span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> SwiftHaskellApp<span class="op">:</span> <span class="dt">App</span> <span class="op">{</span></span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">init</span><span class="op">()</span> <span class="op">{</span></span>
<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a>        flib_init<span class="op">()</span></span>
<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-7"><a href="#cb25-7" aria-hidden="true" tabindex="-1"></a>        NotificationCenter<span class="op">.</span><span class="kw">default</span><span class="op">.</span>addObserver<span class="op">(</span>forName<span class="op">:</span> NSApplication<span class="op">.</span>willTerminateNotification<span class="op">,</span> object<span class="op">:</span> <span class="kw">nil</span><span class="op">,</span> queue<span class="op">:</span> <span class="op">.</span>main<span class="op">)</span> <span class="op">{</span> _ <span class="cf">in</span></span>
<span id="cb25-8"><a href="#cb25-8" aria-hidden="true" tabindex="-1"></a>            <span class="co">// terminating</span></span>
<span id="cb25-9"><a href="#cb25-9" aria-hidden="true" tabindex="-1"></a>            flib_end<span class="op">()</span></span>
<span id="cb25-10"><a href="#cb25-10" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
<span id="cb25-11"><a href="#cb25-11" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb25-12"><a href="#cb25-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-13"><a href="#cb25-13" aria-hidden="true" tabindex="-1"></a>    <span class="op">...</span></span>
<span id="cb25-14"><a href="#cb25-14" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>Running your application should work and proudly print <code>120</code> on the screen.</p>
<h1 data-number="2" id="remarks"><span class="header-section-number">2</span> Remarks</h1>
<p>We’ve come to the end of the first installment in this blogpost series.
Next up is communicating more interesting data types (both with and without
marshalling), making things more ergonomic to use, SwiftUI observation, iOS
compilation, and perhaps developing a simple model app.</p>
<p>The
<a href="https://github.com/alt-romes/haskell-x-swift-project-steps">haskell-x-swift-project-steps</a>
git repository has a commit matching each of the steps of this guide, so if
anything is unclear you can just let the code speak by itself in checking the
commits.</p>
<p>This project, blog post, and research regarding Swift interoperability with
Haskell is being partially sponsored by <a href="https://well-typed.com/">Well-Typed</a>,
and is otherwise carried out in my own free time. If you’d also like to sponsor my
work on Swift x Haskell interoperability with the goal of developing native
macOS/iOS/etc applications, visit <a href="https://github.com/sponsors/alt-romes">my GitHub sponsors
page</a>.</p>
<h2 data-number="2.1" id="further-reading"><span class="header-section-number">2.1</span> Further Reading</h2>
<ul>
<li><a href="https://github.com/nanotech/swift-haskell-tutorial/tree/master">swift-haskell-tutorial by nanotech</a></li>
<li><a href="https://www.hobson.space/posts/haskell-foreign-library/">Haskell foreign library and options: standalone</a></li>
<li><a href="https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/ffi.html#using-the-ffi-with-ghc">Using the FFI with GHC</a></li>
<li><a href="https://nshipster.com/xcconfig/">xcconfig by NSHipster</a></li>
<li><a href="https://clang.llvm.org/docs/Modules.html">Clang module</a></li>
<li><a href="https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/RunpathDependentLibraries.html">Run-path dependent libraries</a></li>
<li><a href="https://cabal.readthedocs.io/en/stable/">Cabal user guide</a></li>
</ul>
]]></summary>
</entry>
<entry>
    <title>Introducing ghc-toolchain to GHC</title>
    <link href="http://alt-romes.github.io/posts/2023-10-02-ghc-toolchain.html" />
    <id>http://alt-romes.github.io/posts/2023-10-02-ghc-toolchain.html</id>
    <published>2023-10-02T00:00:00Z</published>
    <updated>2023-10-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#compiler-toolchains" id="toc-compiler-toolchains"><span class="toc-section-number">1</span> Compiler Toolchains</a></li>
<li><a href="#the-runtime-retargetable-future-of-ghc" id="toc-the-runtime-retargetable-future-of-ghc"><span class="toc-section-number">2</span> The runtime-retargetable future of GHC</a></li>
<li><a href="#introducing-ghc-toolchain" id="toc-introducing-ghc-toolchain"><span class="toc-section-number">3</span> Introducing <code>ghc-toolchain</code></a></li>
<li><a href="#migration-to-ghc-toolchain" id="toc-migration-to-ghc-toolchain"><span class="toc-section-number">4</span> Migration to <code>ghc-toolchain</code></a></li>
<li><a href="#future-work" id="toc-future-work"><span class="toc-section-number">5</span> Future work</a></li>
<li><a href="#conclusion" id="toc-conclusion"><span class="toc-section-number">6</span> Conclusion</a></li>
</ul>
</div>
<p>GHC, like most high-level language compilers, depends upon a set of tools like
assemblers, linkers, and archivers for the production of machine code.
Collectively these tools are known as a <em>toolchain</em> and capture a great deal of
platform-dependent knowledge.</p>
<p>Traditionally, developers generate a <code>./configure</code> script using the venerable
<a href="https://www.gnu.org/software/autoconf/"><code>autoconf</code></a> tool,
then users execute this script
when they install a GHC binary distribution. The <code>./configure</code> script
determines the location of programs (such as the C compiler) and which options GHC
will need to pass them.</p>
<p>While this <code>autoconf</code>-centric model of toolchain configuration has served GHC well,
it has two key issues:</p>
<ul>
<li><p>For cross-compiling to a different platform, it would be highly valuable to
users if GHC would become a <em>runtime-retargetable</em> compiler (like <code>rustc</code> and
<code>go</code>). That is, the user should be able to download a single GHC binary
distribution and use it to compile not only for their local machine, but also
any other targets that GHC supports.</p></li>
<li><p>The ten-thousand-line <code>sh</code> file that is GHC’s <code>./configure</code> script has
historically been challenging to maintain and test. Modifications to the
<code>./configure</code> script are among the most risky changes routinely made
to the compiler, because it is easy to introduce a bug on some specific
toolchain configuration, and infeasible to test all possible configurations
in CI.</p></li>
</ul>
<p>To address these issues, we are introducing <code>ghc-toolchain</code>, a new way to
configure the toolchain for GHC, which will
eventually replace the existing toolchain configuration logic in the
<code>./configure</code> script.
Its main goal is to allow new compilation toolchains to be configured for GHC at
any point in time, notably after the compiler has been installed.
For example, calling <code>ghc-toolchain --triple=x86_64-w64-mingw32</code> will configure a
compilation toolchain on the host machine capable of producing code for
an x86_64 machine running Windows using MinGW.
This is an important step towards making GHC runtime-retargetable, and since
<code>ghc-toolchain</code> is implemented in Haskell, it will be much easier to modify
and test than the <code>./configure</code> script.</p>
<p>In this post we explain in more detail how GHC interacts with the system toolchain and how
<code>ghc-toolchain</code> facilitates our future goal of making GHC a runtime-retargetable
compiler.</p>
<blockquote>
<p>This post was a result from my internship with the GHC team at Well-Typed this summer. It
was originally made available in the <a href="https://well-typed.com/blog/2023/10/improving-ghc-configuration-and-cross-compilation-with-ghc-toolchain/">Well-Typed Blog</a>.
I’m very grateful to Matthew, Ben, Sam, and Andreas for mentoring me
throughout my internship and reviewing previous iteration of this post. It
wouldn’t have been possible to complete this project without Ben Gamari’s help
– Ben wrote the first draft of ghc-toolchain and guided me through many
weird but interesting toolchain quirks and toolchain configuration bugs while
developing ghc-toolchain to its full mergeable extent in GHC.</p>
</blockquote>
<h2 data-number="1" id="compiler-toolchains"><span class="header-section-number">1</span> Compiler Toolchains</h2>
<!-- more -->
<p>GHC cannot produce executables from Haskell programs in isolation – it requires
a correctly configured toolchain to which it can delegate some responsibilities. For
example, GHC’s <a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/codegens.html#native-code-generator-fasm">native code generator
backend</a>
is capable of generating assembly code from a Haskell program, however,
producing object code from that assembly, and linking the objects into an
executable, are all tasks done by the compilation toolchain, which is invoked by
GHC using the flags that were configured for it.</p>
<p>Configuring a compiler toolchain is about locating the set of tools required for
compilation, the base set of flags required to invoke each tool, and properties
of these tools. For example, this might include:</p>
<ul>
<li>determining various characteristics of the platform (e.g. the word size).</li>
<li>probing to find which tools are available (the C compiler, linker,
archiver, object merging tool, etc.),</li>
<li>identifying which flags GHC should pass to each of these tools,</li>
<li>determining whether the tools support response files to work around command-line length limits, and</li>
<li>checking for and working around bugs in the toolchain.</li>
</ul>
<p>At the moment, when a GHC binary distribution is installed, the <code>./configure</code>
script will perform the above steps and store the results in a <code>settings</code> file.
GHC will then read this file so it can correctly invoke the toolchain programs
when compiling Haskell executables.</p>
<p>To cross-compile a Haskell program, a user must build GHC from source as a
cross-compiler (see the <a href="https://gitlab.haskell.org/ghc/ghc/-/wikis/building/cross-compiling">GHC wiki</a>).
This requires configuring a cross-compilation
toolchain, that is, a toolchain that runs on the machine compiling the Haskell
program but that produces executables to run on a different system. It is currently a rather involved process.</p>
<h2 data-number="2" id="the-runtime-retargetable-future-of-ghc"><span class="header-section-number">2</span> The runtime-retargetable future of GHC</h2>
<p>A key long-term goal of this work is to allow GHC to become <em>runtime-retargetable</em>.
This means being able to call <code>ghc --target=aarch64-apple-darwin</code> and have GHC
output code for an AArch64 machine, or call <code>ghc --target=javascript-ghcjs</code> to generate Javascript code, regardless of the platform <code>ghc</code> is being invoked on.</p>
<p>Crucially, this requires the configuration step to be
<em>repeated</em> at a later point, rather than only when the GHC binary distribution
is installed. Once GHC is fully runtime-retargetable, this will allow you to use
multiple different toolchains, potentially targeting different platforms, with
the same installed compiler.</p>
<ul>
<li><p>At the simplest level, you might just have two different toolchains for your host
platform (for example, a <code>gcc</code>-based toolchain and a <code>clang</code>-based toolchain), or
you might just configure a toolchain which uses the new <a href="https://github.com/rui314/mold"><code>mold</code></a> linker rather than <code>ld.gold</code>.</p></li>
<li><p>In a more complex scenario, you may have a normal compiler toolchain as well as
several different cross-compiler toolchains. For example, a toolchain which produces Javascript,
a toolchain which produces WebAssembly, a toolchain which produces AArch64 object code and so on.</p></li>
</ul>
<p>The idea is that the brand new <code>ghc-toolchain</code> will be called once to configure the toolchain
that GHC will use when compiling for a target, then <code>ghc --target=&lt;triple&gt;</code> can
be called as many times as needed. For example, if you have an x86 Linux machine
and wish to produce code for AArch64 devices, the workflow could look something
like:</p>
<pre><code># Configure the aarch64-apple-darwin target first
# (We only need to do this once!)
ghc-toolchain --triple=aarch64-apple-darwin --cc-opt=&quot;-I/some/include/dir&quot; --cc-linker-opt=&quot;-L/some/library/dir&quot;

# Now we can target aarch64-apple-darwin (as many times as we&#39;d like!)
ghc --target=aarch64-apple-darwin -o MyAwesomeTool MyAwesomeTool.hs
ghc --target=aarch64-apple-darwin -o CoolProgram CoolProgram.hs</code></pre>
<h2 data-number="3" id="introducing-ghc-toolchain"><span class="header-section-number">3</span> Introducing <code>ghc-toolchain</code></h2>
<p><code>ghc-toolchain</code> is a standalone tool for configuring a toolchain.
It receives as input a <a href="https://wiki.osdev.org/Target_Triplet">target triplet</a>
(e.g. <code>x86_64-deb10-linux</code>) and user options, discovers the configuration, and
outputs a “target description” (<code>.target</code> file) containing the configured
toolchain.</p>
<p>At the moment, <code>.target</code> files generated by <code>ghc-toolchain</code> can be used by GHC’s
build system (Hadrian) by invoking <code>./configure</code> with
<code>--enable-ghc-toolchain</code>. Otherwise, Hadrian reads the configuration from a
<code>.target</code> file generated by <code>./configure</code> itself.</p>
<p>In the future, <code>ghc-toolchain</code> will be shipped in binary distributions to allow
new toolchains to be added after the compiler is installed (generating new
<code>.target</code> files). GHC will then be able to choose the <code>.target</code> file for the
particular target requested by the user.</p>
<p>From a developer standpoint, <code>ghc-toolchain</code> being written in Haskell makes it
easier to modify in future, especially when compared to the notoriously
difficult to write and debug <code>./configure</code> scripts.</p>
<h2 data-number="4" id="migration-to-ghc-toolchain"><span class="header-section-number">4</span> Migration to <code>ghc-toolchain</code></h2>
<p>We are migrating to <code>ghc-toolchain</code> in a staged manner, since toolchain configuration
logic is amongst the most sensitive things to change in the compiler.
We want to ensure that the configuration logic in
<code>ghc-toolchain</code> is correct and agrees with the logic in
<code>./configure</code>. Therefore, in GHC 9.10 <code>ghc-toolchain</code> will be shipped
and validated but not enabled by default.</p>
<p>To validate <code>ghc-toolchain</code>, GHC will generate <code>.target</code> files with both <code>./configure</code> and
<code>ghc-toolchain</code> and compare the outputs against each other, emitting a warning if they differ.
This means we will be able to catch mistakes in
<code>ghc-toolchain</code> (and in <code>./configure</code> too!) before we make <code>ghc-toolchain</code> the default
method for configuring toolchains in a subsequent release. This mechanism has already identified
<a href="https://gitlab.haskell.org/ghc/ghc/-/issues/?label_name%5B%5D=ghc-toolchain">plenty of issues to resolve</a>.</p>
<!-- There's also a `Note [ghc-toolchain overview]` in -->
<!-- `utils/ghc-toolchain/src/GHC/Toolchain.hs` -->
<h2 data-number="5" id="future-work"><span class="header-section-number">5</span> Future work</h2>
<p>Despite <code>ghc-toolchain</code> bringing us closer to a runtime-retargetable GHC, there
is still much work left to be done (see
<a href="https://gitlab.haskell.org/ghc/ghc/-/issues/11470">#11470</a>).
The next step is to instruct GHC
to choose between multiple available <code>.target</code> files at runtime, instead of
reading the usual <code>settings</code> file (tracked in <a href="https://gitlab.haskell.org/ghc/ghc/-/issues/23682">#23682</a>).</p>
<p>Beyond that, however, there are many open questions still to resolve:</p>
<ul>
<li>How will the runtime system, and core libraries such as <code>base</code>, be provided
for the multiple selected targets?</li>
<li>How will this fit into <code>ghcup</code>’s installation story?</li>
<li>How will <code>cabal</code> handle multiple targets?</li>
</ul>
<p>At the moment, binary distributions include the RTS/libraries already compiled
for a single target. Instead, we are likely to need some mechanism for users to
recompile the RTS/libraries when they configure a new target, or to download
ready-built versions from upstream.</p>
<p>Moreover, accommodating <code>TemplateHaskell</code> under runtime retargetability is particularly
nontrivial, and needs more design work.</p>
<h2 data-number="6" id="conclusion"><span class="header-section-number">6</span> Conclusion</h2>
<p><code>ghc-toolchain</code> is a new tool for configuring toolchains and targets. It
improves on GHC’s existing <code>./configure</code>-based configuration workflow by allowing multiple targets’ toolchains
to be configured at any time, and by making maintenance and future updates to
the toolchain configuration logic much easier.
However, toolchain configuration is a challenging part of the compiler, so we’re
being conservative in migrating to <code>ghc-toolchain</code>, and carefully validating it
before making it the default.</p>
<p>Moreover, <code>ghc-toolchain</code> is an important step towards making a runtime-retargetable
GHC a reality, though there is still much work left to do.
We are grateful to all the GHC developers involved in working towards runtime-retargetability.</p>
<p>Well-Typed is able to work on GHC, HLS, Cabal and other core Haskell
infrastructure thanks to funding from various sponsors. If your company might be
able to contribute to this work, sponsor maintenance efforts, or fund the
implementation of other features, please
<a href="/blog/2022/11/funding-ghc-maintenance">read about how you can help</a> or
<a href="mailto:info@well-typed.com">get in touch</a>.</p>
]]></summary>
</entry>
<entry>
    <title>Writing prettier Haskell with Unicode Syntax and Vim</title>
    <link href="http://alt-romes.github.io/posts/2023-06-21-haskell-unicode-syntax-vim.html" />
    <id>http://alt-romes.github.io/posts/2023-06-21-haskell-unicode-syntax-vim.html</id>
    <published>2023-06-21T00:00:00Z</published>
    <updated>2023-06-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#haskells-unicode-syntax-extension" id="toc-haskells-unicode-syntax-extension"><span class="toc-section-number">1</span> Haskell’s Unicode Syntax Extension</a></li>
<li><a href="#digraphs-in-vim" id="toc-digraphs-in-vim"><span class="toc-section-number">2</span> Digraphs in Vim</a></li>
<li><a href="#conclusion" id="toc-conclusion"><span class="toc-section-number">3</span> Conclusion</a></li>
</ul>
</div>
<h1 data-number="1" id="haskells-unicode-syntax-extension"><span class="header-section-number">1</span> Haskell’s Unicode Syntax Extension</h1>
<p>Haskell (well, GHC Haskell) features an extension called <code>UnicodeSyntax</code>. When
enabled, this extension allows the use of certain unicode symbols in place of
their corresponding keywords. A great example is the <code>forall</code> keyword being
equivalent to the unicode symbol <code>∀</code>, the two of which can be used
interchangebly when <code>UnicodeSyntax</code> is enabled.</p>
<p>Furthermore, with Haskell being a unicode-friendly language, one can define
common Haskell functions, operators or type variables using unicode symbols –
which doesn’t even require <code>UnicodeSyntax</code> to be enabled. For example, one can
define the predicate <code>∈</code> on lists as an alias for <code>elem</code> as follows:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- 5 ∈ [1,3,5] == True</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>(∈)<span class="ot"> ::</span> ∀ α<span class="op">.</span> <span class="dt">Eq</span> α <span class="ot">=&gt;</span> α <span class="ot">-&gt;</span> [α] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>(∈) <span class="ot">=</span> <span class="fu">elem</span></span></code></pre></div>
<p>In practice, I use just a handful of unicode symbols both as keywords and as
identifiers, but a mostly comprehensive list of the keywords that have unicode
alternatives is presented in the GHC user’s guide <a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/unicode_syntax.html"><code>UnicodeSyntax</code> extension
page</a>.
Specifically, in most of my programs you can be sure to find the following:</p>
<ul>
<li><code>∀</code> instead of <code>forall</code>, which is faster to input than the whole word.</li>
<li>A lot of unicode type variables, <code>α</code>, <code>β</code>, <code>τ</code>, <code>σ</code>, <code>δ</code>, <code>κ</code>, <code>ρ</code> – they are
really easy to type too.</li>
<li><code>⊸</code> instead of <code>%1 -&gt;</code>, to use the so-called “lollipop” notation for linear
functions.
<!-- , which is read "lollipop" rather than "what the h★ll" --></li>
</ul>
<p>In my opinion, those are low-hanging niceties (with vim) that make the program
look better overall, but there are others that I haven’t yet reached for
which you may still find good/useful. For example, there’s a library in
hackage, <a href="https://hackage.haskell.org/package/containers-unicode-symbols">containers-unicode-symbols</a>,
which exposes multiple unicode variants of functions on containers
(<code>Map</code>s,<code>Set</code>s,…) such as <code>∈</code>,<code>∉</code>,<code>∅</code>,<code>∪</code>,<code>∩</code>,<code>⊆</code>,<code>⊈</code>.</p>
<p>Finally, I usually add <code>default-extensions: UnicodeSyntax</code> to my cabal
file to make the extension available by default on all modules. However, you can
also enable it on a per module basis as usual with <code>{-# LANGUAGE UnicodeSyntax #-}</code> at the top of the module.</p>
<h1 data-number="2" id="digraphs-in-vim"><span class="header-section-number">2</span> Digraphs in Vim</h1>
<p>To experiment with <code>UnicodeSyntax</code>, or if you’re already convinced that using
unicode symbols makes the programs nicer to look at, all that’s left is to be
able to input these symbols easily.
Vim has a built-in feature called <em>digraphs</em> that makes inputting unicode
symbols a joy. The feature is called <em>digraphs</em> because it maps combinations of
exactly two letters to a unicode symbol (see also <code>:help digraph</code>).</p>
<p>To input a digraph, in <span class="smallcaps">insert mode</span>, press
<kbd>Ctrl</kbd>+<kbd>k</kbd> followed by the two letters which define the digraph.
Here are a few useful, <em>built-in</em>, combinations:</p>
<ul>
<li><kbd>Ctrl-k</kbd>+<kbd>FA</kbd> inputs <code>∀</code>.</li>
<li><kbd>Ctrl-k</kbd>+
<ul>
<li><kbd>a*</kbd> inputs <code>α</code>.</li>
<li><kbd>b*</kbd> inputs <code>β</code>.</li>
<li><kbd>t*</kbd> inputs <code>τ</code>.</li>
<li>In general, <kbd>Ctrl-k</kbd>+<kbd>letter</kbd>+<kbd>*</kbd> inputs the greek letter variant
of that letter</li>
</ul></li>
<li><kbd>Ctrl-k</kbd>+<kbd>(-</kbd> inputs <code>∈</code>.</li>
<li><kbd>Ctrl-k</kbd>+<kbd>::</kbd> inputs <code>∷</code>.</li>
<li><kbd>Ctrl-k</kbd>+<kbd>=&gt;</kbd> inputs <code>⇒</code>.</li>
<li><kbd>Ctrl-k</kbd>+<kbd>-&gt;</kbd> inputs <code>→</code>.</li>
<li><kbd>Ctrl-k</kbd>+<kbd>TE</kbd> inputs <code>∃</code>.</li>
</ul>
<!-- ## Custom Digraphs -->
<p>Besides the built-in ones, it’s <em>very</em> useful to define your own digraphs. Both
for customization/personalization and ergonomics, but also to introduce digraphs
which simply do not exist by default.</p>
<p>To create a digraph, use the <code>digraph</code> VimScript keyword with the two characters
that input it, and the decimal numeric representation of the Unicode character
it is mapped to. In the following <code>.vimrc</code> snippet, I defined the digraph <code>ll</code>
with <code>8888</code> (the unicode decimal representation of ⊸), which effectively maps
<kbd>Ctrl-k</kbd>+<kbd>ll</kbd> to <code>⊸</code>.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>digraph ll <span class="dv">8888</span> <span class="st">&quot; ⊸</span></span></code></pre></div>
<h1 data-number="3" id="conclusion"><span class="header-section-number">3</span> Conclusion</h1>
<p>Concluding, vim makes it really easy, through <em>digraphs</em>, to input unicode
symbols which are understood by Haskell, and even more so with its
<code>UnicodeSyntax</code> extension. Combining these features we can easily write more beautiful
Haskell programs. I’d argue it’s as fast to write</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">lid ::</span> ∀ α<span class="op">.</span> α ⊸ α</span></code></pre></div>
<p>as it is to write</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">lid ::</span> <span class="kw">forall</span> a<span class="op">.</span> a <span class="op">%</span><span class="dv">1</span> <span class="ot">-&gt;</span> a</span></code></pre></div>
<p>while the former is arguably more aesthetically pleasing.</p>
]]></summary>
</entry>
<entry>
    <title>Monthly Update on a Haskell Game Engine</title>
    <link href="http://alt-romes.github.io/posts/2023-01-01-monthly-update-on-a-haskell-game-engine.html" />
    <id>http://alt-romes.github.io/posts/2023-01-01-monthly-update-on-a-haskell-game-engine.html</id>
    <published>2023-01-01T00:00:00Z</published>
    <updated>2023-01-01T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#ghengin" id="toc-ghengin"><span class="toc-section-number">1</span> Ghengin</a>
<ul>
<li><a href="#bullets-on-technical-details" id="toc-bullets-on-technical-details"><span class="toc-section-number">1.1</span> Bullets on Technical Details</a></li>
<li><a href="#the-small-victories" id="toc-the-small-victories"><span class="toc-section-number">1.2</span> The Small Victories</a></li>
<li><a href="#a-peek-into-the-code" id="toc-a-peek-into-the-code"><span class="toc-section-number">1.3</span> A peek into the code</a></li>
</ul></li>
</ul>
</div>
<h1 data-number="1" id="ghengin"><span class="header-section-number">1</span> Ghengin</h1>
<p>I’ve been working the past month or two in a game engine titled
<a href="https://github.com/alt-romes/ghengin"><code>Ghengin</code></a> (pronounced /ɡɛn-ʤɪn/, never /ɡɛn-ɡɪn/). This is not yet a release,
and version 0.1.0 is far into the future. However, I’ve come a long way and I’d
like to share a few pictures of my progress. This post was migrated from the
discussion at the <a href="https://discourse.haskell.org/t/monthly-update-on-a-haskell-game-engine/5515?u=romes">Haskell Discourse</a></p>
<!-- It is my belief that shaders -->
<!-- should be more of a centerpiece in beginner and intermediate-level game -->
<!-- development. -->
<p>The demo I’ve been working on is based on Sebastian Lague’s series <a href="https://www.youtube.com/playlist?list=PLFt_AvWsXl0cONs3T0By4puYy6GM22ko8">Procedural Planets</a>.
It is a showcase of procedurally generated planets you can move around in and
tweak the procedural generation parameters of the planets to create oceans and
continents.</p>
<figure>
<img src="/images/ghengin/devlog8.jpeg" alt="Fig 1. Screenshot of planets demo" />
<figcaption aria-hidden="true">Fig 1. Screenshot of planets demo</figcaption>
</figure>
<h2 data-number="1.1" id="bullets-on-technical-details"><span class="header-section-number">1.1</span> Bullets on Technical Details</h2>
<p>I hope to, soon enough, write a more substantial explanation of the engine’s
technical challenges and overall design decisions so far, and on the game
developer’s facing side of the engine. In the meantime, here are a few key
points regarding the technical feats of the engine along with the main libraries
it currently depends on, which help create a picture of how it is working:</p>
<ul>
<li><p>The renderer is written using the <a href="https://hackage.haskell.org/package/vulkan">great bindings to the Vulkan API</a></p></li>
<li><p>The shaders are crucial in the overall design, and a lot of code depends on
their definition (e.g. preparing render pipelines, allocating descriptor sets
and textures, everything materials related …). The shaders are written using
<a href="https://gitlab.com/sheaf/fir">FIR</a>, an amazing shader language embedded in
Haskell!</p></li>
<li><p>The entity management, scene graph and render queue are done/created through
the <a href="https://hackage.haskell.org/package/apecs-0.9.4">apecs</a> entity component
system.</p></li>
<li><p>Vectors and matrices are from <a href="https://hackage.haskell.org/package/geomancy-0.2.4.1">geomancy</a></p></li>
<li><p><a href="https://hackage.haskell.org/package/GLFW-b">GLFW-b</a> for window management and
user input (used as the window backend for vulkan)</p></li>
<li><p>The <a href="https://hackage.haskell.org/package/dear-imgui">dear-imgui bindings</a> for the GUI</p></li>
<li><p><a href="https://hackage.haskell.org/package/JuicyPixels-3.3.8">JuicyPixels</a> for loading textures</p></li>
</ul>
<p><a href="https://gitlab.com/sheaf/fir">FIR</a> is a really cool shader library and unlike
any you’ve likely tried before (it’s embeded in Haskell, but that’s just the
start). The shader’s “interfaces” are defined at the type level, and in
<code>ghengin</code> that type information is used to validate the
game-developer-defined-materials. In short, if you define materials incompatible
with your shaders, the program will fail at compile time</p>
<h2 data-number="1.2" id="the-small-victories"><span class="header-section-number">1.2</span> The Small Victories</h2>
<p>To give a general sense of progress, I put together a small roadmap of victories
attained while developing the engine, both in words and in screenshots.</p>
<ul>
<li><p>The very first achievement was rendering a triangle (Fig. 2). This is a given
classic in graphics programming.</p></li>
<li><p>Then, I rendered a simple cube and was able to rotate it with a simple model
transform matrix (Fig. 3).</p></li>
<li><p>Later, I got a perspective camera which could move around the world. I was
generating spheres at this point and the colors show that I was getting closer
to generating the normals right too (Fig. 4).</p></li>
<li><p>I managed to integrate dear-imgui into the renderer after that, and even
fixed upstream a dreaded <a href="https://github.com/haskell-game/dear-imgui.hs/pull/166">off by one error</a> which kept making
the GUI behave funny and crash. I was also experimenting with simple diffuse
lighting here (Fig. 5).</p></li>
<li><p>With the GUI in place, I started focusing on developing planets by generating
single sphere and modifying the height value of each point on the sphere by
noise value: generating terrain and mountains (Fig. 6).</p></li>
<li><p>After the terrain generation I spent some long weeks on the internals of the
renderer before achieving more visual results with the exception of the
following color-based-on-height-relative-to-min-and-max-heights planet (Fig. 7).
Those weeks were spent in internal technical challenges which I hope to
describe on a subsequent post with the resulting design and implementation
(and hopefully avoid to some extent the arduous process of understanding and
reaching a design and implementation).</p></li>
<li><p>This week, with the material system working great for a first iteration, I spent
finally some more time on the procedural planets: I added specular highlights to
the lighting model (using the blinn-phong model) and added a (gradient based)
texture to the planet that is sampled according to the height of each point in
the planet. The result is a nicely lit planet with colors depending on the
height: lower height -&gt; blue for water, middle -&gt; green for grass, higher -&gt; brown for mountains (Fig. 8).</p></li>
</ul>
<style>
.showcase {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
@media only screen and (min-width: 768px) {
    .showcase > figure {
        width: 40%;
    }
}

.showcase img {
    width: 25rem;
    height: 16rem;
}
</style>
<div class="showcase">
<figure>
<img src="/images/ghengin/devlog2.jpeg" alt="Fig 2. Hello World! - Rendering a triangle" />
<figcaption aria-hidden="true">Fig 2. Hello World! - Rendering a triangle</figcaption>
</figure>
<figure>
<img src="/images/ghengin/devlog3.jpeg" alt="Fig 3. Rendering a rotating cube" />
<figcaption aria-hidden="true">Fig 3. Rendering a rotating cube</figcaption>
</figure>
<figure>
<img src="/images/ghengin/devlog4.jpeg" alt="Fig 4. A moving camera and some broken spheres" />
<figcaption aria-hidden="true">Fig 4. A moving camera and some broken spheres</figcaption>
</figure>
<figure>
<img src="/images/ghengin/devlog5.jpeg" alt="Fig 5. DearImGUI and simple diffuse lighting" />
<figcaption aria-hidden="true">Fig 5. DearImGUI and simple diffuse lighting</figcaption>
</figure>
<figure>
<img src="/images/ghengin/devlog6.jpeg" alt="Fig 6. The very first planets" />
<figcaption aria-hidden="true">Fig 6. The very first planets</figcaption>
</figure>
<figure>
<img src="/images/ghengin/devlog7.jpeg" alt="Fig 7. The height influences the color" />
<figcaption aria-hidden="true">Fig 7. The height influences the color</figcaption>
</figure>
<figure>
<img src="/images/ghengin/devlog1.jpeg" alt="Fig 8. Texture sampling based on the color!" />
<figcaption aria-hidden="true">Fig 8. Texture sampling based on the color!</figcaption>
</figure>
</div>
<h2 data-number="1.3" id="a-peek-into-the-code"><span class="header-section-number">1.3</span> A peek into the code</h2>
<p>Unfortunately, I don’t expect it to be useful without a proper explanation, but
nonetheless I’ll present a small snippet of the Main module of the procedural
planets game. Additionally, the <a href="https://github.com/alt-romes/ghengin">full source is avaliable</a><a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> – that’s
also where engine development is happening. The next feature I’ve just completed,
at the time of writing, is a gradient editor for the in game GUI (Fig. 1).</p>
<p>As promised, here’s a quick look at the Main module of the procedural planets game:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="ot">initG ::</span> <span class="dt">Ghengin</span> <span class="dt">World</span> ()</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>initG <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Planet settings used to generate the planet and which are edited through the UI</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>  ps <span class="ot">&lt;-</span> makeSettings <span class="op">@</span><span class="dt">PlanetSettings</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>  (planetMesh,minmax) <span class="ot">&lt;-</span> newPlanet ps</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Load the planet gradient texture</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>  sampler <span class="ot">&lt;-</span> createSampler <span class="dt">FILTER_NEAREST</span> <span class="dt">SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>  tex         <span class="ot">&lt;-</span> texture <span class="st">&quot;assets/planet_gradient.png&quot;</span> sampler</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Create the render pipeline based on the shader definition</span></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>  planetPipeline <span class="ot">&lt;-</span> makeRenderPipeline Shader.shaderPipeline</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Create a material which will be validated against the render pipeline at compile time</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>  m1 <span class="ot">&lt;-</span> material (<span class="dt">Texture2DBinding</span> tex <span class="op">.</span> <span class="dt">StaticBinding</span> (vec3 <span class="dv">1</span> <span class="dv">0</span> <span class="dv">0</span>) <span class="op">.</span> <span class="dt">StaticBinding</span> minmax) planetPipeline</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Create a render packet with the mesh, material, and pipeline.</span></span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- All entities with a RenderPacket component are rendered according to it.</span></span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> p1 <span class="ot">=</span> renderPacket planetMesh m1 planetPipeline</span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Define our scene graph</span></span>
<span id="cb1-23"><a href="#cb1-23" aria-hidden="true" tabindex="-1"></a>  sceneGraph <span class="kw">do</span></span>
<span id="cb1-24"><a href="#cb1-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-25"><a href="#cb1-25" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- A planet entity, with the planet render packet and a transform</span></span>
<span id="cb1-26"><a href="#cb1-26" aria-hidden="true" tabindex="-1"></a>    e1 <span class="ot">&lt;-</span> newEntity ( p1, <span class="dt">Transform</span> (vec3 <span class="dv">0</span> <span class="dv">0</span> <span class="dv">0</span>) (vec3 <span class="dv">1</span> <span class="dv">1</span> <span class="dv">1</span>) (vec3 <span class="dv">0</span> (<span class="fu">pi</span><span class="op">/</span><span class="dv">2</span>) <span class="dv">0</span>) )</span>
<span id="cb1-27"><a href="#cb1-27" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-28"><a href="#cb1-28" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- A camera</span></span>
<span id="cb1-29"><a href="#cb1-29" aria-hidden="true" tabindex="-1"></a>    newEntity ( <span class="dt">Camera</span> (<span class="dt">Perspective</span> (radians <span class="dv">65</span>) <span class="fl">0.1</span> <span class="dv">100</span>) <span class="dt">ViewTransform</span></span>
<span id="cb1-30"><a href="#cb1-30" aria-hidden="true" tabindex="-1"></a>              , <span class="dt">Transform</span> (vec3 <span class="dv">0</span> <span class="dv">0</span> <span class="dv">0</span>) (vec3 <span class="dv">1</span> <span class="dv">1</span> <span class="dv">1</span>) (vec3 <span class="dv">0</span> <span class="dv">0</span> <span class="dv">0</span>))</span>
<span id="cb1-31"><a href="#cb1-31" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-32"><a href="#cb1-32" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- The planet UI component based on the `ps` settings</span></span>
<span id="cb1-33"><a href="#cb1-33" aria-hidden="true" tabindex="-1"></a>    newEntityUI <span class="st">&quot;Planet&quot;</span>  <span class="op">$</span> makeComponents ps (e1,tex)</span>
<span id="cb1-34"><a href="#cb1-34" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-35"><a href="#cb1-35" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> ()</span>
<span id="cb1-36"><a href="#cb1-36" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-37"><a href="#cb1-37" aria-hidden="true" tabindex="-1"></a><span class="ot">updateG ::</span> () <span class="ot">-&gt;</span> <span class="dt">DeltaTime</span> <span class="ot">-&gt;</span> <span class="dt">Ghengin</span> <span class="dt">World</span> <span class="dt">Bool</span></span>
<span id="cb1-38"><a href="#cb1-38" aria-hidden="true" tabindex="-1"></a>updateG () dt <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb1-39"><a href="#cb1-39" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-40"><a href="#cb1-40" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Every frame we update the first person camera with the user inputs and the planet&#39;s rotation</span></span>
<span id="cb1-41"><a href="#cb1-41" aria-hidden="true" tabindex="-1"></a>  cmapM <span class="op">$</span> \(<span class="ot">_ ::</span> <span class="dt">Camera</span>,<span class="ot"> tr ::</span> <span class="dt">Transform</span>) <span class="ot">-&gt;</span> updateFirstPersonCameraTransform dt tr</span>
<span id="cb1-42"><a href="#cb1-42" aria-hidden="true" tabindex="-1"></a>  cmap <span class="op">$</span> \(<span class="ot">_ ::</span> <span class="dt">RenderPacket</span>,<span class="ot"> tr ::</span> <span class="dt">Transform</span>) <span class="ot">-&gt;</span> (tr{rotation <span class="ot">=</span> withVec3 tr<span class="op">.</span>rotation (\x y z <span class="ot">-&gt;</span> vec3 x (y<span class="op">+</span><span class="fl">0.5</span><span class="op">*</span>dt) z) }<span class="ot"> ::</span> <span class="dt">Transform</span>)</span>
<span id="cb1-43"><a href="#cb1-43" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-44"><a href="#cb1-44" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> <span class="dt">False</span></span>
<span id="cb1-45"><a href="#cb1-45" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-46"><a href="#cb1-46" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb1-47"><a href="#cb1-47" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb1-48"><a href="#cb1-48" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Run the game with this init, update and end function</span></span>
<span id="cb1-49"><a href="#cb1-49" aria-hidden="true" tabindex="-1"></a>  ghengin w initG <span class="fu">undefined</span> updateG endG</span></code></pre></div>
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>If you are curious about the full source of the planets game, beware of dragons
<span class="emoji" data-emoji="slightly_smiling_face">🙂</span>. It is not ready as a learning resource whatsoever.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
]]></summary>
</entry>
<entry>
    <title>Equality Saturation in Haskell, a tutorial</title>
    <link href="http://alt-romes.github.io/posts/2022-08-23-a-first-hegg-tutorial.html" />
    <id>http://alt-romes.github.io/posts/2022-08-23-a-first-hegg-tutorial.html</id>
    <published>2022-08-23T00:00:00Z</published>
    <updated>2022-08-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#symbolic-maths-in-e-graphs" id="toc-symbolic-maths-in-e-graphs"><span class="toc-section-number">1</span> Symbolic Maths in E-graphs</a>
<ul>
<li><a href="#syntax" id="toc-syntax"><span class="toc-section-number">1.1</span> Syntax</a></li>
<li><a href="#language" id="toc-language"><span class="toc-section-number">1.2</span> Language</a></li>
<li><a href="#analysis" id="toc-analysis"><span class="toc-section-number">1.3</span> Analysis</a></li>
</ul></li>
<li><a href="#equality-saturation-on-symbolic-expressions" id="toc-equality-saturation-on-symbolic-expressions"><span class="toc-section-number">2</span> Equality saturation on symbolic expressions</a>
<ul>
<li><a href="#cost-function" id="toc-cost-function"><span class="toc-section-number">2.1</span> Cost function</a></li>
<li><a href="#rewrite-rules" id="toc-rewrite-rules"><span class="toc-section-number">2.2</span> Rewrite rules</a></li>
<li><a href="#equality-saturation-finally" id="toc-equality-saturation-finally"><span class="toc-section-number">2.3</span> Equality saturation, finally</a></li>
</ul></li>
</ul>
</div>
<p><code>hegg</code> is a Haskell-native library providing fast e-graphs and equality
saturation, based on <a href="https://arxiv.org/pdf/2004.03082.pdf"><em>egg: Fast and Extensible Equality
Saturation</em></a> and <a href="https://arxiv.org/pdf/2108.02290.pdf"><em>Relational
E-matching</em></a>.</p>
<p>Suggested material on equality saturation and e-graphs for beginners</p>
<ul>
<li><a href="https://www.youtube.com/watch?v=ap29SzDAzP0">egg: Fast and Extensible Equality Saturation in a 5m video</a></li>
<li><a href="https://docs.rs/egg/latest/egg/tutorials/_01_background/index.html">egg’s users guide</a></li>
</ul>
<p>To get a feel for how we can use <code>hegg</code> and do equality saturation in Haskell,
we’ll write a simple numeric <em>symbolic</em> manipulation library that can simplify expressions
according to a set of rewrite rules by leveraging equality saturation.</p>
<p>I hope to eventually write a better exposition that assumes less prior
knowledge which introduces first e-graphs-only workflows, and only then equality
saturation, from a <code>hegg</code> user’s perspective. Until then, this rough tutorial
serves as an alternative.</p>
<h1 data-number="1" id="symbolic-maths-in-e-graphs"><span class="header-section-number">1</span> Symbolic Maths in E-graphs</h1>
<p>If you’ve never heard of symbolic mathematics you might get some intuition from
reading <a href="https://iagoleal.com/posts/calculus-symbolic/">Let’s Program a Calculus Student</a> first.
First, we define our symbolic maths language and enable it to be represented by
an e-graph using <code>hegg</code>.</p>
<h2 data-number="1.1" id="syntax"><span class="header-section-number">1.1</span> Syntax</h2>
<p>We’ll start by defining the abstract syntax tree for our simple symbolic expressions:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">SymExpr</span> <span class="ot">=</span> <span class="dt">Const</span> <span class="dt">Double</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>             <span class="op">|</span> <span class="dt">Symbol</span> <span class="dt">String</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>             <span class="op">|</span> <span class="dt">SymExpr</span> <span class="op">:+:</span> <span class="dt">SymExpr</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>             <span class="op">|</span> <span class="dt">SymExpr</span> <span class="op">:*:</span> <span class="dt">SymExpr</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>             <span class="op">|</span> <span class="dt">SymExpr</span> <span class="op">:/:</span> <span class="dt">SymExpr</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>infix <span class="dv">6</span> <span class="op">:+:</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>infix <span class="dv">7</span> <span class="op">:*:</span>, <span class="op">:/:</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="ot">e1 ::</span> <span class="dt">SymExpr</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>e1 <span class="ot">=</span> (<span class="dt">Symbol</span> <span class="st">&quot;x&quot;</span> <span class="op">:*:</span> <span class="dt">Const</span> <span class="dv">2</span>) <span class="op">:/:</span> (<span class="dt">Const</span> <span class="dv">2</span>) <span class="co">-- (x*2)/2</span></span></code></pre></div>
<p>You might notice that <code>(x*2)/2</code> is the same as just <code>x</code>. Our goal is to get
equality saturation to do that for us.</p>
<p>Our second step is to instance <code>Language</code> for our <code>SymExpr</code></p>
<h2 data-number="1.2" id="language"><span class="header-section-number">1.2</span> Language</h2>
<p><code>Language</code> is the required constraint on <em>expressions</em> that are to be
represented in e-graph and on which equality saturation can be run:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Language</span> l <span class="ot">=</span> (<span class="dt">Traversable</span> l, ∀ a<span class="op">.</span> <span class="dt">Ord</span> a <span class="ot">=&gt;</span> <span class="dt">Ord</span> (l a))</span></code></pre></div>
<p>To declare a <code>Language</code> we must write the “base functor” of <code>SymExpr</code> (i.e. use
a type parameter where the recursion points used to be in the original
<code>SymExpr</code>), then instance <code>Traversable l</code>, <code>∀ a. Ord a =&gt; Ord (l a)</code> (we can do
it automatically through deriving), and write an <code>Analysis</code> instance for it (see
next section).</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">SymExpr</span> a <span class="ot">=</span> <span class="dt">Const</span> <span class="dt">Double</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>               <span class="op">|</span> <span class="dt">Symbol</span> <span class="dt">String</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>               <span class="op">|</span> a <span class="op">:+:</span> a</span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>               <span class="op">|</span> a <span class="op">:*:</span> a</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>               <span class="op">|</span> a <span class="op">:/:</span> a</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>               <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Functor</span>, <span class="dt">Foldable</span>, <span class="dt">Traversable</span>)</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>infix <span class="dv">6</span> <span class="op">:+:</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>infix <span class="dv">7</span> <span class="op">:*:</span>, <span class="op">:/:</span></span></code></pre></div>
<p>Suggested reading on defining recursive data types in their parametrized
version: <a href="https://blog.sumtypeofway.com/posts/introduction-to-recursion-schemes.html">Introduction To Recursion
Schemes</a></p>
<p>If we now wanted to represent an expression, we’d write it in its
fixed-point form</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">e1 ::</span> <span class="dt">Fix</span> <span class="dt">SymExpr</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>e1 <span class="ot">=</span> <span class="dt">Fix</span> (<span class="dt">Fix</span> (<span class="dt">Fix</span> (<span class="dt">Symbol</span> <span class="st">&quot;x&quot;</span>) <span class="op">:*:</span> <span class="dt">Fix</span> (<span class="dt">Const</span> <span class="dv">2</span>)) <span class="op">:/:</span> (<span class="dt">Fix</span> (<span class="dt">Const</span> <span class="dv">2</span>))) <span class="co">-- (x*2)/2</span></span></code></pre></div>
<p>Then, we define an <code>Analysis</code> for our <code>SymExpr</code>.</p>
<h2 data-number="1.3" id="analysis"><span class="header-section-number">1.3</span> Analysis</h2>
<p>E-class analysis is first described in <a href="https://arxiv.org/pdf/2004.03082.pdf"><em>egg: Fast and Extensible Equality
Saturation</em></a> as a way to make equality
saturation more <em>extensible</em>.</p>
<p>With it, we can attach <em>analysis data</em> from a semilattice to each e-class. More
can be read about e-class analysis in the <a href=""><code>Data.Equality.Analsysis</code></a> module and
in the paper.</p>
<p>We can easily define constant folding (<code>2+2</code> being simplified to <code>4</code>) through
an <code>Analysis</code> instance.</p>
<p>An <code>Analysis</code> is defined over a <code>domain</code> and a <code>language</code>. To define constant
folding, we’ll say the domain is <code>Maybe Double</code> to attach a value of that type to
each e-class, where <code>Nothing</code> indicates the e-class does not currently have a
constant value and <code>Just i</code> means the e-class has constant value <code>i</code>.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Analysis</span> (<span class="dt">Maybe</span> <span class="dt">Double</span>) <span class="dt">SymExpr</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>  makeA <span class="ot">=</span> <span class="op">...</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>  joinA <span class="ot">=</span> <span class="op">...</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>  modifyA <span class="ot">=</span> <span class="op">...</span></span></code></pre></div>
<p>Let’s now understand and implement the three methods of the analysis instance we want.</p>
<p><code>makeA</code> is called when a new e-node is added to a new e-class, and constructs
for the new e-class a new value of the domain to be associated with it, always
by accessing the associated data of the node’s children data. Its type is <code>l domain -&gt; domain</code>, so note that the e-node’s children associated data is
directly available in place of the actual children.</p>
<p>We want to associate constant data to the e-class, so we must find if the
e-node has a constant value or otherwise return <code>Nothing</code>:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ot">makeA ::</span> <span class="dt">SymExpr</span> (<span class="dt">Maybe</span> <span class="dt">Double</span>) <span class="ot">-&gt;</span> <span class="dt">Maybe</span> <span class="dt">Double</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>makeA <span class="ot">=</span> \<span class="kw">case</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Const</span> x <span class="ot">-&gt;</span> <span class="dt">Just</span> x</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Symbol</span> _ <span class="ot">-&gt;</span> <span class="dt">Nothing</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>  x <span class="op">:+:</span> y <span class="ot">-&gt;</span> (<span class="op">+</span>) <span class="op">&lt;$&gt;</span> x <span class="op">&lt;*&gt;</span> y</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>  x <span class="op">:*:</span> y <span class="ot">-&gt;</span> (<span class="op">*</span>) <span class="op">&lt;$&gt;</span> x <span class="op">&lt;*&gt;</span> y</span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>  x <span class="op">:/:</span> y <span class="ot">-&gt;</span> (<span class="op">/</span>) <span class="op">&lt;$&gt;</span> x <span class="op">&lt;*&gt;</span> y</span></code></pre></div>
<p><code>joinA</code> is called when e-classes c1 c2 are being merged into c. In this case, we
must join the e-class data from both classes to form the e-class data to be
associated with new e-class c. Its type is <code>domain -&gt; domain -&gt; domain</code>. In our
case, to merge <code>Just _</code> with <code>Nothing</code> we simply take the <code>Just</code>, and if we
merge two e-classes with a constant value (that is, both are <code>Just</code>), then the
constant value is the same (or something went very wrong) and we just keep it.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">joinA ::</span> <span class="dt">Maybe</span> <span class="dt">Double</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> <span class="dt">Double</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> <span class="dt">Double</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>joinA <span class="dt">Nothing</span> (<span class="dt">Just</span> x) <span class="ot">=</span> <span class="dt">Just</span> x</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>joinA (<span class="dt">Just</span> x) <span class="dt">Nothing</span> <span class="ot">=</span> <span class="dt">Just</span> x</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>joinA <span class="dt">Nothing</span> <span class="dt">Nothing</span>  <span class="ot">=</span> <span class="dt">Nothing</span></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>joinA (<span class="dt">Just</span> x) (<span class="dt">Just</span> y) <span class="ot">=</span> <span class="kw">if</span> x <span class="op">==</span> y <span class="kw">then</span> <span class="dt">Just</span> x <span class="kw">else</span> <span class="fu">error</span> <span class="st">&quot;ouch, that shouldn&#39;t have happened&quot;</span></span></code></pre></div>
<p>Finally, <code>modifyA</code> describes how an e-class should (optionally) be modified
according to the e-class data and what new language expressions are to be added
to the e-class also w.r.t. the e-class data.
Its type is <code>ClassId -&gt; EGraph domain l -&gt; EGraph domain l</code>, where the first argument
is the id of the class to modify (the class which prompted the modification),
and then receives and returns an e-graph, in which the e-class has been
modified. For our example, if the e-class has a constant value associated to
it, we want to create a new e-class with that constant value and merge it to
this e-class.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- import Data.Equality.Graph.Lens ((^.), _class, _data)</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="ot">modifyA ::</span> <span class="dt">ClassId</span> <span class="ot">-&gt;</span> <span class="dt">EGraph</span> (<span class="dt">Maybe</span> <span class="dt">Double</span>) <span class="dt">SymExpr</span> <span class="ot">-&gt;</span> <span class="dt">EGraph</span> (<span class="dt">Maybe</span> <span class="dt">Double</span>) <span class="dt">SymExpr</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>modifyA c egr</span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=</span> <span class="kw">case</span> egr <span class="op">^.</span>_class c<span class="op">.</span>_data <span class="kw">of</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Nothing</span> <span class="ot">-&gt;</span> egr</span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Just</span> i <span class="ot">-&gt;</span></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a>          <span class="kw">let</span> (c&#39;, egr&#39;) <span class="ot">=</span> represent (<span class="dt">Fix</span> (<span class="dt">Const</span> i)) egr</span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a>           <span class="kw">in</span> <span class="fu">snd</span> <span class="op">$</span> merge c c&#39; egr&#39;</span></code></pre></div>
<p>Modify is a bit trickier than the other methods, but it allows our e-graph to
change based on the e-class analysis data. Note that the method is optional and
there’s a default implementation for it which doesn’t change the e-class or adds
anything to it. Analysis data can be otherwise used, e.g., to inform rewrite
conditions.</p>
<p>By instancing this e-class analysis, all e-classes that have a constant value
associated to them will also have an e-node with a constant value. This is great
for our simple symbolic library because it means if we ever find e.g. an
expression equal to <code>3+1</code>, we’ll also know it to be equal to <code>4</code>, which is a
better result than <code>3+1</code> (we’ve then successfully implemented constant folding).</p>
<p>If, otherwise, we didn’t want to use an analysis, we could specify the analysis
domain as <code>()</code> which will make the analysis do nothing, because there’s an
instance polymorphic over <code>lang</code> for <code>()</code> that looks like this:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Analysis</span> () lang <span class="kw">where</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>  makeA _ <span class="ot">=</span> ()</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>  joinA _ _ <span class="ot">=</span> ()</span></code></pre></div>
<h1 data-number="2" id="equality-saturation-on-symbolic-expressions"><span class="header-section-number">2</span> Equality saturation on symbolic expressions</h1>
<p>Equality saturation is defined as the function</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">equalitySaturation ::</span> <span class="kw">forall</span> l<span class="op">.</span> <span class="dt">Language</span> l</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>                   <span class="ot">=&gt;</span> <span class="dt">Fix</span> l             <span class="co">-- ^ Expression to run equality saturation on</span></span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a>                   <span class="ot">-&gt;</span> [<span class="dt">Rewrite</span> l]       <span class="co">-- ^ List of rewrite rules</span></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a>                   <span class="ot">-&gt;</span> <span class="dt">CostFunction</span> l    <span class="co">-- ^ Cost function to extract the best equivalent representation</span></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>                   <span class="ot">-&gt;</span> (<span class="dt">Fix</span> l, <span class="dt">EGraph</span> l) <span class="co">-- ^ Best equivalent expression and resulting e-graph</span></span></code></pre></div>
<p>To recap, our goal is to reach <code>x</code> starting from <code>(x*2)/2</code> by means of equality
saturation.</p>
<p>We already have a starting expression, so we’re missing a list of rewrite rules
(<code>[Rewrite l]</code>) and a cost function (<code>CostFunction</code>).</p>
<h2 data-number="2.1" id="cost-function"><span class="header-section-number">2.1</span> Cost function</h2>
<p>Picking up the easy one first:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">CostFunction</span> l cost <span class="ot">=</span> l cost <span class="ot">-&gt;</span> cost</span></code></pre></div>
<p>A cost function is used to attribute a cost to representations in the e-graph and to extract the best one.
The first type parameter <code>l</code> is the language we’re going to attribute a cost to, and
the second type parameter <code>cost</code> is the type with which we will model cost. For
the cost function to be valid, <code>cost</code> must instance <code>Ord</code>.</p>
<p>We’ll say <code>Const</code>s and <code>Symbol</code>s are the cheapest and then in increasing cost we
have <code>:+:</code>, <code>:*:</code> and <code>:/:</code>, and model cost with the <code>Int</code> type.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ot">cost ::</span> <span class="dt">CostFunction</span> <span class="dt">SymExpr</span> <span class="dt">Int</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>cost <span class="ot">=</span> \<span class="kw">case</span></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Const</span>  x <span class="ot">-&gt;</span> <span class="dv">1</span></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Symbol</span> x <span class="ot">-&gt;</span> <span class="dv">1</span></span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>  c1 <span class="op">:+:</span> c2 <span class="ot">-&gt;</span> c1 <span class="op">+</span> c2 <span class="op">+</span> <span class="dv">2</span></span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a>  c1 <span class="op">:*:</span> c2 <span class="ot">-&gt;</span> c1 <span class="op">+</span> c2 <span class="op">+</span> <span class="dv">3</span></span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>  c1 <span class="op">:/:</span> c2 <span class="ot">-&gt;</span> c1 <span class="op">+</span> c2 <span class="op">+</span> <span class="dv">4</span></span></code></pre></div>
<h2 data-number="2.2" id="rewrite-rules"><span class="header-section-number">2.2</span> Rewrite rules</h2>
<p>Rewrite rules are transformations applied to matching expressions represented in
an e-graph.</p>
<p>We can write simple rewrite rules and conditional rewrite rules, but we’ll only look at the simple ones.</p>
<p>A simple rewrite is formed of its left hand side and right hand side. When the
left hand side is matched in the e-graph, the right hand side is added to the
e-class where the left hand side was found.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Rewrite</span> lang <span class="ot">=</span> <span class="dt">Pattern</span> lang <span class="op">:=</span> <span class="dt">Pattern</span> lang          <span class="co">-- Simple rewrite rule</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>                  <span class="op">|</span> <span class="dt">Rewrite</span> lang <span class="op">:|</span> <span class="dt">RewriteCondition</span> lang <span class="co">-- Conditional rewrite rule</span></span></code></pre></div>
<p>A <code>Pattern</code> is basically an expression that might contain variables and which can be matched against actual expressions.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Pattern</span> lang</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=</span> <span class="dt">NonVariablePattern</span> (lang (<span class="dt">Pattern</span> lang))</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>    <span class="op">|</span> <span class="dt">VariablePattern</span> <span class="dt">Var</span></span></code></pre></div>
<p>A patterns is defined by its non-variable and variable parts, and can be
constructed directly or using the helper function <code>pat</code> and using
<code>OverloadedStrings</code> for the variables, where <code>pat</code> is just a synonym for
<code>NonVariablePattern</code> and a string literal <code>"abc"</code> is turned into a <code>Pattern</code>
constructed with <code>VariablePattern</code>.</p>
<p>We can then write the following very specific set of rewrite rules to simplify
our simple symbolic expressions.</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="ot">rewrites ::</span> [<span class="dt">Rewrite</span> <span class="dt">SymExpr</span>]</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>rewrites <span class="ot">=</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>  [ pat (pat (<span class="st">&quot;a&quot;</span> <span class="op">:*:</span> <span class="st">&quot;b&quot;</span>) <span class="op">:/:</span> <span class="st">&quot;c&quot;</span>) <span class="op">:=</span> pat (<span class="st">&quot;a&quot;</span> <span class="op">:*:</span> pat (<span class="st">&quot;b&quot;</span> <span class="op">:/:</span> <span class="st">&quot;c&quot;</span>))</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>  , pat (<span class="st">&quot;x&quot;</span> <span class="op">:/:</span> <span class="st">&quot;x&quot;</span>)               <span class="op">:=</span> pat (<span class="dt">Const</span> <span class="dv">1</span>)</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>  , pat (<span class="st">&quot;x&quot;</span> <span class="op">:*:</span> (pat (<span class="dt">Const</span> <span class="dv">1</span>)))   <span class="op">:=</span> <span class="st">&quot;x&quot;</span></span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>  ]</span></code></pre></div>
<h2 data-number="2.3" id="equality-saturation-finally"><span class="header-section-number">2.3</span> Equality saturation, finally</h2>
<p>We can now run equality saturation on our expression!</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> expr <span class="ot">=</span> <span class="fu">fst</span> (equalitySaturation e1 rewrites cost)</span></code></pre></div>
<p>And upon printing we’d see <code>expr = Symbol "x"</code>!</p>
<p>If we had instead <code>e2 = Fix (Fix (Fix (Symbol "x") :/: Fix (Symbol "x")) :+: (Fix (Const 3))) -- (x/x)+3</code>, we’d get <code>expr = Const 4</code> because of our rewrite
rules put together with our constant folding!</p>
<p>This was a first introduction which skipped over some details but that tried to
walk through fundamental concepts for using e-graphs and equality saturation
with this library.</p>
<p>The final code for this tutorial is available under <code>test/SimpleSym.hs</code></p>
<p>A more complicated symbolic rewrite system which simplifies some derivatives and
integrals was written for the testsuite. It can be found at <code>test/Sym.hs</code>.</p>
<p>This library could also be used not only for equality-saturation but also for
the equality-graphs and other equality-things (such as e-matching) available.
For example, using just the e-graphs from <code>Data.Equality.Graph</code> to improve GHC’s
pattern match checker (https://gitlab.haskell.org/ghc/ghc/-/issues/19272).</p>
]]></summary>
</entry>
<entry>
    <title>Graphical Applications in Haskell with FRP and Reflex</title>
    <link href="http://alt-romes.github.io/posts/lectures/2022-07-10-frp.html" />
    <id>http://alt-romes.github.io/posts/lectures/2022-07-10-frp.html</id>
    <published>2022-07-10T00:00:00Z</published>
    <updated>2022-07-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#functional-reactive-programming" id="toc-functional-reactive-programming"><span class="toc-section-number">1</span> Functional Reactive Programming</a>
<ul>
<li><a href="#behaviours" id="toc-behaviours"><span class="toc-section-number">1.1</span> Behaviours</a></li>
<li><a href="#events" id="toc-events"><span class="toc-section-number">1.2</span> Events</a></li>
</ul></li>
<li><a href="#reflex" id="toc-reflex"><span class="toc-section-number">2</span> Reflex</a>
<ul>
<li><a href="#building-uis-with-reflex-dom" id="toc-building-uis-with-reflex-dom"><span class="toc-section-number">2.1</span> Building UIs with Reflex-Dom</a></li>
<li><a href="#reflex-combinators" id="toc-reflex-combinators"><span class="toc-section-number">2.2</span> Reflex Combinators</a></li>
</ul></li>
<li><a href="#example-101companies" id="toc-example-101companies"><span class="toc-section-number">3</span> Example: 101companies</a></li>
</ul>
</div>
<!-- description: The Functional Reactive Programming paradigm and the -->
<!--                 <code>reflex</code> library, and using them to create DOM-based graphical -->
<!--                 applications with the <code>reflex-dom</code> library... -->
<h1 data-number="1" id="functional-reactive-programming"><span class="header-section-number">1</span> Functional Reactive Programming</h1>
<p>Functional reactive programming is a general paradigm well suited to programming
<em>real-time systems</em> in a high-level and functional way.</p>
<p><em>Real-time systems</em> or <em>reactive systems</em> are those that handle continuous
time-varying values, discrete events in real time, and react accordingly. A good
example of these systems is a <em>mobile robot</em>. They must take into consideration
continuous inputs like wheel speed, orientation, and discrete events such as
detection of another object.</p>
<p>The class of reactive systems we’re interested in here is interactive <em>graphical
UIs</em>. A user interface has multiple components that can be seen as discrete
events and continuous time-varying values. An input box, where one might write
their name, is an example of a time varying value (it continously changes –
whenever the user types something); a button is an example of a discrete event
in time: at certain points in time the user will click the button. This will
make more sense with practice and code samples.</p>
<p>So the promise of functional reactive programming is that we can program these
complicated reactive systems in a pure functional way. But how?</p>
<p>Functional Reactive Programming introduces two key concepts: <strong>Behaviours</strong> and <strong>Events</strong>.</p>
<ul>
<li><p><strong>Behaviours</strong> are first-class values that vary over continuous time.</p>
<p>That means a behaviour is a value that changes with time and can be passed
to/returned by functions.</p></li>
<li><p><strong>Events</strong> are first-class values that occur at some points in time.</p>
<p>They may refer, e.g., to happenings in the real world time – such as a
mouse click or a key press.</p></li>
</ul>
<p>And then, it says that the FRP implementation will handle all time-related
details so that the programmer can describe their <em>reactive system</em> without
thinking about what happens at <strong>any</strong> particular point in time, but rather thinking
about what happens accross <strong>all</strong> points in time.</p>
<p>This type of <em>wholemeal programming</em> (working with the whole, not the individual
part) is quite common in functional programming. When working with lists, the
same pattern appears: we think and define functions in terms of entire lists,
rather than about any particular element in the list.</p>
<p>Functional reactive programming just takes it further by abstracting over <em>time
itself</em>.</p>
<p>In the end, the programmer doesn’t need to worry about any of the <em>how</em>, just
the <em>what</em> (which quite nicely aligns with the original paper on FRP[1], which
distinguishes <em>presentation</em> from <em>modelling</em>). So, we manipulate time-dependent
<em>behaviours</em> and <em>events</em>, but we never directly see the <em>time</em>.</p>
<p>In fact, both <strong>Behaviors</strong> and <strong>Events</strong> are usually <em>abstract data types</em>,
meaning we don’t even need to know how they are defined.</p>
<p>Later we’ll see what this actually looks like.</p>
<ul>
<li>[1] <em>Functional Reactive Animation, …</em></li>
</ul>
<h2 data-number="1.1" id="behaviours"><span class="header-section-number">1.1</span> Behaviours</h2>
<p>A <strong>Behaviour</strong> is a first-class value that varies over continuous time. In
other words, a Behaviour is a value that can be passed to and returned by
functions (is first-class) and this value is defined for all time (and can
change accross time)</p>
<p>Intuitively, it can be seen as a function from time to value (<code>b :: Time -&gt; Value</code>) and
could be visualized as:</p>
<p><img src="https://github.com/hansroland/reflex-dom-inbits/raw/master/images//behavior.png" /></p>
<p>Note how this function is pure (there are no side effects): we simply map all
points in time to a value.</p>
<p>A behaviour is an abstract type constructor, meaning we know nothing about its
data constructors. We interact with behaviours through the combinators
and functions defined by the FRP implementation we’re using. The type parameter
of <code>Behavior</code> indicates the type of the values.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Behavior</span> a</span></code></pre></div>
<p>Behaviors are usually <strong>Functors</strong> (it depends on the FRP implementation, in
<em>Reflex</em> they are). We can imagine that if we have a behaviour (<code>x :: Behavior Int</code>) which is for all points in time equal to 1 (you might imagine the 2D graph
of the constant math function <code>f(x) = 1</code>), there is an easy way to define a
behavior <code>y</code> which is constantly equal to 2: <code>fmap (+1) x :: Behavior Int</code>.</p>
<p>Let’s write a short example of a function that transforms a <code>Behavior String</code>
into a <code>Behavior (Maybe Color)</code></p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Color</span> <span class="ot">=</span> <span class="dt">Yellow</span> <span class="op">|</span> <span class="dt">Magenta</span> <span class="op">|</span> <span class="dt">Cyan</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="ot">color ::</span> <span class="dt">Behavior</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Behavior</span> (<span class="dt">Maybe</span> <span class="dt">Color</span>)</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>color bstr <span class="ot">=</span> <span class="fu">fmap</span> toColor bstr</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>    toColor <span class="st">&quot;yellow&quot;</span>  <span class="ot">=</span> <span class="dt">Just</span> <span class="dt">Yellow</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>    toColor <span class="st">&quot;magenta&quot;</span> <span class="ot">=</span> <span class="dt">Just</span> <span class="dt">Magenta</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>    toColor <span class="st">&quot;cyan&quot;</span>    <span class="ot">=</span> <span class="dt">Just</span> <span class="dt">Cyan</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>    toColor _         <span class="ot">=</span> <span class="dt">Nothing</span></span></code></pre></div>
<p>An example of a behaviour we’ll use is the value in an input text box. This box
has a string at all times. Before the user writes anything, the value is the
empty string. The value at some time after the user has written “123” is “123”.</p>
<h2 data-number="1.2" id="events"><span class="header-section-number">1.2</span> Events</h2>
<p>An <strong>Event</strong> is a first-class value that occurs at discrete points in time. In
other words, an Event is a value that can be passed to and returned by
functions (is first-class) and this value is defined at only some points in
time. If the event is occuring, <em>and if it is</em>, what its
value is.</p>
<p>It’s a bit harder to think about intuitively, but one can imagine an event as a
function from time to maybe a value (<code>e :: Time -&gt; Maybe Value</code>) or as a list of
values and the times at which they occur (<code>e :: [(Time, Value)]</code>).</p>
<p><img src="https://github.com/hansroland/reflex-dom-inbits/raw/master/images//event.png" /></p>
<p>An event is also an abstract type constructor, meaning we know nothing about its
data constructors. As with behaviors, we interact with events through the combinators
and functions defined by the FRP implementation we’re using. The type parameter
of <code>Event</code> also indicates the type of the values.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Event</span> a</span></code></pre></div>
<p>Above, <code>a</code> is the type of the value the event carries when it occurs.</p>
<p>Events are functors! You can think of them being functors the same way you would about
Behaviors.</p>
<p>An example of an event we’ll use is the one generated by a button. Everytime the
button is clicked, an event occurs of type <code>Event ()</code> (a button click has no
associated value, unlike, e.g., key presses, which would have type <code>Event Char</code>).</p>
<p>Ahead we’ll see how we can manipulate and put together events and behaviors to
build a reactive application.</p>
<h1 data-number="2" id="reflex"><span class="header-section-number">2</span> Reflex</h1>
<p><a href="https://hackage.haskell.org/package/reflex">Reflex</a> is a haskell library for
functional reactive programming in haskell.</p>
<blockquote>
<p>Interactive programs without callbacks or side-effects. Functional Reactive
Programming (FRP) uses composable events and time-varying values to describe
interactive systems as pure functions. Just like other pure functional code,
functional reactive code is easier to get right on the first try, maintain,
and reuse.</p>
</blockquote>
<blockquote>
<p>Reflex is a fully-deterministic, higher-order Functional Reactive Programming
interface and an engine that efficiently implements that interface.</p>
</blockquote>
<p>Reflex provides the above described abstractions (behaviors and events),
functions to work with them, and an additional abstraction called <strong>Dynamics</strong>.
For our intents and purposes, <strong>we’ll consider dynamics to be the same as
behaviors</strong>, since discussing the details of it would be out of the scope of
this tutorial[2].</p>
<ul>
<li>[2] In a <em>very</em> short note: Reflex is implemented with push-pull evaluation,
and thus often requires explicit push notifications to update things like
the DOM. Event push notifications when they occur, but Behaviors don’t push
anything. A Dynamic is a combination of an Event and Behavior, meaning it’s
a continuous time-varying value that pushes notification whenever it
changes, and fills the spaces where we need a behaviour <em>and</em> to know when
the value changes.</li>
</ul>
<h2 data-number="2.1" id="building-uis-with-reflex-dom"><span class="header-section-number">2.1</span> Building UIs with Reflex-Dom</h2>
<p>To build a UI we’ll use
<a href="https://hackage.haskell.org/package/reflex-dom">reflex-dom</a> which is a haskell
library that provides a monadic interface for building a DOM-based UI with
functional reactive programming abstractions from <em>reflex</em>.</p>
<p>A DOM user interface is defined with element tags. A webpage can have many
elements such as <em>divisions</em> and text <em>paragraphs</em>.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode html"><code class="sourceCode html"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="dt">&lt;</span><span class="kw">div</span><span class="dt">&gt;</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>    <span class="dt">&lt;</span><span class="kw">p</span><span class="dt">&gt;</span>This is a paragraph.<span class="dt">&lt;/</span><span class="kw">p</span><span class="dt">&gt;</span> </span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>    <span class="dt">&lt;</span><span class="kw">button</span><span class="dt">&gt;</span>Button below the paragraph<span class="dt">&lt;/</span><span class="kw">button</span><span class="dt">&gt;</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="dt">&lt;/</span><span class="kw">div</span><span class="dt">&gt;</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="dt">&lt;</span><span class="kw">div</span><span class="dt">&gt;</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>    <span class="dt">&lt;</span><span class="kw">p</span><span class="dt">&gt;</span>This is the second division.<span class="dt">&lt;/</span><span class="kw">p</span><span class="dt">&gt;</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>    <span class="dt">&lt;</span><span class="kw">input</span><span class="dt">&gt;&lt;/</span><span class="kw">input</span><span class="dt">&gt;</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a><span class="dt">&lt;/</span><span class="kw">div</span><span class="dt">&gt;</span></span></code></pre></div>
<p>Would define a webpage with two divisions (<code>&lt;div&gt;</code>). The first division has a
paragraph (<code>&lt;p&gt;</code>) and a button (<code>&lt;button&gt;</code>), the second, a paragraph and and a
text-box for input (<code>&lt;input&gt;</code>).</p>
<p>Reflex-dom defines the <code>Widget</code> monad[3] and multiple functions with which we can
create our UI. However, some of these functions do more than build the UI: they
return and accept events and behaviors! Let’s look at a few.</p>
<p>We can put text on the UI, without creating a new element. Notice how the
returned <code>Widget</code> is a computation that builds the UI and the resulting value of
the said computation has type <code>()</code>.</p>
<pre><code>text :: Text -&gt; Widget ()</code></pre>
<p>The most basic element-creating function is <code>el</code>. It takes the name of the
element as a string, a <code>Widget</code> computation, and returns another <code>Widget</code>
computation. This still does nothing regarding FRP.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ot">el ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Widget</span> a <span class="ot">-&gt;</span> <span class="dt">Widget</span> a</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>ex1 <span class="ot">=</span> el <span class="st">&quot;p&quot;</span> (text <span class="st">&quot;This is a paragraph&quot;</span>)</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- would correspond to</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- &lt;p&gt;This is a paragraph&lt;/p&gt;</span></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>ex2 <span class="ot">=</span> el <span class="st">&quot;div&quot;</span> (el <span class="st">&quot;p&quot;</span> (text <span class="st">&quot;Other paragraph&quot;</span>))</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a><span class="co">-- would correspond to</span></span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a><span class="co">-- &lt;div&gt;</span></span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;p&gt;This is a paragraph&lt;/p&gt;</span></span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a><span class="co">-- &lt;/div&gt;</span></span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a>ex3 <span class="ot">=</span> el <span class="st">&quot;div&quot;</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb6-14"><a href="#cb6-14" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;p&quot;</span> (text <span class="st">&quot;First paragraph&quot;</span>)</span>
<span id="cb6-15"><a href="#cb6-15" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;p&quot;</span> (text <span class="st">&quot;Second paragraph&quot;</span>)</span>
<span id="cb6-16"><a href="#cb6-16" aria-hidden="true" tabindex="-1"></a><span class="co">-- would correspond to</span></span>
<span id="cb6-17"><a href="#cb6-17" aria-hidden="true" tabindex="-1"></a><span class="co">--  &lt;div&gt;</span></span>
<span id="cb6-18"><a href="#cb6-18" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;p&gt;First paragraph&lt;/p&gt;</span></span>
<span id="cb6-19"><a href="#cb6-19" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;p&gt;Second paragraph&lt;/p&gt;</span></span>
<span id="cb6-20"><a href="#cb6-20" aria-hidden="true" tabindex="-1"></a><span class="co">--  &lt;div&gt;</span></span></code></pre></div>
<p>A button can be clicked at some points in time. We can model a button click with
an event! There is a convenient function that returns a <code>Widget</code> computation
that creates a button and returns an event that occurs when the button is
clicked. We’ll see ahead an example in which we this event.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">button ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Widget</span> (<span class="dt">Event</span> t ()) </span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>ex4 <span class="ot">=</span> el <span class="st">&quot;div&quot;</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;p&quot;</span> (text <span class="st">&quot;Before button&quot;</span>)</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>        clickEvt <span class="ot">&lt;-</span> button <span class="st">&quot;Click me!&quot;</span></span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;p&quot;</span> (text <span class="st">&quot;After button&quot;</span>)</span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a><span class="co">-- would correspond to</span></span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a><span class="co">--  &lt;div&gt;</span></span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;p&gt;Before button&lt;/p&gt;</span></span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;button&gt;Click me!&lt;/button&gt;</span></span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;p&gt;After button&lt;/p&gt;</span></span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a><span class="co">--  &lt;div&gt;</span></span></code></pre></div>
<p>An input text box has a continuous time-varying value: What the user has input
in the box. We can model the value inside the input box with a behavior! As with
the button, we already have a function that returns a <code>Widget</code> computation that
creates an input box and which returns a behavior of the value in the text box.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ot">input ::</span> <span class="dt">Widget</span> (<span class="dt">Dynamic</span> <span class="dt">Text</span>)</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>ex5 <span class="ot">=</span> el <span class="st">&quot;div&quot;</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>        inputBehavior <span class="ot">&lt;-</span> input</span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>        <span class="fu">return</span> ()</span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a><span class="co">-- would correspond to</span></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a><span class="co">--  &lt;div&gt;</span></span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;input&gt;&lt;/input&gt;</span></span>
<span id="cb8-10"><a href="#cb8-10" aria-hidden="true" tabindex="-1"></a><span class="co">--  &lt;div&gt;</span></span></code></pre></div>
<p>Lastly, we have a function for displaying a behavior of a string. Whatever the
value of the string is at the current time, is what’s displayed on the string.
Non-surprisingly, this function is called <code>dynText</code>.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ot">dynText ::</span> <span class="dt">Dynamic</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Widget</span> ()</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>ex6 <span class="ot">=</span> el <span class="st">&quot;div&quot;</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>        inputBehavior <span class="ot">&lt;-</span> input</span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;p&quot;</span> (dynText inputBehavior)</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a><span class="co">-- what would this look like?</span></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a><span class="co">-- &lt;div&gt;</span></span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;input&gt;&lt;/input&gt;</span></span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a><span class="co">--      &lt;p&gt;???&lt;/p&gt;</span></span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a><span class="co">-- &lt;/div&gt;</span></span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a><span class="co">-- not so simple, would require javascript</span></span></code></pre></div>
<p>Next we’ll look at some UI-independent combinators on events and behaviors, and
an example of how we can use them in building a more complex UI.</p>
<ul>
<li>[3] In fact, <code>Widget x</code> is the monad (<code>Widget :: * -&gt; * -&gt; *</code>), where <code>x</code>
is a type parameter to guarantee contexts don’t get mixed.</li>
</ul>
<h2 data-number="2.2" id="reflex-combinators"><span class="header-section-number">2.2</span> Reflex Combinators</h2>
<p>In this section we describe some reflex combinators for manipulating events and
behaviors. Remember that for our purposes we’ll consider dynamics to be the same
as behaviors but with a different name.</p>
<p>We can create a behavior which is constant over all time, given the constant
value.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">constDyn ::</span> a <span class="ot">-&gt;</span> <span class="dt">Dynamic</span> a</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a>d1 <span class="ot">=</span> constDyn <span class="dv">2</span> <span class="co">-- is 2 at all points in time</span></span></code></pre></div>
<p>We can create a behavior that changes to the value of an event every time said
event occurs, provided an initial value for the behavior to have before the
first occurrence of the event is given.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ot">holdDyn ::</span> a <span class="ot">-&gt;</span> <span class="dt">Event</span> a <span class="ot">-&gt;</span> <span class="dt">Widget</span> (<span class="dt">Dynamic</span> a)</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a>d2 <span class="ot">=</span> holdDyn <span class="ch">&#39;A&#39;</span> keyPress <span class="co">-- until the first event occurrence is &#39;A&#39;, and then it&#39;s the value of the event occurrence</span></span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">where</span><span class="ot"> keyPress ::</span> <span class="dt">Event</span> <span class="dt">Char</span></span></code></pre></div>
<p>We can create a behavior that changes everytime an event occurs, provided the
function to fold the event value with the current value, and an initial value.
This is somewhat similar to a list fold, but it’s a actually a fold <em>across time</em>.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ot">foldDyn ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">Event</span> a <span class="ot">-&gt;</span> m (<span class="dt">Dynamic</span> b)</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- Note: foldr :: (a -&gt; b -&gt; b) -&gt; b -&gt; [a] -&gt; b</span></span></code></pre></div>
<p>As an example, we can now define an application that displays a button and the
number of times said button has been clicked (remember how behaviors instance
<code>Functor</code>)</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>app <span class="ot">=</span> el <span class="st">&quot;div&quot;</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>        clickEvt <span class="ot">&lt;-</span> button <span class="st">&quot;Click me!&quot;</span></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>        clickAmount <span class="ot">&lt;-</span> foldDyn (\_ acc <span class="ot">-&gt;</span> acc<span class="op">+</span><span class="dv">1</span>) <span class="dv">0</span> clickEvt</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;p&quot;</span> (dynText (displayAmt <span class="op">&lt;$&gt;</span> clickAmount))</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">where</span></span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a>        displayAmt x <span class="ot">=</span> <span class="st">&quot;Clicked &quot;</span> <span class="op">&lt;&gt;</span> showT x <span class="op">&lt;&gt;</span> <span class="st">&quot; times.&quot;</span></span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a><span class="co">-- Note how length for normal functions can be defined as</span></span>
<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> ls <span class="ot">=</span> <span class="fu">foldr</span> (\_ acc <span class="ot">-&gt;</span> acc<span class="op">+</span><span class="dv">1</span>) <span class="dv">0</span> ls</span></code></pre></div>
<p>This might be a bit confusing so we’ll walk through each value.</p>
<ul>
<li><code>clickEvt</code> has type <code>Event ()</code>, representing the occurrences of a button click
through time</li>
<li><code>clickAmount</code> has type <code>Dynamic Int</code>. We start with the value <code>0</code>, and
when the <code>Event ()</code> occurs, we apply the lambda of type <code>() -&gt; Int -&gt; Int</code>
which ignores the first argument and adds <code>+1</code> to the existing counter.</li>
<li><code>displayAmt &lt;$&gt; clickAmount</code> has type <code>Dynamic Text</code>, meaning we can display
it with <code>dynText</code>. Note that <code>displayAmt :: Int -&gt; Text</code>, and we <code>fmap</code> it
over <code>Dynamic Int</code> (hence why we get <code>Dynamic Text</code>).</li>
</ul>
<p>If you were something similar[4] to this code, you’d see an application with a
button and a text paragraph with a counter. Every time you click the button the
counter will increase.</p>
<p>Lastly, we’ll cover a function that allows us to sample the value of a behavior
every time an event occurs.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="ot">tagPromptlyDyn ::</span> <span class="dt">Dynamic</span> a <span class="ot">-&gt;</span> <span class="dt">Event</span> b <span class="ot">-&gt;</span> <span class="dt">Event</span> a</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- e1 will occur with the value of the input box every time the button is clicked</span></span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="ot">e1 ::</span> <span class="dt">Event</span> <span class="dt">Text</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>e1 <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>    click <span class="ot">&lt;-</span> button <span class="st">&quot;Sample input box value&quot;</span></span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a>    valBehv <span class="ot">&lt;-</span> input</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a>    <span class="fu">return</span> (tagPromptlyDyn valBehv click)</span></code></pre></div>
<p>Next we’ll build a simple application for the Company example.</p>
<ul>
<li>[4] A full runnable example of this program is provided in the appendix(?)</li>
</ul>
<h1 data-number="3" id="example-101companies"><span class="header-section-number">3</span> Example: 101companies</h1>
<p>For our 101 companies example we’ll build a simple application with three
distinct divisions. One for information where we display the total price of the
employees, one for the hiring form with which we can add employees to our
company, and one with the list of the employees in the company.</p>
<p><img src="/images/101companies-frp-demo.png" /></p>
<p>Our application models and displays the changes in a company over time. We’ll
model the company with a behavior. Initially, the company will be the sample
company. Whenever an employee is hired the company behavior changes accordingly.</p>
<p>The first section is a simple division with a text that changes according to a
behavior. We only want to display the total value of a company that changes over
time, so we’ll capture this idea with this function:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="ot">info ::</span> <span class="dt">Dynamic</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Widget</span> x ()</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>info c <span class="ot">=</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>    el <span class="st">&quot;div&quot;</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;h3&quot;</span> (text <span class="st">&quot;Info&quot;</span>)</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>        dynText (companyToTotal <span class="op">&lt;$&gt;</span> c)</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a><span class="ot">    companyToTotal ::</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Text</span></span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>    companyToTotal c <span class="ot">=</span> <span class="st">&quot;Total cost: $&quot;</span> <span class="op">&lt;&gt;</span> showT (total c)</span></code></pre></div>
<p>Our hiring department defines a company that changes over time: It defines the
button that will add an employee to the company everytime it’s clicked, and
otherwise doesn’t take any arguments.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="ot">hiring ::</span> <span class="dt">Widget</span> x (<span class="dt">Dynamic</span> <span class="dt">Company</span>)</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>hiring <span class="ot">=</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>    el <span class="st">&quot;div&quot;</span> <span class="kw">do</span></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;h3&quot;</span> (text <span class="st">&quot;Hiring&quot;</span>)</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>        name    <span class="ot">&lt;-</span> input <span class="st">&quot;Name&quot;</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>        address <span class="ot">&lt;-</span> input <span class="st">&quot;Addr.&quot;</span></span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a>        salary  <span class="ot">&lt;-</span> input <span class="st">&quot;Salary&quot;</span></span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a>        clickEv <span class="ot">&lt;-</span> button <span class="st">&quot;Hire&quot;</span></span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span><span class="ot"> behaviorEmployee ::</span> <span class="dt">Dynamic</span> <span class="dt">Employee</span> <span class="ot">=</span> <span class="dt">Employee</span> <span class="op">&lt;$&gt;</span> name <span class="op">&lt;*&gt;</span> address <span class="op">&lt;*&gt;</span> (readSalary <span class="op">&lt;$&gt;</span> salary)</span>
<span id="cb16-10"><a href="#cb16-10" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span><span class="ot"> hireEmployee     ::</span> <span class="dt">Event</span> <span class="dt">Employee</span> <span class="ot">=</span> tagPromptlyDyn behaviorEmployee clickEv</span>
<span id="cb16-11"><a href="#cb16-11" aria-hidden="true" tabindex="-1"></a>        foldDyn addEmployee sampleCompany hireEmployee</span>
<span id="cb16-12"><a href="#cb16-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-13"><a href="#cb16-13" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb16-14"><a href="#cb16-14" aria-hidden="true" tabindex="-1"></a><span class="ot">    addEmployee ::</span> <span class="dt">Employee</span> <span class="ot">-&gt;</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Company</span></span>
<span id="cb16-15"><a href="#cb16-15" aria-hidden="true" tabindex="-1"></a>    addEmployee e (<span class="dt">Company</span> n es) <span class="ot">=</span> <span class="dt">Company</span> n (e<span class="op">:</span>es)</span>
<span id="cb16-16"><a href="#cb16-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-17"><a href="#cb16-17" aria-hidden="true" tabindex="-1"></a><span class="ot">    readSalary ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Salary</span></span>
<span id="cb16-18"><a href="#cb16-18" aria-hidden="true" tabindex="-1"></a>    readSalary <span class="ot">=</span> <span class="fu">read</span> <span class="op">.</span> unpack</span></code></pre></div>
<ul>
<li><code>input</code> is a helper function defined in our module with type <code>Text -&gt; Widget x   (Dynamic Text)</code>. It takes a text to display above the input, and returns the
DOM-building computation that returns a behavior of the value inside the
input box.</li>
<li>We make three input boxes and get three behaviors of text.</li>
<li>We make a button and get <code>clickEvt :: Event ()</code>.</li>
<li>We make a new behavior <code>behaviorEmployee</code> that combines the continuos values
in the input boxes to define an employee that changes over continuous time.
(We make use of applicative functor syntax here)</li>
<li>We create a new event <code>hireEmployee</code> by combining the click event with the
employee behavior. This event fires every time the button is clicked, and
the value will be the current employee described in the input boxes at that
time.</li>
<li>In the last line, we return the behavior of the company by folding (<code>foldDyn</code>)
over the employee-creating event <code>hireEmployee</code> and starting with the
initial company <code>sampleCompany</code>. That is, every time the event fires, we
apply <code>addEmployee</code> to the value of the event and to the current value of
the behavior (which initially is equal to <code>sampleCompany</code>).</li>
</ul>
<p>Finally, we’ll display the list of employees. We’ll make use of a reflex
function called <code>simpleList :: Dynamic t [v] -&gt; (Dynamic t v -&gt; Widget a) -&gt; Widget x ()</code>[5]. It basically says that with a behavior of a list of values, and
with a function that can turn the behavior of each value in the list into a
widget, we get a widget which applies the function to every element of the list.</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="ot">employeesList ::</span> <span class="dt">Dynamic</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Widget</span> x ()</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>employeesList c <span class="ot">=</span></span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>    section <span class="kw">do</span></span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;h3&quot;</span> (text <span class="st">&quot;Employees&quot;</span>)</span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a>        el <span class="st">&quot;table&quot;</span> <span class="kw">do</span></span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a>            el <span class="st">&quot;tr&quot;</span> <span class="kw">do</span></span>
<span id="cb17-7"><a href="#cb17-7" aria-hidden="true" tabindex="-1"></a>                el <span class="st">&quot;td&quot;</span> (text <span class="st">&quot;Name&quot;</span>)</span>
<span id="cb17-8"><a href="#cb17-8" aria-hidden="true" tabindex="-1"></a>                el <span class="st">&quot;td&quot;</span> (text <span class="st">&quot;Address&quot;</span>)</span>
<span id="cb17-9"><a href="#cb17-9" aria-hidden="true" tabindex="-1"></a>                el <span class="st">&quot;td&quot;</span> (text <span class="st">&quot;Salary&quot;</span>)</span>
<span id="cb17-10"><a href="#cb17-10" aria-hidden="true" tabindex="-1"></a>            simpleList (employees <span class="op">&lt;$&gt;</span> c) \dEmployee <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb17-11"><a href="#cb17-11" aria-hidden="true" tabindex="-1"></a>                el <span class="st">&quot;tr&quot;</span> <span class="kw">do</span></span>
<span id="cb17-12"><a href="#cb17-12" aria-hidden="true" tabindex="-1"></a>                    <span class="kw">let</span> dName <span class="ot">=</span> <span class="fu">fmap</span> emplName dEmployee</span>
<span id="cb17-13"><a href="#cb17-13" aria-hidden="true" tabindex="-1"></a>                    <span class="kw">let</span> dAddr <span class="ot">=</span> <span class="fu">fmap</span> emplAddr dEmployee</span>
<span id="cb17-14"><a href="#cb17-14" aria-hidden="true" tabindex="-1"></a>                    <span class="kw">let</span> dSalr <span class="ot">=</span> <span class="fu">fmap</span> emplSalr dEmployee</span>
<span id="cb17-15"><a href="#cb17-15" aria-hidden="true" tabindex="-1"></a>                    el <span class="st">&quot;td&quot;</span> (dynText dName)</span>
<span id="cb17-16"><a href="#cb17-16" aria-hidden="true" tabindex="-1"></a>                    el <span class="st">&quot;td&quot;</span> (dynText dAddr)</span>
<span id="cb17-17"><a href="#cb17-17" aria-hidden="true" tabindex="-1"></a>                    el <span class="st">&quot;td&quot;</span> (dynText dSalr)</span>
<span id="cb17-18"><a href="#cb17-18" aria-hidden="true" tabindex="-1"></a>        <span class="fu">return</span> ()</span>
<span id="cb17-19"><a href="#cb17-19" aria-hidden="true" tabindex="-1"></a>            <span class="kw">where</span></span>
<span id="cb17-20"><a href="#cb17-20" aria-hidden="true" tabindex="-1"></a>                emplName (<span class="dt">Employee</span> n _ _) <span class="ot">=</span> n</span>
<span id="cb17-21"><a href="#cb17-21" aria-hidden="true" tabindex="-1"></a>                emplAddr (<span class="dt">Employee</span> _ a _) <span class="ot">=</span> a</span>
<span id="cb17-22"><a href="#cb17-22" aria-hidden="true" tabindex="-1"></a>                emplSalr (<span class="dt">Employee</span> _ _ s) <span class="ot">=</span> <span class="st">&quot;$&quot;</span> <span class="op">&lt;&gt;</span> (<span class="fu">pack</span> <span class="op">.</span> <span class="fu">show</span>) s</span></code></pre></div>
<ul>
<li>We’re creating an HTML table. It consists of table rows (<code>&lt;tr&gt;</code>) and each
table row has multiple cells called table data (<code>&lt;td&gt;</code>).</li>
<li>We display a row with the headers Name, Address, and Salary.</li>
<li>We apply the simple list function to the list of employees in the company.
Note how <code>c :: Dynamic Company</code>, and <code>employees :: Company -&gt; [Employee]</code>,
so <code>employees &lt;$&gt; c :: Dynamic [Employee]</code>.</li>
<li>The function to display each element of the list displays the name, address,
and salary of the employee in a table row. We get the behavior of each
individual attribute (name, salary, employee) by using <code>fmap</code> on the
behavior of the employee with the utility functions defined below.</li>
</ul>
<p>Finally, we put together these three things in one widget:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="ot">body ::</span> <span class="dt">Widget</span> x ()</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>body <span class="ot">=</span> mdo</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>    info dynamicCompany</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>    dynamicCompany <span class="ot">&lt;-</span> hiring</span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a>    employeesList dynamicCompany</span></code></pre></div>
<p><code>hiring</code> defines the behavior of the company, and both <code>info</code> and
<code>employeesList</code> consume it. We then define main using a main reflex-dom
function to run the body of the application:</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span> mainWidgetWithCss style body</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a>style <span class="ot">=</span> <span class="st">&quot;body { padding: 2em; margin: auto; max-width: 50em; } h3 {...&quot;</span></span></code></pre></div>
<p>You might note that we pass <code>dynamicCompany</code> to <code>info</code> <em>before</em> it’s actually
defined. I think we’ve seen enough mind-blowing things for this post, but in
short, we’re making use of an extension called <code>RecursiveDo</code> that allows us to
do these logic-defying things.</p>
<ul>
<li>[5] Simplified version of the signature for our purposes… The actual one is
<code>simpleList :: (Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m) =&gt;   Dynamic t [v] -&gt; (Dynamic t v -&gt; m a) -&gt; m (Dynamic t [a])</code></li>
</ul>
<!-- Acknowledgments -->
<!-- =============== -->
<!-- Ask John to review this? -->
]]></summary>
</entry>
<entry>
    <title>Graphical Applications in Haskell with MVC and Gloss</title>
    <link href="http://alt-romes.github.io/posts/lectures/2022-06-27-mvc-gloss.html" />
    <id>http://alt-romes.github.io/posts/lectures/2022-06-27-mvc-gloss.html</id>
    <published>2022-06-27T00:00:00Z</published>
    <updated>2022-06-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#mvc" id="toc-mvc"><span class="toc-section-number">1</span> MVC</a></li>
<li><a href="#functional-mvc-gloss" id="toc-functional-mvc-gloss"><span class="toc-section-number">2</span> Functional MVC: Gloss</a>
<ul>
<li><a href="#picture" id="toc-picture"><span class="toc-section-number">2.1</span> Picture</a></li>
<li><a href="#event" id="toc-event"><span class="toc-section-number">2.2</span> Event</a></li>
<li><a href="#gloss" id="toc-gloss"><span class="toc-section-number">2.3</span> Gloss</a></li>
</ul></li>
</ul>
</div>
<h1 data-number="1" id="mvc"><span class="header-section-number">1</span> MVC</h1>
<p>Model–view–controller (MVC) is a software architectural pattern commonly used
for developing user interfaces that divide the related program logic into three
interconnected elements.</p>
<p><strong>MVC</strong> says that an interactive application should consist roughly of three
main parts – <strong>Model</strong>, <strong>View</strong>, and <strong>Controller</strong>.</p>
<ul>
<li><p>The <strong>Model</strong> is the data and state that we need to keep track of to
<em>model</em> our application. If you’re programming a Chess game, the model could
consist of the state of the board (which pieces are where), the time passed
since the last player played, whose turn it is, etc…</p></li>
<li><p>The <strong>View</strong> is the definition of how our model should be displayed to the
user. Intuitively, you can think of it as a function <code>Model -&gt; UI</code> (and
begin to see how <em>functional MVC</em> might be interesting). For the above
example, the view would define how the chess board can be shown to the user
(a 3d object, a 2d ascii board, …), where the time passed shows up in the
screen, etc.</p></li>
<li><p>The <strong>Controller</strong> handles all events and interactions with the application
and how they modify the existing model. In chess, the controller could
define that when a player drags a piece in the board, the position of that
piece in the board <em>model</em> changes to the new position, the current turn
changes to the other player, and the time passed is reset to zero.</p></li>
</ul>
<p>And the three relate in the following manner:</p>
<figure>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/MVC-Process.svg/400px-MVC-Process.svg.png" alt="MVC diagram from Wikipedia" />
<figcaption aria-hidden="true">MVC diagram from Wikipedia</figcaption>
</figure>
<h1 data-number="2" id="functional-mvc-gloss"><span class="header-section-number">2</span> Functional MVC: Gloss</h1>
<p>How does the model-view-controller idea translate into functional programming?
It turns out to be quite simple because the three parts match basic FP concepts.</p>
<p>We’ll focus on the library <strong>Gloss</strong> to develop a graphical application. Gloss
is very easy to setup, provides abstractions for drawing graphics, and
outlines the MVC compoonents clearly. We’ll implement a simple simulation of the
101companies employees to illustrate the concepts.</p>
<p>To define the model, the structure which is updated thorought the program, we
simply define a new datatype that <em>models</em> the application to be updated and
displayed. Our model will be just company itself! Nothing of Gloss comes in here.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Our model</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Company</span> <span class="ot">=</span> <span class="dt">Company</span> <span class="dt">Name</span> [<span class="dt">Employee</span>]</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Employee</span> <span class="ot">=</span> <span class="dt">Employee</span> <span class="dt">Name</span> <span class="dt">Address</span> <span class="dt">Salary</span></span></code></pre></div>
<p>The view, as mentioned before, is just a function from the model to the
graphics to be drawn. With Gloss, the graphics to be displayed are defined with
the <code>Picture</code> type. That means this is the function signature</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="ot">view ::</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Picture</span></span></code></pre></div>
<p>Ahead, we’ll see how to display things on the screen with Gloss and further
inspect the <code>Picture</code> type.</p>
<p>The model, <em>in gloss</em>, actually consists of two separate functions. The first
updates the model when events (of type <code>Event</code>) happen, and the second updates
the model when time passes. We could name these two functions <code>handleEvent</code> and
<code>frameUpdate</code>.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">handleEvent ::</span> <span class="dt">Event</span> <span class="ot">-&gt;</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Company</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ot">frameUpdate ::</span> <span class="dt">Float</span> <span class="ot">-&gt;</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Company</span></span></code></pre></div>
<p>the <code>Float</code> in <code>frameUpdate</code> is the time passed since the last frame. We’ll look
at frames and events ahead.</p>
<p>Finally, to put this all together, gloss provides a function that takes an
initial model, the view function, the controller functions, and runs the
described application.</p>
<p>Which means that if with a datatype and those three functions defined, we’re
ready to run our graphical application.</p>
<p>The function is:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Play a game in a window.</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="ot">play    ::</span> <span class="dt">Display</span>                      <span class="co">-- ^ Display mode.</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> <span class="dt">Color</span>                        <span class="co">-- ^ Background color.</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> <span class="dt">Int</span>                          <span class="co">-- ^ Number of simulation steps to take for each second of real time.</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> world                        <span class="co">-- ^ The initial world.</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> (world <span class="ot">-&gt;</span> <span class="dt">Picture</span>)           <span class="co">-- ^ A function to convert the world a picture.</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> (<span class="dt">Event</span> <span class="ot">-&gt;</span> world <span class="ot">-&gt;</span> world)    <span class="co">-- ^ A function to handle input events.</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> (<span class="dt">Float</span> <span class="ot">-&gt;</span> world <span class="ot">-&gt;</span> world)    <span class="co">-- ^ A function to step the world one iteration.</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a>                                        <span class="co">--   It is passed the period of time (in seconds) needing to be advanced.</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a>        <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</span></code></pre></div>
<p>There’s quite a bit more happening here so let’s go over each parameter:</p>
<ul>
<li><p><code>Display</code> is the window the game will run in. This can be either <code>FullScreen</code>
or <code>InWindow "Nice Window" (width, height) (10, 10)</code> in which the parameters
are the window title, the width and height of the window, and its starting
position.</p></li>
<li><p>The <code>Color</code> is for the background color of the window. The simplest colors are
<code>black</code> and <code>white</code>, and there are other functions to create colors</p></li>
<li><p>The <code>Int</code> is the number of frames in a second. Every new frame, the
<code>frameUpdate</code> function we defined previously is called (and the float passed
to it is how much time each frame lasts). For example, <code>60</code> would mean 60
frames per second, and each time the function would be passed <code>1/60 = 0.016</code>
seconds as an argument.</p></li>
<li><p>The <code>world</code> type variable stands for our model. This parameter is the initial
state of our model. We’d use some <code>initialCompany :: Company</code> here.</p></li>
<li><p>The <code>world -&gt; Picture</code> function is our view function. We’d pass <code>view ::   Company -&gt; Picture</code> here.</p></li>
<li><p>The <code>Event -&gt; world -&gt; world</code> function is half of our controller. Given an event,
we update the model. We’d pass <code>handleEvent :: Event -&gt; Company -&gt; Company</code>.</p></li>
<li><p>The <code>(Float -&gt; world -&gt; world)</code> function is the other half of the controller.
It is called every step/frame of our application (the frame rate is defined
in the <code>Int</code> parameter above). We’d pass <code>frameUpdate :: Float -&gt; Company -&gt;   Company</code> here.</p></li>
</ul>
<p>And the return type is <code>IO ()</code>! Meaning we can call this directly from main. The
main program would look like:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>    play</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>        <span class="dt">FullScreen</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>        black          <span class="co">-- Background color</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>        <span class="dv">30</span>             <span class="co">-- Number of frames for each second of real time.</span></span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>        initialCompany <span class="co">-- The company at the beginning of the game</span></span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a>        view           <span class="co">-- How to display a company?</span></span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a>        handleEvent    <span class="co">-- How to react to events?</span></span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a>        frameUpdate    <span class="co">-- What to do every frame?</span></span></code></pre></div>
<h2 data-number="2.1" id="picture"><span class="header-section-number">2.1</span> Picture</h2>
<p>In this section we explain how to create <code>Picture</code>s, and how the 101company’s
<em>view</em> is implemented.</p>
<p>In Gloss, <code>Picture</code>s are the building blocks out of which we build a graphical
application. There exist multiple ways of creating pictures; the simplest ones
are to directly use the data constructors for <code>Picture</code>.</p>
<p>For example, these would be valid pictures.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- Draws a circle with radius 5</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="dt">Circle</span> <span class="dv">5</span><span class="ot">    ::</span> <span class="dt">Picture</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- Draws some text rotated by 90º degrees</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a><span class="dt">Rotate</span> <span class="dv">90</span> (<span class="dt">Text</span> <span class="st">&quot;Hello&quot;</span>)<span class="ot">    ::</span> <span class="dt">Picture</span></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a><span class="co">-- Draws both simultaneously on the screen</span></span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a><span class="dt">Pictures</span> [<span class="dt">Circle</span> <span class="dv">5</span>, <span class="dt">Rotate</span> <span class="dv">90</span> (<span class="dt">Text</span> <span class="st">&quot;Hello&quot;</span>)]<span class="ot">   ::</span> <span class="dt">Picture</span></span></code></pre></div>
<p>As we see, we can combine pictures using the <code>Pictures</code> data constructor,
<code>Rotate</code>, <code>Translate</code>, and <code>Scale</code> them (with those data constructors), and
create them from scratch as with <code>Circle</code>, <code>Polygon</code>, etc.</p>
<p>This is more evident from the definition of <code>Picture</code>. Here is a bit from the
<a href="https://hackage.haskell.org/package/gloss-1.13.2.2/docs/Graphics-Gloss-Data-Picture.html#t:Picture">pictures
documentation</a></p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Picture</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A blank picture, with nothing in it.</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>        <span class="ot">=</span> <span class="dt">Blank</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A convex polygon filled with a solid color.</span></span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Polygon</span>       <span class="dt">Path</span></span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A circle with the given radius.</span></span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Circle</span>        <span class="dt">Float</span></span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A circle with the given radius and thickness.</span></span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a>        <span class="co">--   If the thickness is 0 then this is equivalent to `Circle`.</span></span>
<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">ThickCircle</span>   <span class="dt">Float</span> <span class="dt">Float</span></span>
<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-15"><a href="#cb7-15" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | Some text to draw with a vector font.</span></span>
<span id="cb7-16"><a href="#cb7-16" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Text</span>          <span class="dt">String</span></span>
<span id="cb7-17"><a href="#cb7-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-18"><a href="#cb7-18" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A picture translated by the given x and y coordinates.</span></span>
<span id="cb7-19"><a href="#cb7-19" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Translate</span>     <span class="dt">Float</span> <span class="dt">Float</span>     <span class="dt">Picture</span></span>
<span id="cb7-20"><a href="#cb7-20" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-21"><a href="#cb7-21" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A picture rotated clockwise by the given angle (in degrees).</span></span>
<span id="cb7-22"><a href="#cb7-22" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Rotate</span>        <span class="dt">Float</span>           <span class="dt">Picture</span></span>
<span id="cb7-23"><a href="#cb7-23" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-24"><a href="#cb7-24" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A picture scaled by the given x and y factors.</span></span>
<span id="cb7-25"><a href="#cb7-25" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Scale</span>         <span class="dt">Float</span>   <span class="dt">Float</span>   <span class="dt">Picture</span></span>
<span id="cb7-26"><a href="#cb7-26" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-27"><a href="#cb7-27" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- | A picture consisting of several others.</span></span>
<span id="cb7-28"><a href="#cb7-28" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Pictures</span>      [<span class="dt">Picture</span>]</span>
<span id="cb7-29"><a href="#cb7-29" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-30"><a href="#cb7-30" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="op">...</span> <span class="co">-- ommited for brevity</span></span></code></pre></div>
<p>Now that we’ve seen the concept of pictures, and know that they will be displayed
by the main function, we must still consider how they’re laid out on the window.</p>
<ul>
<li>The window has a width and a height, say 400x400</li>
<li>Each picture has a pair of coordinates, for it’s position on the x and y axis.
By default this position is (0,0).</li>
<li>The origin (coordinates <code>(0, 0)</code>) is located in the middle of the window.
Taking the window of 400x400, the center of the left border would be at
(-200, 0), the right border would be at (200, 0), the center of the top
border would be at (0, 200) and the bottom border at (0, -200)</li>
</ul>
<p>Now we can get to creating the view for our company! We’ll display our company
employees on the screen, one circle for each. The bigger the circle, the bigger
the pay.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Company</span> <span class="ot">=</span> <span class="dt">Company</span> <span class="dt">Name</span> <span class="dt">Employees</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Employee</span> <span class="ot">=</span> <span class="dt">Employee</span> <span class="dt">Name</span> <span class="dt">Address</span> <span class="dt">Salary</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="ot">view ::</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Picture</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>view (<span class="dt">Company</span> _ employees) <span class="ot">=</span></span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- We map each employee to its picture</span></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> emPics <span class="ot">=</span> <span class="fu">map</span> empToPicture employees</span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-10"><a href="#cb8-10" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- And make one big picture out of all of them</span></span>
<span id="cb8-11"><a href="#cb8-11" aria-hidden="true" tabindex="-1"></a>     <span class="kw">in</span> <span class="dt">Pictures</span> emPics</span>
<span id="cb8-12"><a href="#cb8-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-13"><a href="#cb8-13" aria-hidden="true" tabindex="-1"></a><span class="ot">empToPicture ::</span> <span class="dt">Employee</span> <span class="ot">-&gt;</span> <span class="dt">Picture</span></span>
<span id="cb8-14"><a href="#cb8-14" aria-hidden="true" tabindex="-1"></a>empToPicture (<span class="dt">Employee</span> name _ salary) <span class="ot">=</span></span>
<span id="cb8-15"><a href="#cb8-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-16"><a href="#cb8-16" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- We&#39;ll combine both the text and the circle into one picture</span></span>
<span id="cb8-17"><a href="#cb8-17" aria-hidden="true" tabindex="-1"></a>    <span class="dt">Pictures</span></span>
<span id="cb8-18"><a href="#cb8-18" aria-hidden="true" tabindex="-1"></a>        [ <span class="dt">Text</span> name <span class="co">-- Draw the employee&#39;s name</span></span>
<span id="cb8-19"><a href="#cb8-19" aria-hidden="true" tabindex="-1"></a>        , <span class="dt">Circle</span> (salary<span class="op">*</span><span class="fl">0.02</span>) <span class="co">-- Draw a circle with radius proportional to salary</span></span>
<span id="cb8-20"><a href="#cb8-20" aria-hidden="true" tabindex="-1"></a>        ]</span></code></pre></div>
<p>An attentive reader might comment that all employees will be displayed on top of
each other. They’re right since all pictures are by default positioned at (0,0)</p>
<p>In the demo, I drew each employee evenly spaced from the others around an
non-visible circle. The idea is to divide 360º by the number of employees and
then calculate their position using sin and cosine. There’s no need to go over
all the details, so here’s a plausible implementation of that should explain
itself.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ot">view ::</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Picture</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>view (<span class="dt">Company</span> _ employees) <span class="ot">=</span></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- We map each employee (with its number) to its picture</span></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">let</span> emPics <span class="ot">=</span> <span class="fu">map</span> empToPicture (<span class="fu">zip</span> [<span class="dv">0</span><span class="op">..</span>] employees)</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- And make one big picture out of all of them</span></span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a>     <span class="kw">in</span> <span class="dt">Pictures</span> emPics</span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a><span class="ot">    nEmployees ::</span> <span class="dt">Float</span></span>
<span id="cb9-12"><a href="#cb9-12" aria-hidden="true" tabindex="-1"></a>    nEmployees <span class="ot">=</span> <span class="fu">fromIntegral</span> (<span class="fu">length</span> employees)</span>
<span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a><span class="ot">    empToPicture ::</span> (<span class="dt">Float</span>, <span class="dt">Employee</span>) <span class="ot">-&gt;</span> <span class="dt">Picture</span></span>
<span id="cb9-15"><a href="#cb9-15" aria-hidden="true" tabindex="-1"></a>    empToPicture (i, <span class="dt">Employee</span> name _ salary) <span class="ot">=</span></span>
<span id="cb9-16"><a href="#cb9-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-17"><a href="#cb9-17" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- Move the picture according to calculation</span></span>
<span id="cb9-18"><a href="#cb9-18" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Translate</span> (<span class="dv">150</span><span class="op">*</span><span class="fu">cos</span> (<span class="dv">2</span><span class="op">*</span><span class="fu">pi</span><span class="op">*</span>i<span class="op">/</span>nEmployees)) (<span class="dv">150</span><span class="op">*</span><span class="fu">sin</span> (<span class="dv">2</span><span class="op">*</span><span class="fu">pi</span><span class="op">*</span>i<span class="op">/</span>nEmployees)) <span class="op">$</span></span>
<span id="cb9-19"><a href="#cb9-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-20"><a href="#cb9-20" aria-hidden="true" tabindex="-1"></a>            <span class="co">-- We&#39;ll combine both the text and the circle into one picture</span></span>
<span id="cb9-21"><a href="#cb9-21" aria-hidden="true" tabindex="-1"></a>            <span class="dt">Pictures</span></span>
<span id="cb9-22"><a href="#cb9-22" aria-hidden="true" tabindex="-1"></a>                [ <span class="dt">Text</span> name <span class="co">-- Draw the employee&#39;s name</span></span>
<span id="cb9-23"><a href="#cb9-23" aria-hidden="true" tabindex="-1"></a>                , <span class="dt">Circle</span> (salary<span class="op">*</span><span class="fl">0.02</span>) <span class="co">-- Draw a circle with radius proportional to salary</span></span>
<span id="cb9-24"><a href="#cb9-24" aria-hidden="true" tabindex="-1"></a>                ]</span></code></pre></div>
<p>This will layout our employees around the center, evenly spaced.</p>
<p>To finalize, we’ll add some color to the circles. We want employees which are
paid a lot of money to be represented with red circles, the ones which are paid
little money to be yellow, and the others to be orange.</p>
<p>Where we currently define the circle, we’ll rather define a colored circle</p>
<pre><code>-- Before
Circle (salary*0.02)

-- After
Color (mkColor salary) (Circle (salary*0.02))
  where
    mkColor s
      | s &gt; 10000 = red
      | s &gt; 1000 = orange
      | otherwise = yellow</code></pre>
<p>To display just the view without defining the controller we can use the
<code>display</code> function. This one is a bit simpler than <code>play</code> because it only cares
about the view.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>main</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a> <span class="ot">=</span> display</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a>        (<span class="dt">InWindow</span></span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a>               <span class="st">&quot;Hello World&quot;</span>     <span class="co">-- window title</span></span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a>                (<span class="dv">400</span>, <span class="dv">150</span>)       <span class="co">-- window size</span></span>
<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a>                (<span class="dv">10</span>, <span class="dv">10</span>))        <span class="co">-- window position</span></span>
<span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a>        white                    <span class="co">-- background color</span></span>
<span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a>        (view initialCompany)    <span class="co">-- picture to display</span></span></code></pre></div>
<p>For the final demo code see the <code>Display</code> module.</p>
<h2 data-number="2.2" id="event"><span class="header-section-number">2.2</span> Event</h2>
<p>In this section we explain Gloss’s <code>Event</code>s, and how the 101company’s
<em>controller</em> is implemented.</p>
<p>In Gloss, the <code>Event</code> type models the possible input events in the application,
such as mouse clicks, key presses, window resizes, ….</p>
<p>Everytime such an event occurs, the controller function with type <code>Event -&gt; world -&gt; world</code> is called and the input event passed as the first argument.</p>
<p>Events are defined by its data constructors:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Event</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=</span> <span class="dt">EventKey</span>    <span class="dt">Key</span> <span class="dt">KeyState</span> <span class="dt">Modifiers</span> (<span class="dt">Float</span>, <span class="dt">Float</span>)</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>    <span class="op">|</span> <span class="dt">EventMotion</span> (<span class="dt">Float</span>, <span class="dt">Float</span>)</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>    <span class="op">|</span> <span class="dt">EventResize</span> (<span class="dt">Int</span>, <span class="dt">Int</span>)</span></code></pre></div>
<p><code>EventKey</code> is the data constructor for event involving a <code>Key</code>, which could be a
mouse click or a key press, since <code>Key</code> is defined as</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Key</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>        <span class="ot">=</span> <span class="dt">Char</span>        <span class="dt">Char</span></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">SpecialKey</span>  <span class="dt">SpecialKey</span></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">MouseButton</span> <span class="dt">MouseButton</span></span></code></pre></div>
<p>A <code>Key</code> might be a simple character key, a special key, or a mouse button. For
more information on the latter two types you might check the
<a href="https://hackage.haskell.org/package/gloss-1.13.2.2/docs/Graphics-Gloss-Interface-IO-Interact.html#t:Event">documentation</a></p>
<p>A <code>KeyState</code> indicates whether the key is pressed down, or released. We’ll use
<code>Up</code>, since in our simulation we only care about when the user “finishes”
pressing a key, not while they’re pressing it</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">KeyState</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>        <span class="ot">=</span> <span class="dt">Down</span></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>        <span class="op">|</span> <span class="dt">Up</span></span></code></pre></div>
<p>Our controller function will have to pattern match on <code>Event</code> to decide how the
model should be updated.</p>
<p>We want to react to three different events: When <code>C</code> is pressed we cut the
salaries of the employees in half; when <code>A</code> is pressed we add an employee; when
<code>D</code> is pressed we delete an employee.</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="ot">eventHandler ::</span> <span class="dt">Event</span> <span class="ot">-&gt;</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Company</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>eventHandler evt c <span class="ot">=</span> <span class="kw">case</span> evt <span class="kw">of</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- &#39;c&#39; key was pressed, cut</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>    <span class="dt">EventKey</span> (<span class="dt">Key</span> <span class="ch">&#39;c&#39;</span>) <span class="dt">Up</span> _ _ <span class="ot">-&gt;</span> cut c</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- &#39;d&#39; key was pressed, delete</span></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a>    <span class="dt">EventKey</span> (<span class="dt">Key</span> <span class="ch">&#39;d&#39;</span>) <span class="dt">Up</span> _ _ <span class="ot">-&gt;</span> deleteEmp c</span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- &#39;a&#39; key was pressed, add</span></span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a>    <span class="dt">EventKey</span> (<span class="dt">Key</span> <span class="ch">&#39;a&#39;</span>) <span class="dt">Up</span> _ _ <span class="ot">-&gt;</span> addEmp c</span>
<span id="cb15-11"><a href="#cb15-11" aria-hidden="true" tabindex="-1"></a>     </span>
<span id="cb15-12"><a href="#cb15-12" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- For all other cases we return the company unchanged</span></span>
<span id="cb15-13"><a href="#cb15-13" aria-hidden="true" tabindex="-1"></a>    _ <span class="ot">-&gt;</span> c</span></code></pre></div>
<p>The <code>cut</code>, <code>deleteEmp</code> and <code>addEmp</code> are simple functions of type <code>Company -&gt; Company</code></p>
<p>As for the other part of the controller: We want the salary of all
employees to be raised every frame.</p>
<p>We can write our <code>Float -&gt; Company -&gt; Company</code> to raise the employees salaries
by 10€ everytime it’s called – as long as the employee earns less than 10000€.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="ot">frameUpdate ::</span> <span class="dt">Float</span> <span class="ot">-&gt;</span> <span class="dt">Company</span> <span class="ot">-&gt;</span> <span class="dt">Company</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>frameUpdate _ (<span class="dt">Company</span> n emps) <span class="ot">=</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>    <span class="dt">Company</span> n <span class="op">$</span> <span class="fu">map</span> (raise (<span class="op">&lt;</span> <span class="dv">10000</span>) <span class="dv">10</span>) emps</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a><span class="ot">    raise ::</span> (<span class="dt">Salary</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> <span class="dt">Salary</span> <span class="ot">-&gt;</span> <span class="dt">Employee</span> <span class="ot">-&gt;</span> <span class="dt">Employee</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>    raise p inc (<span class="dt">Employee</span> n a s) <span class="ot">=</span> <span class="dt">Employee</span> n a ((<span class="kw">if</span> p s <span class="kw">then</span> inc <span class="kw">else</span> <span class="dv">0</span>) <span class="op">+</span> s)</span></code></pre></div>
<p>The demo code can be read in the <code>Main</code> module.</p>
<h2 data-number="2.3" id="gloss"><span class="header-section-number">2.3</span> Gloss</h2>
<p>Gloss is a framework for programming graphical applications in Haskell, which
is itself described in terms of the <strong>MVC</strong> pattern.</p>
<p>In Haskell (and other strongly-typed functional programming languages) in
particular, the <strong>MVC</strong> pattern is less loosely defined than usual, and can be
more clearly identified in the code. This is because the we can “strongly”
encode our <em>model</em> with types and the <em>view</em> and <em>controller</em> are simply
functions defined in terms of the model type. Pure functions and user-defined
types get us a clearer distinction between the three.</p>
<p>Hello World:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>main</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a> <span class="ot">=</span> display</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>        (<span class="dt">InWindow</span></span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a>               <span class="st">&quot;Hello World&quot;</span>     <span class="co">-- window title</span></span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a>                (<span class="dv">400</span>, <span class="dv">150</span>)       <span class="co">-- window size</span></span>
<span id="cb17-7"><a href="#cb17-7" aria-hidden="true" tabindex="-1"></a>                (<span class="dv">10</span>, <span class="dv">10</span>))        <span class="co">-- window position</span></span>
<span id="cb17-8"><a href="#cb17-8" aria-hidden="true" tabindex="-1"></a>        white                    <span class="co">-- background color</span></span>
<span id="cb17-9"><a href="#cb17-9" aria-hidden="true" tabindex="-1"></a>        picture                  <span class="co">-- picture to display</span></span>
<span id="cb17-10"><a href="#cb17-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-11"><a href="#cb17-11" aria-hidden="true" tabindex="-1"></a><span class="ot">picture ::</span> <span class="dt">Picture</span></span>
<span id="cb17-12"><a href="#cb17-12" aria-hidden="true" tabindex="-1"></a>picture <span class="ot">=</span> <span class="dt">Translate</span> (<span class="op">-</span><span class="dv">170</span>) (<span class="op">-</span><span class="dv">20</span>) <span class="co">-- shift the text to the middle of the window</span></span>
<span id="cb17-13"><a href="#cb17-13" aria-hidden="true" tabindex="-1"></a>        <span class="op">$</span> <span class="dt">Scale</span> <span class="fl">0.5</span> <span class="fl">0.5</span>          <span class="co">-- display it half the original size</span></span>
<span id="cb17-14"><a href="#cb17-14" aria-hidden="true" tabindex="-1"></a>        <span class="op">$</span> <span class="dt">Text</span> <span class="st">&quot;Hello World&quot;</span>     <span class="co">-- text to display</span></span></code></pre></div>
<!-- --- -->
<!-- Draft part below -->
<!-- ================ -->
<!-- TODO: Não esquecer de mostrar outros exemplos de coisas feitas em gloss, se -->
<!-- calhar até no início -->
<!-- After seeing how we can display some simple text on the screen, let's work on -->
<!-- building a representation of our company. To avoid taking care of positioning -->
<!-- we'll simply display the employees along a circle, making a bigger circle for a -->
<!-- better paid employee. -->
<!-- And now we can add names to them. Let's display them at the top left corner of the circle -->
<!-- To extend our simulation we'll say that the company raises the salary of -->
<!-- everyone that isn't making > $10000 by $250 everyday. It is up to the manager to -->
<!-- keep on cutting the salaries before they run out of money. -->
<!-- Controller -->
<!-- ========== -->
<!-- When writing a controller, that is, a function that updates the state of the -->
<!-- world, we want to react to both user events, such as mouse clicks, but also to -->
<!-- the passing of time. -->
<!-- Considering this, the controller in gloss is defined with two separate -->
<!-- functions: one to control the time moving forward, and the other to react to -->
<!-- user events. -->
<!-- These two functions are passed to the main `play` function i.e. `play` takes two -->
<!-- higher order functions that control events and time -->
]]></summary>
</entry>
<entry>
    <title>Haskell 102 Lecture Notes</title>
    <link href="http://alt-romes.github.io/posts/lectures/2022-05-08-lecture-2.html" />
    <id>http://alt-romes.github.io/posts/lectures/2022-05-08-lecture-2.html</id>
    <published>2022-05-08T00:00:00Z</published>
    <updated>2022-05-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#functions-types-currying-partial-application-higher-order-functions" id="toc-functions-types-currying-partial-application-higher-order-functions"><span class="toc-section-number">1</span> Functions Types, Currying, Partial application, Higher-order functions</a></li>
<li><a href="#laziness" id="toc-laziness"><span class="toc-section-number">2</span> Laziness</a></li>
<li><a href="#recursion-inductive-method" id="toc-recursion-inductive-method"><span class="toc-section-number">3</span> Recursion: Inductive Method</a></li>
<li><a href="#recursive-data-structures" id="toc-recursive-data-structures"><span class="toc-section-number">4</span> Recursive data structures</a></li>
<li><a href="#type-classes" id="toc-type-classes"><span class="toc-section-number">5</span> Type Classes</a></li>
<li><a href="#type-classes-kinds-constraints" id="toc-type-classes-kinds-constraints"><span class="toc-section-number">6</span> Type Classes Kinds, Constraints</a></li>
</ul>
</div>
<h1 data-number="1" id="functions-types-currying-partial-application-higher-order-functions"><span class="header-section-number">1</span> Functions Types, Currying, Partial application, Higher-order functions</h1>
<p>All functions have a type, the <em>function type</em>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> [] <span class="ot">=</span> <span class="dv">0</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="dv">1</span> <span class="op">+</span> <span class="fu">length</span> xs</span></code></pre></div>
<p>The same way we think about the <code>Either</code> type constructor, and about the tuple
type constructor <code>(,)</code>, we can think about the function type type constructor
(the arrow <code>-&gt;</code>). They are all type constructors that take two arguments.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Either</span> a b <span class="ot">=</span> <span class="dt">Left</span> a <span class="op">|</span> <span class="dt">Right</span> b</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> (,) a b <span class="ot">=</span> (a, b)     <span class="co">-- pseudo code</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> (<span class="ot">-&gt;</span>) a b <span class="ot">=</span> a <span class="ot">-&gt;</span> b    <span class="co">-- pseudo code</span></span></code></pre></div>
<p>This means that the <code>(-&gt;)</code> type constructor, when applied to two types <code>a</code> and <code>b</code>, creates
a new type <code>a -&gt; b</code>, where <code>a</code> is the input type and <code>b</code> the return type.</p>
<p>This beggets the question, what is the type of a function that takes two
arguments? There are two ways to define multi-argument functions.</p>
<p>The first would be to think about functions that receive multiple arguments in a
tuple.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">prepend ::</span> (<span class="dt">Char</span>, <span class="dt">String</span>) <span class="ot">-&gt;</span> <span class="dt">String</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>prepend (c, str) <span class="ot">=</span> c<span class="op">:</span>str</span></code></pre></div>
<p>You could even use it like this <code>prepend('h', "ello")</code>, which somewhat resembles
the imperative style function call.</p>
<p>The second option is to have a function take one argument <code>a</code>, and return a
function that takes another argument <code>b</code> and only then returns <code>c</code>.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">prepend ::</span> <span class="dt">Char</span> <span class="ot">-&gt;</span> (<span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">String</span>)</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>prepend c <span class="ot">=</span> (\str <span class="ot">-&gt;</span> c<span class="op">:</span>str)</span></code></pre></div>
<p>And this is the most common way to have multi-argument functions in functional
programming languages. In Haskell, thinking about two argument functions and
functions that return functions is really the same thing.</p>
<p>The most common way of writing the two argument function <code>prepend</code> in Haskell,
read “<code>prepend</code> is a function that takes <em>two</em> arguments of type <code>Char</code> and <code>String</code>
and returns <code>String</code>”, would be</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">prepend ::</span> <span class="dt">Char</span> <span class="ot">-&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">String</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>prepend c str <span class="ot">=</span> c<span class="op">:</span>str</span></code></pre></div>
<p>The <code>(Char, String) -&gt; String</code> version is said to be an <em>uncurried</em> function,
while <code>Char -&gt; String -&gt; String</code> is said to be <em>curried</em>.</p>
<p>An advantage in using <em>curried</em> functions is the possibility to partially apply
them.</p>
<p>We can define a new function that always prepends <code>B</code> in terms of <code>prepend</code> by
partially applying <code>prepend</code> (that is, applying the function to a partial number
of arguments)</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>prependB <span class="ot">=</span> prepend <span class="ch">&#39;B&#39;</span></span></code></pre></div>
<p>Partial application is useful in everyday functional programming; A common
example is passing partially applied functions to functions that take functions:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="fu">map</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [b]</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- Given a list of strings, prepend C to them all</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a><span class="ot">prependAll ::</span> [<span class="dt">String</span>] <span class="ot">-&gt;</span> [<span class="dt">String</span>]</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>prependAll strs <span class="ot">=</span> <span class="fu">map</span> (prepend <span class="ch">&#39;C&#39;</span>) strs</span></code></pre></div>
<p>In functional programming, functions are <em>first-class</em>, meaning they can be
passed as parameters and returned from functions. Functions used in those ways
are said to be higher-order functions</p>
<p>As an end note on function types, notice that the “correct use” of <code>-&gt;</code> type constructor is enforced by the
kind system, the same way the usage of <code>Either</code> is enforced by the kind system.
The kinds of these type constructors are:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Either</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> (,)<span class="ot">    ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span><span class="ot"> (-&gt;)   ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span></span></code></pre></div>
<p>To have a function type we must supply both type arguments to the <code>-&gt;</code> type
constructor (i.e. <code>Int -&gt; Char</code> is a valid <em>type</em>), but what happens if we
<em>partially apply</em> the type constructor?</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> (<span class="ot">-&gt;</span>) <span class="dt">Int</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">FunctionFromInt</span> <span class="ot">=</span> (<span class="ot">-&gt;</span>) <span class="dt">Int</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">FunctionFromInt</span> <span class="dt">Char</span><span class="ot"> ::</span> <span class="op">*</span> <span class="co">-- equivalent to `Int -&gt; Char`</span></span></code></pre></div>
<h1 data-number="2" id="laziness"><span class="header-section-number">2</span> Laziness</h1>
<p><small>This section derives from <a href="https://www.haskell.org/tutorial/functions.html">A Gentle Introduction to Haskell</a></small></p>
<p>Suppose <code>bot</code> is defined by:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>bot <span class="ot">=</span> bot</span></code></pre></div>
<p>In other words, <code>bot</code> is a non-terminating expression. Abstractly, we denote the
value of a non-terminating expression as <em>|</em>. Expressions that result in some
kind of a run-time error, such as 1/0, also have this value. Such an error is
not recoverable: programs will not continue past these errors.</p>
<p>A function <code>f</code> is said to be <em>strict</em> if, when applied to a nonterminating
expression, it also fails to terminate. In other words, f is <em>strict</em> iff the
value of <code>f bot</code> is <code>bot</code>. For most programming languages, all functions are strict.
But this is not so in Haskell.</p>
<p>As a simple example, consider const1, the constant 1 function, defined by:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>const1 x <span class="ot">=</span> <span class="dv">1</span></span></code></pre></div>
<p>The value of <code>const1 bot</code> in Haskell is <code>1</code>. Operationally speaking, since <code>const1</code>
does not <em>need</em> the value of its argument, it never attempts to evaluate it, and
thus never gets caught in a nonterminating computation. For this reason,
non-strict functions are also called <em>lazy functions</em>, and are said to evaluate
their arguments <em>lazily</em>, or <em>by need</em>.</p>
<p>Another way of explaining non-strict functions is that Haskell computes using
definitions rather than the assignments found in traditional languages. Read a
declaration such as</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a>v <span class="ot">=</span> <span class="dv">1</span><span class="op">/</span><span class="dv">0</span></span></code></pre></div>
<p>as define <code>v</code> as <code>1/0</code> instead of compute <code>1/0</code> and store the result in <code>v</code>. Only if
the value (definition) of <code>v</code> is needed will the division by zero error occur. By
itself, this declaration does not imply any computation. Programming using
assignments requires careful attention to the ordering of the assignments: the
meaning of the program depends on the order in which the assignments are
executed. Definitions, in contrast, are much simpler: they can be presented in
any order without affecting the meaning of the program.</p>
<h1 data-number="3" id="recursion-inductive-method"><span class="header-section-number">3</span> Recursion: Inductive Method</h1>
<p>Inspired on <a href="http://ctp.di.fct.unl.pt/~amd/lap/teoricas/03.html">AMD - Teórica 3</a>.</p>
<p>A well defined recursive function does case analysis over its parameters.</p>
<p>The <strong>base cases</strong> are the ones that don’t lead to recursive calls of the
function. The <strong>general cases</strong> are those that lead to, directly or indirectly,
recursive calls of the function.</p>
<p>The <em>inductive method</em> helps the programmer reason about the logical properties
of the problem to solve:
* The trivial case should be dealt with trivially
* The general case should be dealt with by <em>reducing the problem to a simpler
problem</em>
When reducing the problem to a simpler one, assume the simpler one is already
solved, and try to form the result based on that answer. In practice, the
simpler problem is solved by the recursive call.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>fact <span class="dv">0</span> <span class="ot">=</span> <span class="dv">1</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>fact n <span class="ot">=</span> n <span class="op">*</span> fact (n<span class="op">-</span><span class="dv">1</span>)</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> [] <span class="ot">=</span> <span class="dv">0</span></span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="dv">1</span> <span class="op">+</span> <span class="fu">length</span> xs</span></code></pre></div>
<p>Analysing these recursive functions, we note that when dealing with the
<strong>general case</strong> (the non-trivial case), they both <em>reduce the original problem
to a simpler instance</em> of the same problem. the <code>length</code> function reduces the
original problem <code>length (x:xs)</code> to the simpler <code>length xs</code>, and the function
<code>fact</code> reduces the problem <code>fact n</code> to the simler problem <code>fact (n-1)</code>.</p>
<p>Assuming the simpler problem is already solved (what is the length of <code>xs</code>?), we
can just think about the step to take to the solution, which is add <code>1</code> to the
recursive call result.</p>
<h1 data-number="4" id="recursive-data-structures"><span class="header-section-number">4</span> Recursive data structures</h1>
<p>Data structures can use themselves to define themselves, or in other words,
define themselves recursively. When they do so, they can be called <em>recursive
data types</em>.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Tree</span> a <span class="ot">=</span> <span class="dt">Leaf</span> <span class="op">|</span> <span class="dt">Node</span> a (<span class="dt">Tree</span> a) (<span class="dt">Tree</span> a)</span></code></pre></div>
<p>A <code>Tree</code> here is defined in terms of other <code>Tree</code>s. A <code>Tree</code> of <code>a</code>s can be either a
<code>Leaf</code> or a <code>Node</code> with a value of type <code>a</code> and two subtrees.</p>
<p>Recursive data types are expressive kinds of structures and a very idiom in
functional programming. For example, we can clearly express a simple calculator
language through a recursive data type <code>Expr</code>.</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Expr</span> <span class="ot">=</span> <span class="dt">Const</span> <span class="dt">Int</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>          <span class="op">|</span> <span class="dt">Add</span> <span class="dt">Expr</span> <span class="dt">Expr</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>          <span class="op">|</span> <span class="dt">Mult</span> <span class="dt">Expr</span> <span class="dt">Expr</span></span></code></pre></div>
<p>This way, we can represent numerical expressions in through our datatype:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- 5</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="dt">Const</span> <span class="dv">5</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- 6 * 2</span></span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a><span class="dt">Mult</span> (<span class="dt">Const</span> <span class="dv">6</span>) (<span class="dt">Const</span> <span class="dv">2</span>)</span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a><span class="co">-- 2 + 3 * 4</span></span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a><span class="dt">Mult</span> (<span class="dt">Add</span> (<span class="dt">Const</span> <span class="dv">2</span>) (<span class="dt">Const</span> <span class="dv">3</span>)) (<span class="dt">Const</span> <span class="dv">4</span>)</span></code></pre></div>
<p>And easily define recursive operations on it:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="ot">calculate ::</span> <span class="dt">Expr</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>calculate (<span class="dt">Const</span> i) <span class="ot">=</span> i</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>calculate (<span class="dt">Add</span> x y) <span class="ot">=</span> calculate x <span class="op">+</span> calculate y</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>calculate (<span class="dt">Mult</span> x y) <span class="ot">=</span> calculate x <span class="op">*</span> calculate y</span></code></pre></div>
<p>Because of Haskell’s laziness, we can even make infinite values of this recursive type.</p>
<p>Write a function that creates an infinite tree of length <code>n</code> given <code>n :: Int</code></p>
<div class="sourceCode" id="cb18"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="ot">infiniteTree ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Tree</span> a</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>infiniteTree <span class="ot">=</span> <span class="fu">undefined</span></span></code></pre></div>
<p>What about an expression that infinitely adds <code>n</code>?</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- infiniteAdd 5 &lt;=&gt; 5 + 5 + 5 + ... + 5 + ... + 5 + ...</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a><span class="ot">infiniteAdd ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Expr</span></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>infiniteAdd <span class="ot">=</span> <span class="fu">undefined</span></span></code></pre></div>
<p>One can then write functions to make use of these infinite structures. For
example, a function that given an infinite expression of adding <code>n</code>, adds <code>n</code>
<code>k</code> amount of times (that is, a function that multiplies <code>n</code> by <code>k</code> through
creating an infinite addition expression).</p>
<p>The most common example of an infinite structure is the infinite list and
operations on it</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>[<span class="dv">1</span><span class="op">..</span>] <span class="co">-- [1,2,3,4,5,6,7......</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="fu">take</span> <span class="dv">5</span> [<span class="dv">1</span><span class="op">..</span>] <span class="co">-- [1,2,3,4,5]</span></span></code></pre></div>
<p>Could you write a generator of infinite lists starting at <code>n</code>?</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">List</span> a <span class="ot">=</span> <span class="dt">Nil</span> <span class="op">|</span> <span class="dt">Cons</span> a (<span class="dt">List</span> a)</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a><span class="ot">infList ::</span> n <span class="ot">-&gt;</span> <span class="dt">List</span> a</span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a>infList <span class="ot">=</span> <span class="fu">undefined</span></span></code></pre></div>
<h1 data-number="5" id="type-classes"><span class="header-section-number">5</span> Type Classes</h1>
<p>Previously we saw <em>parametric polymorphism</em>, and how a function needed to treat the polymorphic
types agnostically, that is, the polymorphic type could be instanced by any type
and the expression would still be valid. A common example is the map function</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="fu">map</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [b]</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a><span class="fu">map</span> _ [] <span class="ot">=</span> []</span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a><span class="fu">map</span> f (x<span class="op">:</span>xs) <span class="ot">=</span> f x<span class="op">:</span><span class="fu">map</span> f xs</span></code></pre></div>
<p>In which the elements of the list are treated agnostically – they could have any
type and this function would still typecheck.</p>
<p>Sometimes, however, we desire a function to be polymorphic over just some types,
for example, a function polymorphic over all types for which equality <code>(==)</code> is
defined.</p>
<p>We don’t want to define multiple equal functions just with different types,
neither do we want a fully polymorphic function because equality isn’t defined
for all types (e.g. the <code>Expr</code>s we created previously).</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual1 ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual2 ::</span> [<span class="dt">Char</span>] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual3 ::</span> [<span class="dt">Bool</span>] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb23-4"><a href="#cb23-4" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual4 ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Bool</span> <span class="co">-- how to compare a?</span></span></code></pre></div>
<p>That’s where <em>type-class polymorphism</em> (also known as <em>ad-hoc polymorphism</em>)
comes into play. We can define a <strong>type class</strong> which corresponds to a set of
types which have certain operations defined for them, and we can define
<em>type-class polymorphic</em> functions which can only be called on types which
instance the said type-class.</p>
<p>Let’s define a type class for equality. Any <em>type</em> that <em>instances</em> this <em>type
class</em> <code>Eq</code>, or in other words, any <em>type</em> that belongs to the <em>set of types</em> that
support the equality comparison <code>(==)</code>, well, can be compared using <code>==</code>.</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a>      <span class="op">+</span> <span class="co">--- class name</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a>      <span class="op">|</span></span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a>      v</span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Eq</span> a <span class="kw">where</span></span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a><span class="ot">    (==) ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a>      <span class="op">^</span></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a>      <span class="op">|</span></span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a>      <span class="op">+</span> <span class="co">--- operation that must be defined for all instances of `Eq`</span></span></code></pre></div>
<p>We can then define <em>type-class polymorphic</em> functions such as <code>allEqual</code>, which
take a polymorphic type <code>a</code>, as long as <code>a</code> instances <code>Eq</code> (<code>Eq a =&gt; a</code>).</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a>             <span class="op">+</span> <span class="co">-- Constraint</span></span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a>             <span class="op">|</span>          <span class="op">+</span> <span class="co">-- Function type, where `a` must instance `Eq`</span></span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a>             v          v</span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a>            _____   ___________</span>
<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual ::</span> <span class="dt">Eq</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a>allEqual [] <span class="ot">=</span> <span class="dt">True</span></span>
<span id="cb25-7"><a href="#cb25-7" aria-hidden="true" tabindex="-1"></a>allEqual [x] <span class="ot">=</span> <span class="dt">True</span></span>
<span id="cb25-8"><a href="#cb25-8" aria-hidden="true" tabindex="-1"></a>allEqual (x<span class="op">:</span>y<span class="op">:</span>xs) <span class="ot">=</span> x <span class="op">==</span> y <span class="op">&amp;&amp;</span> allEqual xs</span></code></pre></div>
<p>If we then called <code>allEqual</code> on a list of <code>Expr</code>, it still wouldn’t work –
that’s because <code>Expr</code> doesn’t instance <code>Eq</code> (how do you compare two <code>Expr</code>?)</p>
<div class="sourceCode" id="cb26"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a>allEqual [<span class="dt">Const</span> <span class="dv">5</span>, <span class="dt">Const</span> <span class="dv">5</span>, <span class="dt">Add</span> (<span class="dt">Const</span> <span class="dv">6</span>) (<span class="dt">Const</span> <span class="dv">7</span>)]</span></code></pre></div>
<p>To define an <em>instance</em> of a type class for some type, we use the <code>instance</code>
keyword in the following way:</p>
<div class="sourceCode" id="cb27"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a>         <span class="op">+</span> <span class="co">--- class name</span></span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a>         <span class="op">|</span>   <span class="op">+</span> <span class="co">--- instancing type</span></span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a>         v   v</span>
<span id="cb27-4"><a href="#cb27-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Eq</span> <span class="dt">Expr</span> <span class="kw">where</span></span>
<span id="cb27-5"><a href="#cb27-5" aria-hidden="true" tabindex="-1"></a> <span class="co">-- (==) :: Expr -&gt; Expr -&gt; Bool</span></span>
<span id="cb27-6"><a href="#cb27-6" aria-hidden="true" tabindex="-1"></a>    (<span class="op">==</span>) x y <span class="ot">=</span> <span class="kw">case</span> (x,y) <span class="kw">of</span></span>
<span id="cb27-7"><a href="#cb27-7" aria-hidden="true" tabindex="-1"></a>        (<span class="dt">Const</span> i, <span class="dt">Const</span> j) <span class="ot">-&gt;</span> i <span class="op">==</span> j</span>
<span id="cb27-8"><a href="#cb27-8" aria-hidden="true" tabindex="-1"></a>        (<span class="dt">Add</span> z w, <span class="dt">Add</span> k p) <span class="ot">-&gt;</span> z <span class="op">==</span> k <span class="op">&amp;&amp;</span> w <span class="op">==</span> p</span>
<span id="cb27-9"><a href="#cb27-9" aria-hidden="true" tabindex="-1"></a>        (<span class="dt">Mult</span> z w, <span class="dt">Mult</span> k p) <span class="ot">-&gt;</span> z <span class="op">==</span> k <span class="op">&amp;&amp;</span> w <span class="op">==</span> p</span>
<span id="cb27-10"><a href="#cb27-10" aria-hidden="true" tabindex="-1"></a>        (_, _) <span class="ot">-&gt;</span> <span class="dt">False</span></span></code></pre></div>
<p>After which <code>allEqual [Const 2, Const 2]</code> would return <code>True</code>.</p>
<h1 data-number="6" id="type-classes-kinds-constraints"><span class="header-section-number">6</span> Type Classes Kinds, Constraints</h1>
<p>Let’s begin with this set up</p>
<div class="sourceCode" id="cb28"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Box</span> a <span class="ot">=</span> <span class="dt">MkBox</span> a</span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-3"><a href="#cb28-3" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Eq</span> a <span class="kw">where</span></span>
<span id="cb28-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a><span class="ot">    (==) ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a</span>
<span id="cb28-5"><a href="#cb28-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-6"><a href="#cb28-6" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual ::</span> <span class="dt">Eq</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span></code></pre></div>
<p>And now let’s revisit <em>kinds</em>.
The kind of a simple type such as <code>Int</code>, is <code>*</code>.
The kind of a type constructor such as <code>Box</code> is <code>* -&gt; *</code>
The kind of a type constructor applied to a type, such as <code>Box Int</code> is <code>*</code>.</p>
<div class="sourceCode" id="cb29"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Int</span><span class="ot"> ::</span> <span class="op">*</span></span>
<span id="cb29-2"><a href="#cb29-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Box</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span></span>
<span id="cb29-3"><a href="#cb29-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Box</span> <span class="dt">Int</span><span class="ot"> ::</span> <span class="op">*</span></span></code></pre></div>
<p>Now imagine there existed a kind called <code>MagicalKind</code>, and we could define type operators
that returned types of this kind</p>
<div class="sourceCode" id="cb30"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Magic</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="dt">MagicalKind</span></span></code></pre></div>
<p>The <code>Magic</code> type operator receives a <code>*</code> and returns <code>MagicalKind</code>. <code>*</code> is a
kind, <code>MagicalKind</code> is a kind, and their combination through the kind arrow
<code>(-&gt;)</code> is also a kind.</p>
<p>If we applied <code>Magic</code> to some type, say, <code>Int</code>, we’d get something of kind
<code>MagicalKind</code>.</p>
<div class="sourceCode" id="cb31"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Magic</span> <span class="dt">Int</span><span class="ot"> ::</span> <span class="dt">MagicalKind</span></span></code></pre></div>
<p>There are other kinds besides <code>*</code> and kinds constructed with <code>-&gt;</code>. There exists
an important kind called <code>Constraint</code>, and there exist type operators that
return types of kind <code>Constraint</code>.</p>
<p>Those type operators are defined through type classes. Our <code>Eq</code> class has a
kind:</p>
<div class="sourceCode" id="cb32"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Eq</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="dt">Constraint</span></span></code></pre></div>
<p>Which means that <code>Eq</code> applied to <code>Int</code>, <code>Eq Int</code>, has kind <code>Constraint</code>.</p>
<p>It’s the kind system that enforces the correct usage of constraints and type classes.
Going back to the set up of this section, how could we create an instance of <code>Eq</code> for <code>Box</code>?</p>
<div class="sourceCode" id="cb33"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Eq</span> <span class="dt">Box</span> <span class="kw">where</span></span>
<span id="cb33-2"><a href="#cb33-2" aria-hidden="true" tabindex="-1"></a>    (<span class="op">==</span>) <span class="ot">=</span> <span class="fu">undefined</span></span></code></pre></div>
<p>This would actually not compile! Why? Let’s inspect the kinds.</p>
<div class="sourceCode" id="cb34"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Eq</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="dt">Constraint</span></span>
<span id="cb34-2"><a href="#cb34-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Box</span><span class="ot"> ::</span> <span class="op">*</span> <span class="ot">-&gt;</span> <span class="op">*</span></span>
<span id="cb34-3"><a href="#cb34-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Box</span><span class="ot"> a ::</span> <span class="op">*</span></span></code></pre></div>
<p>When we write <code>Eq Box</code>, <code>Eq</code> is expecting a type of kind <code>*</code>, but we pass it
<code>Box</code> of kind <code>* -&gt; *</code>!</p>
<p>A correct instance could be formulated as follows</p>
<div class="sourceCode" id="cb35"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb35-1"><a href="#cb35-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Eq</span> (<span class="dt">Box</span> a) <span class="kw">where</span></span>
<span id="cb35-2"><a href="#cb35-2" aria-hidden="true" tabindex="-1"></a>    (<span class="dt">Box</span> x) <span class="op">==</span> (<span class="dt">Box</span> y) <span class="ot">=</span> <span class="dt">True</span> <span class="co">-- We define two boxes to be always equal</span></span></code></pre></div>
<p>Now, <code>Box a</code> has kind <code>*</code>, and so <code>Eq (Box a)</code> is correctly formulated.</p>
<p>Finally, let’s look at the <code>Constraint</code> kind. When defining a type class
polymorphic function, we use the <code>=&gt;</code> symbol. On the left side of the symbol we
must have <em>constraints</em>, and on the right, <em>types</em>. The kind system also
enforces this.</p>
<div class="sourceCode" id="cb36"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb36-1"><a href="#cb36-1" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual ::</span> <span class="dt">Eq</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span></code></pre></div>
<p>This is a correct function definition. <code>Eq a</code> has kind <code>Constraint</code>, and so it
can comfortably sit on the left side of <code>=&gt;</code>. If we were, however, to write</p>
<div class="sourceCode" id="cb37"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true" tabindex="-1"></a><span class="ot">allEqual ::</span> <span class="dt">Box</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Bool</span></span></code></pre></div>
<p>We’d get an error complaining about how <code>Box a</code> should have kind <code>Constraint</code>,
but in reality has kind <code>*</code>.</p>
<p>Suggested reading: <a href="https://www.cis.upenn.edu/~cis194/spring13/lectures/05-type-classes.html">Type Classes</a></p>
]]></summary>
</entry>
<entry>
    <title>Haskell 101 Lecture Notes</title>
    <link href="http://alt-romes.github.io/posts/lectures/2022-05-04-lecture.html" />
    <id>http://alt-romes.github.io/posts/lectures/2022-05-04-lecture.html</id>
    <published>2022-05-04T00:00:00Z</published>
    <updated>2022-05-04T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="toc"><div class="header">Contents</div>
<ul>
<li><a href="#functions-computations-abstraction-and-application" id="toc-functions-computations-abstraction-and-application"><span class="toc-section-number">1</span> Functions, Computations: Abstraction and application</a></li>
<li><a href="#expressions-values-types" id="toc-expressions-values-types"><span class="toc-section-number">2</span> Expressions, Values, Types</a></li>
<li><a href="#adts-construction-deconstruction" id="toc-adts-construction-deconstruction"><span class="toc-section-number">3</span> ADTs, Construction, Deconstruction</a></li>
<li><a href="#polymorphism" id="toc-polymorphism"><span class="toc-section-number">4</span> Polymorphism</a></li>
<li><a href="#non-nullary-type-constructors-kinds" id="toc-non-nullary-type-constructors-kinds"><span class="toc-section-number">5</span> Non-nullary type constructors, Kinds</a></li>
</ul>
</div>
<h1 data-number="1" id="functions-computations-abstraction-and-application"><span class="header-section-number">1</span> Functions, Computations: Abstraction and application</h1>
<p>What is a function? <span class="math inline"><em>f</em>(<em>x</em>) = 4<em>x</em> + 2</span>?
And what’s function application?</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>f(x) <span class="ot">=</span> <span class="dv">4</span>x <span class="op">+</span> <span class="dv">2</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>f(<span class="dv">5</span>) <span class="ot">=</span> <span class="op">?</span></span></code></pre></div>
<blockquote>
<p>In mathematics, function application is the act of applying a function to an
argument from its domain so as to obtain the corresponding value from its range.
In this sense, function application can be thought of as the opposite of
function abstraction.</p>
</blockquote>
<p>In functional programming languages, <em>computations</em> are based on function
<em>abstraction</em> and <em>application</em>. An <em>abstraction</em>, a.k.a a function, is denoted
through the lambda notation (<code>\x -&gt; ...</code>). An <em>application</em>, a.k.a function
application, is denoted by <em>juxtaposition</em>: an expression followed by another
expression represents the application of the first expression to the following
one.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>f <span class="ot">=</span> \x <span class="ot">-&gt;</span> <span class="dv">4</span> <span class="op">*</span> x <span class="op">+</span> <span class="dv">2</span> <span class="co">-- `f` is an abstraction</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>f <span class="dv">5</span> <span class="co">-- application of `f` to `5`</span></span></code></pre></div>
<h1 data-number="2" id="expressions-values-types"><span class="header-section-number">2</span> Expressions, Values, Types</h1>
<p>Haskell is a purely functional programming language. As such, all computations
are done via the <em>evaluation</em> of <em>expressions</em> (syntactic terms) to yield
<em>values</em> (abstract entities that we regard as answers). Every value has an
associated <em>type</em> (intuitively, we can think of types as sets of values).</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="dv">5</span><span class="ot"> ::</span> <span class="dt">Integer</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ch">&#39;a&#39;</span><span class="ot"> ::</span> <span class="dt">Char</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="ot">inc ::</span> <span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Integer</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>[<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]<span class="ot"> ::</span> [<span class="dt">Integer</span>]</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>(<span class="ch">&#39;b&#39;</span>, <span class="dv">4</span>)<span class="ot"> ::</span> (<span class="dt">Char</span>, <span class="dt">Int</span>)</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a><span class="fu">sum</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]<span class="ot"> ::</span> <span class="dt">Integer</span></span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>inc <span class="dv">5</span><span class="ot"> ::</span> <span class="dt">Integer</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a><span class="fu">sum</span><span class="ot"> ::</span> [<span class="dt">Integer</span>] <span class="ot">-&gt;</span> <span class="dt">Integer</span></span></code></pre></div>
<p>The <code>::</code> can be read “has type”. All expression evaluate to a value, and all
values have types, which means all expressions have types too. Above are some of
the common types.</p>
<p>Which of the following are expressions, and which are values? What are the types
of the expressions?</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="fu">product</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>[<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="fu">product</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]</span></code></pre></div>
<p>They are all <em>expressions</em>, and only the first two are <em>value</em>s. The first
one is a function abstraction, which is a value, the second one is a value
constructed with the data constructors of <code>List</code>, but the third one, however, is a
function application (<code>product</code> applied to <code>[1,2,3]</code>) which <em>evaluate</em>s to a <em>value</em>.</p>
<p>Load up <code>ghci</code> and input <code>:type &lt;exp&gt;</code> to query the type of an expression.</p>
<h1 data-number="3" id="adts-construction-deconstruction"><span class="header-section-number">3</span> ADTs, Construction, Deconstruction</h1>
<p>Algebraic data types (ADTs) allow us to define our own <em>types</em> and <em>values</em>.</p>
<p>To create a new <em>type</em> called <code>Point</code>, we define a new value <code>MkPoint</code> that has
type <code>Int -&gt; Int -&gt; Point</code>. This function can be used to create
values of type <code>Point</code>. It takes two arguments of type <code>Int</code>, which means
<code>MkPoint 1 2</code> (<code>MkPoint</code> applied to <code>1</code> and <code>2</code>) has type <code>Point</code>.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>      <span class="op">+---</span> <span class="kw">type</span> constructor</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>      <span class="op">|</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>      v</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Point</span> <span class="ot">=</span> <span class="dt">MkPoint</span> <span class="dt">Int</span> <span class="dt">Int</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>                <span class="op">^</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>                <span class="op">|</span></span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>                <span class="op">+---</span> <span class="kw">data</span> constructor</span></code></pre></div>
<p>N.B. A <em>type constructor</em> with 0 arguments is also called simply <em>type</em></p>
<p>We can define types with more data constructors, which might take 0 to N
arguments.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Shape</span> <span class="ot">=</span> <span class="dt">Square</span> <span class="dt">Int</span> <span class="dt">Int</span> <span class="dt">Int</span> <span class="dt">Int</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>           <span class="op">|</span> <span class="dt">Triangle</span> <span class="dt">Int</span> <span class="dt">Int</span> <span class="dt">Int</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>           <span class="op">|</span> <span class="dt">Line</span> <span class="dt">Int</span> <span class="dt">Int</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>           <span class="op">|</span> <span class="dt">Point</span></span></code></pre></div>
<p>Which are the type constructors? What are the data constructors? Write 2
different expressions with type <code>Shape</code>.</p>
<p>There are two dual concepts related to ADTs: <em>construction</em> and <em>deconstruction</em></p>
<p>We’ve already seen that we can <em>construct</em> values of our defined type with the
<em>data constructor</em>.
The deconstruction of an <em>ADT</em> is done through <em>pattern matching</em>.</p>
<p>Pattern matching is done by specifying the expression to deconstruct together
with the patterns that might match the ADT “form”.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">shape1 ::</span> <span class="dt">Shape</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>shape1 <span class="ot">=</span> <span class="fu">undefined</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>            <span class="op">+------</span> expression to deconstruct</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>            <span class="op">|</span></span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>aNumber <span class="ot">=</span>   v</span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">case</span> shape1 <span class="kw">of</span></span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Square</span> a b c d <span class="ot">-&gt;</span> a <span class="op">+</span> b <span class="op">+</span> c <span class="op">+</span> d</span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Triangle</span> a <span class="dv">0</span> c <span class="ot">-&gt;</span> a <span class="op">+</span> c</span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a>                <span class="op">^</span></span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a>                <span class="op">|</span></span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a>                <span class="op">+----------------</span> <span class="kw">pattern</span></span>
<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Line</span> <span class="dv">5</span> <span class="dv">5</span> <span class="ot">-&gt;</span> <span class="dv">5</span> <span class="op">^</span> <span class="dv">5</span></span>
<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a>        a <span class="ot">-&gt;</span> <span class="dv">0</span></span></code></pre></div>
<p>What would be the value of <code>aNumber</code> if <code>shape1 = Triangle 22 0 1</code> ? And <code>shape1 = Point</code>? And <code>shape1 = Triangle 1 1 1</code>? And <code>shape1 = Line 5 5</code>? And <code>shape1 = Line 1 2</code>?</p>
<p>What is the type of aNumber?</p>
<p>N.B. Constructors are really just a special kind of function (the distinguishing feature being that they can be used in pattern matching, and that when data constructors are given arguments they construct <em>values</em>)</p>
<h1 data-number="4" id="polymorphism"><span class="header-section-number">4</span> Polymorphism</h1>
<p>Polymorphic types are universally quantified in some way over <em>all</em> types.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span><span class="ot">         ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Integer</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> []      <span class="ot">=</span>  <span class="dv">0</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span> (x<span class="op">:</span>xs)  <span class="ot">=</span>  <span class="dv">1</span> <span class="op">+</span> <span class="fu">length</span> xs</span></code></pre></div>
<p>This function works for lists of <em>any</em> type, be it lists of <code>Int</code>, <code>Char</code>,
<code>Shape</code>, etc.</p>
<p>This example wouldn’t work: e.g. if <code>a</code> was <code>Char</code>, it would mean <code>x</code> had type
<code>Char</code>, which could not be added to the result of applying <code>sum</code> to <code>xs</code> (<code>sum xs :: Integer</code>)</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="fu">sum</span><span class="ot">            ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Integer</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="fu">sum</span> []         <span class="ot">=</span>  <span class="dv">0</span></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="fu">sum</span> (x<span class="op">:</span>xs)     <span class="ot">=</span>  x <span class="op">+</span> <span class="fu">sum</span> xs</span></code></pre></div>
<p>This kind of completely generic polymorphism is called <em>parametric
polymorphism</em>.</p>
<!-- We said previously types could be seen as sets of values. -->
<!-- The `Integer` type corresponds to the set of all integer numbers -->
<!-- The `Natural` type correspondsd to the set of all natural numbers -->
<!-- The `Char` type corresponds to the set of all characters -->
<!-- Our `Shape` type corresponds to the set containing all possible combinations of -->
<!--     applying `Square` or `Triangle` or `Line` to integer numbers, plus `Point`. -->
<h1 data-number="5" id="non-nullary-type-constructors-kinds"><span class="header-section-number">5</span> Non-nullary type constructors, Kinds</h1>
<p>When defining new types, I mentioned the name right next to the <code>data</code> keyword
was called a <em>type constructor</em>, also called just <em>type</em> when the amount of
arguments was null.</p>
<p>If the amount of arguments is &gt; 0, the definition looks like this</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Box</span> a <span class="ot">=</span> <span class="dt">MkBox</span> a</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">DoubleBox</span> a b <span class="ot">=</span> <span class="dt">MkDoubleBox</span> a b</span></code></pre></div>
<p>Where <code>a</code> and <code>b</code> are type variables.
Expressions can never have a <em>type</em> <code>Box</code>, they instead can have type <code>Box Int</code>,
<code>Box Char</code>, or even be polymorphic as in <code>Box a</code> for all <code>a</code>s.</p>
<blockquote>
<p>As we know, the type system detects typing errors in expressions. But what about
errors due to malformed type expressions? The expression <code>(+) 1 2 3</code> results in a
type error since <code>(+)</code> takes only two arguments. Similarly, the type <code>Tree Int Int</code>
should produce some sort of an error since the <code>Tree</code> type takes only a single
argument. So, how does Haskell detect malformed type expressions? The answer is
a second type system which ensures the correctness of types! Each type has an
associated <em>kind</em> which ensures that the type is used correctly.</p>
</blockquote>
<p>The same way all <em>expressions</em> have <em>types</em>, all <em>types</em>, <em>type constructors</em>,
and in general <em>type expressions</em> have <em>kinds</em> (<em>kinds</em> are the <em>types</em> of
<em>types</em>).</p>
<p>All simple types have the kind <code>Type</code>, for example</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Int</span><span class="ot"> ::</span> <span class="dt">Type</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Char</span><span class="ot"> ::</span> <span class="dt">Type</span></span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Float</span><span class="ot"> ::</span> <span class="dt">Type</span></span></code></pre></div>
<p>Where <code>type Int :: Type</code> means type <code>Int</code> has kind <em>Type</em></p>
<p><em>Type constructors</em>, however, take types as arguments and only then are considered
types themselves. In our example, <code>Box</code> isn’t a valid type, while <code>Box Int</code> is.
With <em>kinds</em>, this is easily explained. The type constructor <code>Box</code> actually has
kind <code>Type -&gt; Type</code>, meaning it takes a type (<code>Type</code>) as an argument to become a type as
well (<code>Type</code>).</p>
<p>What’s the kind of <code>DoubleBox</code>?</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Box</span><span class="ot"> ::</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">DoubleBox</span><span class="ot"> ::</span> <span class="op">?</span></span></code></pre></div>
<p>Try this out in <code>ghci</code> by inputting <code>:kind &lt;type&gt;</code> to query the type of a type.</p>
<p>To watch on kinds: <a href="https://youtu.be/JleVecHAad4">An introduction to Haskell’s kinds</a></p>
]]></summary>
</entry>

</feed>
