<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Functional[Justin]</title>
    <description>Principal Software Engineer. Streaming data at scale. Generative AI. Functional Programming. Neovim. Emacs.</description>
    <link>http://justinhj.github.io/</link>
    <atom:link href="http://justinhj.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Sat, 18 Apr 2026 20:32:48 +0000</pubDate>
    <lastBuildDate>Sat, 18 Apr 2026 20:32:48 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>Refreshing your Neovim config for 0.12.0</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;

&lt;div id=&quot;outline-container-org12a1d94&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org12a1d94&quot;&gt;Introduction&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org12a1d94&quot;&gt;
&lt;p&gt;
Neovim version 0.12.1 was just released and you can check the release news here:
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/neovim/neovim/blob/v0.12.1/runtime/doc/news.txt&quot;&gt;Neovim v0.12.1 release news&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
This is a massive release bringing a number of core capabilities that used to require external plugins into Neovim as built-in features. I took this opportunity to do a full refresh of my config. This was required as over the last few years I have pulled in many plugins only to forget what they are for. My config had too many files, too much surface area when trying to make changes or fix annoyances.
&lt;/p&gt;

&lt;p&gt;
Rather than use an off the shelf config I had built it all by hand to meet my needs perfectly, but without careful maintenance it becomes an overgrown mess. In particular my lsp configurations and key maps were spread all over different places, and there was cruft I wasn&apos;t even using such as luasnip (hrsh7th/nvim-cmp won&apos;t work without a snippets plugin whether you want one or not).
&lt;/p&gt;

&lt;p&gt;
I considered two options for the refresh:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Gradually fix it a bit at a time.&lt;/li&gt;
&lt;li&gt;Kill it with fire and start again.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Given the mess my old config had gotten to I decided the latter would be much more manageable.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orge55627f&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orge55627f&quot;&gt;Running two configs on the same machine&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orge55627f&quot;&gt;
&lt;p&gt;
It&apos;s a lot easier to work on a new config if you still have the old one around for reference, and can easily run the new and the old together. One way to make this work is the &lt;code&gt;NVIM_APPNAME&lt;/code&gt; environment variable. Normally Neovim expects the various working folders, including the configuration, to be in the nvim folder.
&lt;/p&gt;

&lt;p&gt;
By using the &lt;code&gt;NVIM_APPNAME&lt;/code&gt; environment variable you can set it to something different, I chose nvim-next. This let&apos;s you build an entirely new config and leave your old one intact.
&lt;/p&gt;

&lt;p&gt;
I started by manually creating the new folders (MacOS example).
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-bash&quot;&gt;mkdir -p ~/.config/nvim-next
mkdir -p ~/.local/share/nvim-next
mkdir -p ~/.local/state/nvim-next
mkdir -p ~/.cache/nvim-next
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now it&apos;s possible to run with a fresh config without worrying about messing up the old one.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-bash&quot;&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;NVIM_APPNAME&lt;/span&gt;=nvim-next nvim
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
During development of the new config I used this command to open them both up together.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-bash&quot;&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;NVIM_APPNAME&lt;/span&gt;=nvim-next nvim -O ~/.config/nvim-next/init.lua ~/.config/nvim/init.lua
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Finally, you may want to include the environment variable in your shell config to use it as your &quot;real&quot; config more easily.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-bash&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;export&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;NVIM_APPNAME&lt;/span&gt;=nvim-next
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;


&lt;div id=&quot;outline-container-org0367c42&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org0367c42&quot;&gt;Replicating the config&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org0367c42&quot;&gt;
&lt;p&gt;
I needed some method to migrate this without missing anything so I went through the init.lua file and copied over anything that was obviously needed and unchanged. In particular, the vim options have not changed.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;vim.g.mapleader = &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;,&quot;&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Prevents showing extra messages when using completion&lt;/span&gt;
vim.opt.shortmess:append(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;c&quot;&lt;/span&gt;)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Sets the height of the command line area at the bottom&lt;/span&gt;
vim.opt.cmdheight = 2
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Displays the line number for the current line&lt;/span&gt;
vim.opt.number = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Displays line numbers relative to the current cursor position&lt;/span&gt;
vim.opt.relativenumber = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Time in milliseconds to wait for a mapped sequence to complete&lt;/span&gt;
vim.opt.timeoutlen = 500
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Time in milliseconds of inactivity before calling CursorHold or writing to swap&lt;/span&gt;
vim.opt.updatetime = 4000
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Ignores case when searching patterns&lt;/span&gt;
vim.opt.ignorecase = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Automatically switches to case-sensitive search if a capital letter is used&lt;/span&gt;
vim.opt.smartcase = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Enables 24-bit RGB colors in the terminal&lt;/span&gt;
vim.opt.termguicolors = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Configures the behavior of the insert mode completion menu&lt;/span&gt;
vim.opt.completeopt = &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;menu,menuone,noselect,popup&quot;&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Number of spaces that a &amp;lt;Tab&amp;gt; character represents&lt;/span&gt;
vim.opt.tabstop = 2
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Number of spaces to use for each step of automatic indentation&lt;/span&gt;
vim.opt.shiftwidth = 2
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Number of spaces that a &amp;lt;Tab&amp;gt; counts for during editing operations&lt;/span&gt;
vim.opt.softtabstop = 2
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Converts tabs into spaces when typing&lt;/span&gt;
vim.opt.expandtab = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Automatically inserts an extra level of indentation in some cases&lt;/span&gt;
vim.opt.smartindent = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Makes &amp;lt;Tab&amp;gt; insert &apos;shiftwidth&apos; number of spaces at the start of a line&lt;/span&gt;
vim.opt.smarttab = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
After that I stepped through the init.lua entirely and made a list of things to keep and things to lose. Let&apos;s cover them by category.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgd0cd587&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgd0cd587&quot;&gt;vim.pack, Neovim&apos;s new built-in plugin manager&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgd0cd587&quot;&gt;
&lt;p&gt;
Previously I used &lt;a href=&quot;https://github.com/folke/lazy.nvim&quot;&gt;folke/lazy.nvim&lt;/a&gt; for plugin management. This worked well and was fairly easy to configure, however there was complexity in the form of having to think about and configure lazy loading. For example, in loading this colour theme I need to think about whether to load it lazy or not, the priority with respect to other plugins and what to do to configure it.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;{
  &lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;shaunsingh/nord.nvim&apos;&lt;/span&gt;,
  lazy = &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;,
  priority = 1000,
  &lt;span style=&quot;color: #feacd0;&quot;&gt;config&lt;/span&gt; = &lt;span style=&quot;color: #b6a0ff;&quot;&gt;function&lt;/span&gt;()
    vim.cmd &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;colorscheme nord&quot;&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;end&lt;/span&gt;
},
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
vim.pack&apos;s approach is a lot more vanilla. It has no lazy loading, no priority system and all plugins have to be on a remote git repo. I think you cannot use local folders or local git repos. This may make plugin development a bit tricky.
&lt;/p&gt;

&lt;p&gt;
If you load a lot of plugins and some of them are slow, the optimization of lazy loading is probably worth it. With vim.pack you can still do the setup functions conditionally based on autocommands if you need to. 
&lt;/p&gt;

&lt;p&gt;
In my use case I found the start up time is 80ms and plenty fast enough for me, so I don&apos;t miss the lazy loading.
&lt;/p&gt;

&lt;p&gt;
To actually do the conversion you simply call vim.pack.add when you want to add a plugin, and once it is installed every command after that can use it.
&lt;/p&gt;

&lt;p&gt;
For example the configuration above becomes:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;vim.pack.add({
  { src = &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;https://github.com/shaunsingh/nord.nvim&quot;&lt;/span&gt; },
})

vim.cmd(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;colorscheme nord&apos;&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that assumed Github paths are not filled out like in Lazy.nvim, you must fill them yourself, or as the documentation suggests use a helper function to generate the names.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;local&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;gh&lt;/span&gt; = &lt;span style=&quot;color: #b6a0ff;&quot;&gt;function&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;x&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;https://github.com/&apos;&lt;/span&gt; .. x &lt;span style=&quot;color: #b6a0ff;&quot;&gt;end&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;local&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;cb&lt;/span&gt; = &lt;span style=&quot;color: #b6a0ff;&quot;&gt;function&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;x&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;https://codeberg.org/&apos;&lt;/span&gt; .. x &lt;span style=&quot;color: #b6a0ff;&quot;&gt;end&lt;/span&gt;

vim.pack.add({ gh(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;user/plugin1&apos;&lt;/span&gt;), cb(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;user/plugin2&apos;&lt;/span&gt;) })
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
vim.pack keeps track of the versions you are using and saves to a lock file. This is supposed to be committed to source control and it means you can move to another machine and get the exact same plugin versions. It also means you may have merge issues if you edit the configs on different machines.
&lt;/p&gt;

&lt;p&gt;
Also of note is the new :restart command, which lets you iterate on changes to plugins and configuration more easily. The Neovim core restarts. With mksession you can save the current session then resume it after a restart. 
&lt;/p&gt;

&lt;p&gt;
One more thing I like about vim.pack is it uses simple buffers as its user interface. vim.pack.update({}) shows a buffer with the packages and any updates that need doing. Simply writing the file acts as confirmation you want to go ahead. Nice.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org4665a53&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org4665a53&quot;&gt;Treesitter&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org4665a53&quot;&gt;
&lt;p&gt;
I ran into some issues with Treesitter as I ended up with a mix of different tree-sitter compiled grammars and different versions of Treesitter. It all worked after doing the following:
&lt;/p&gt;

&lt;p&gt;
Install the tree-sitter-cli, which is required by newer versions of treesitter-nvim.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-bash&quot;&gt;brew install tree-sitter-cli
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Ensure to switch to the main branch of treesitter-nvim (main is more up to date than master).
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;vim.pack.add({
  { src = &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;https://github.com/nvim-treesitter/nvim-treesitter&quot;&lt;/span&gt;, 
    version = &lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;main&apos;&lt;/span&gt; },
})
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
After that I was able to TSUpdate and TSInstall whatever I needed without any issues providing perfect syntax highlighting.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgb35f839&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb35f839&quot;&gt;LSP and completion&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb35f839&quot;&gt;
&lt;p&gt;
As mentioned, the bulk of my config complexity was coming from completion and LSP configuration. This complexity is greatly reduced by the following changes:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Remove nvim-cmp and LuaSnip&lt;/li&gt;
&lt;li&gt;Use native completion&lt;/li&gt;
&lt;li&gt;Modular lsp configuration&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Since completion is now built-in I can turn it on with the following global settings and an LspAttach autocmd to enable it for each lsp server after checking if it is supported.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;vim.opt.completeopt = &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;menu,menuone,noselect,popup&quot;&lt;/span&gt; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Ensures the menu appears even for a single match and uses the native popup window.&lt;/span&gt;
vim.o.autocomplete = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Enables the overall completion feature.&lt;/span&gt;

vim.api.nvim_create_autocmd(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;LspAttach&quot;&lt;/span&gt;, {
  group = vim.api.nvim_create_augroup(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;lsp_completion&quot;&lt;/span&gt;, { clear = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt; }),
  &lt;span style=&quot;color: #feacd0;&quot;&gt;callback&lt;/span&gt; = &lt;span style=&quot;color: #b6a0ff;&quot;&gt;function&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;args&lt;/span&gt;)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;local&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;client_id&lt;/span&gt; = args.data.client_id
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;not&lt;/span&gt; client_id &lt;span style=&quot;color: #b6a0ff;&quot;&gt;then&lt;/span&gt;
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt;
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;end&lt;/span&gt;

    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;local&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;client&lt;/span&gt; = vim.lsp.get_client_by_id(client_id)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; client &lt;span style=&quot;color: #b6a0ff;&quot;&gt;and&lt;/span&gt; client:supports_method(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;textDocument/completion&quot;&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;then&lt;/span&gt;
      &lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Enable native LSP completion for this client + buffer&lt;/span&gt;
      vim.lsp.completion.enable(&lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;, client_id, args.buf, {
        autotrigger = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;,   &lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;auto-show menu as you type (recommended)&lt;/span&gt;
        &lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;You can also set { autotrigger = false } and trigger manually with &amp;lt;C-x&amp;gt;&amp;lt;C-o&amp;gt;&lt;/span&gt;
      })
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;end&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;end&lt;/span&gt;,
})
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Finally, I still use Mason for easy management of LSP servers. What remains is to enable the servers which must be done by calling the enable method, and to configure it. For example for Python I added the following in my init.lua to enable the server.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;vim.lsp.enable(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;pylsp&apos;&lt;/span&gt;) &lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Python&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
LSP configuration can now be done using an lsp folder in your config. Each config file should be named after the LSP server. In this case I made lsp/pylsp.lua. It should simply return the configuration structure.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; {
  cmd = { &lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;pylsp&apos;&lt;/span&gt; },
  filetypes = { &lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;python&apos;&lt;/span&gt; },
  settings = {
    pylsp = {
      plugins = {
        mccabe = { enabled = &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt; },
        pycodestyle = { enabled = &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt; },
        flake8 = {
          enabled = &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;,
          ignore = { &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;E501&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;E302&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;W&quot;&lt;/span&gt; },
          maxLineLength = 120,
        },
      },
    },
  },
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This kind of convention over configuration appeals to me and helps keeps things organized.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orga3c3afd&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga3c3afd&quot;&gt;New User interface (ui2) and the status line&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga3c3afd&quot;&gt;
&lt;p&gt;
ui2 is a &quot;is a redesign of the core messages and commandline UI, which will replace the legacy message grid in the TUI.&quot;. In particular it removes &quot;Press Enter&quot; interruptions, and it highlights the command line as you type. Nice.
&lt;/p&gt;

&lt;p&gt;
As a maintainer of a status line plugin, &lt;a href=&quot;https://github.com/justinhj/battery.nvim&quot;&gt;battery.nvim&lt;/a&gt; I was curious if anything had broken the statusline. Everything seemed to work without any changes. 
&lt;/p&gt;

&lt;p&gt;
ui2 is opt-in and you can do so as follows:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-lua&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;-- &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;New UI opt-in&lt;/span&gt;
&lt;span style=&quot;color: #f78fe7;&quot;&gt;require&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&apos;vim._core.ui2&apos;&lt;/span&gt;).enable({})
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org28e3aee&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org28e3aee&quot;&gt;The best of the rest&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org28e3aee&quot;&gt;
&lt;p&gt;
I&apos;ve kept the most minimal set of plugins for my config. In particular I still have:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;mason, mason-lspconfig &amp;#x2013; lsp server managment&lt;/li&gt;
&lt;li&gt;nvim-treesitter &amp;#x2013; tools for treesitter&lt;/li&gt;
&lt;li&gt;shaunsingh/nord.nvim &amp;#x2013; my favourite colourscheme&lt;/li&gt;
&lt;li&gt;mrjones2014/legendary.nvim &amp;#x2013; archived but still great key map manager&lt;/li&gt;
&lt;li&gt;ibhagwan/fzf-lua &amp;#x2013; fast finder for files and text within files&lt;/li&gt;
&lt;li&gt;nvim-lualine/lualine.nvim &amp;#x2013; best statusline&lt;/li&gt;
&lt;li&gt;justinhj/battery.nvim &amp;#x2013; Let me plug my own plugin&lt;/li&gt;
&lt;li&gt;nvim-lua/plenary.nvim &amp;#x2013; Useful libraries&lt;/li&gt;
&lt;li&gt;folke/which-key.nvim &amp;#x2013; Keymap display&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Some I may miss
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;tpope/vim-fugitive &amp;#x2013; Nice Git commands, but I mostly use Git at the command line&lt;/li&gt;
&lt;li&gt;karb94/neoscroll.nvim &amp;#x2013; smooth scrolling&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org23ff122&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org23ff122&quot;&gt;vim.net.request&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org23ff122&quot;&gt;
&lt;p&gt;
I have done some http programming in lua, mostly with the help of plenary and libuv. Adding GET requests to the built-in lua is a nice step. I would hope it gets POST and other methods to expand its utility over time.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org4f02f78&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org4f02f78&quot;&gt;Wrapping up&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org4f02f78&quot;&gt;
&lt;p&gt;
There are a couple of options once you&apos;re happy with the new config. One option is to keep the old config around forever. Another would be to delete it completely.
&lt;/p&gt;

&lt;p&gt;
For science, on my Windows machine which I mostly use for Gaming and a bit of ML and AI, I completely deleted the old config and replaced it. On my Macbook I keep both for now. 
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org6a4f83d&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org6a4f83d&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org6a4f83d&quot;&gt;
&lt;p&gt;
0.12.x is one of the biggest updates for a while in Neovim and it&apos;s great to see the out-of-the-box experience expanding. I found clearing out my configuration and refreshing it for 2026 was a good excuse to explore these new features.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org00f72ee&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org00f72ee&quot;&gt;Thanks&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org00f72ee&quot;&gt;
&lt;p&gt;
Thank you to &lt;code&gt;GrandLate7367&lt;/code&gt;, &lt;code&gt;TheLeoP_&lt;/code&gt; and  &lt;code&gt;mushfiq_814&lt;/code&gt; on Reddit&apos;s &lt;code&gt;r/neovim&lt;/code&gt; for pointing out some issues with the original post.
&lt;/p&gt;

&lt;p&gt;
&amp;copy;2026 Justin Heyes-Jones. All Rights Reserved
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Mon, 06 Apr 2026 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2026/04/06/refreshing-your-neovim-config-for-0-12-0.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2026/04/06/refreshing-your-neovim-config-for-0-12-0.html</guid>
        
        <category>neovim</category>
        
        <category>vim</category>
        
        <category>command-line</category>
        
        
      </item>
    
      <item>
        <title>Visualizing K-Way Merge&amp;#58 An Interactive Guide to Database Sorting</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML&quot;&gt;&lt;/script&gt;
&lt;p&gt;
&lt;img src=&quot;/../images/aleksandr-galichkin-AUae3_x_lDU-unsplash.jpg&quot; alt=&quot;aerial view of three empty tennis courts&quot; title=&quot;&quot; /&gt;
&lt;/p&gt;
&lt;span&gt;
Photo by &lt;a href=&quot;https://unsplash.com/@axga?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;Aleksandr Galichkin&lt;/a&gt; on &lt;a href=&quot;https://unsplash.com/photos/aerial-view-of-three-empty-tennis-courts-AUae3_x_lDU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;Unsplash&lt;/a&gt;
&lt;/span&gt;

&lt;p&gt;
In this post, inspired by a &lt;a href=&quot;https://www.youtube.com/embed/agjVihO6IPM?si=gBBtRn744A5A2Wqr&quot;&gt;video&lt;/a&gt; by Tigerbeetle engineers Tobias Ziegler (@toziegler) and Alex Kladov (@matklad), I&apos;ll walk through four algorithms for merging multiple sorted runs of data; a problem that shows up in modern database internals. You will be able to use an interactive web application to explore and understand each one. 
&lt;/p&gt;

&lt;p&gt;
The title image isn&apos;t just a pretty picture of tennis courts; it&apos;s the inspiration for the most efficient external sorting algorithm: The Tournament Tree.
&lt;/p&gt;

&lt;div id=&quot;outline-container-orga70713b&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga70713b&quot;&gt;External sort and k-way merge&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga70713b&quot;&gt;
&lt;p&gt;
Whilst most engineers are familiar with a number of sorting algorithms that work with data sets that fit entirely in memory, there are use cases, both historical and current, that do not. In these cases you must pull in small chunks of memory and sort them before outputting to a larger sorted output. 
&lt;/p&gt;

&lt;p&gt;
As an extreme example take the 1960 USA Census for example. The Census Bureau&apos;s UNIVAC 1105 was a supercomputer of the day, with up to 18 attached tape drives. Even so, it had a limited memory (less than 300kb) and so there is no way to sort the data in memory.
&lt;/p&gt;

&lt;p&gt;
Instead the process used was called Balanced k-way merge. Input data was put onto one set of tapes, and another set of tapes are used as output. The computer read as many records as it could fit in memory, sorted them and wrote them to tape. The tape was then filled with these sorted runs. 
&lt;/p&gt;

&lt;p&gt;
The k-way merge part comes from k (the number of runs being handled at once, in this case the number of tapes, let&apos;s assume 4). At the first step the computer reads the first records from each tape and outputs the smallest one to the output tape. Next, it gets the next record from the tape where the smallest record came from. This process continues until the records on all 4 tapes have been exported to a single sorted run on the output tape.
&lt;/p&gt;

&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/2YnydcjlLPg?si=IKNFMKHE5TMEels4&quot; title=&quot;YouTube video player&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share&quot; referrerpolicy=&quot;strict-origin-when-cross-origin&quot; allowfullscreen&gt;&lt;/iframe&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org7b156e7&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org7b156e7&quot;&gt;External sort in modern databases&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org7b156e7&quot;&gt;
&lt;p&gt;
Modern databases use essentially the same logic. An LSM tree (see next section) flushes &quot;SSTables&quot; (sorted runs) to disk (which are modern &quot;tapes&quot;) and then performs a background k-way merge (compaction) to combine them. The physics changed (seek times vs. linear scan), but the math of the k-way merge remains exactly the same.
&lt;/p&gt;

&lt;p&gt;
External sort is used for various purposes:
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Databases&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Purpose&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Algorithm&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;LSM-Tree Databases (RocksDB, Cassandra, ScyllaDB, LevelDB)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Compaction&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;min-heap&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Search Engines (Apache Lucene / Elasticsearch / Solr)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Segment merging&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;min-heap&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Analytical &amp;amp; Columnar Databases (ClickHouse, DuckDB)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Part Merging: Maintaining column blocks sort order&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Linear scan/Vectorized merge&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Relational Databases (PostgreSQL)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Queries that exceed work&lt;sub&gt;mem&lt;/sub&gt;/Merging joins&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Tree of Losers/Polyphase&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org712f4b8&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org712f4b8&quot;&gt;LSM trees&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org712f4b8&quot;&gt;
&lt;p&gt;
LSM-Trees (Log-Structured Merge-Trees) are a data structure that achieves fast writes by buffering changes in memory and periodically merging them with sorted on-disk tables. I won&apos;t go into much detail on them in this post, it&apos;s only important to know that the typical implementation requires taking multiple sorted runs of records and merge sorting them into a single sorted run.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgbeb8019&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgbeb8019&quot;&gt;Tigerbeetle&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgbeb8019&quot;&gt;
&lt;p&gt;
Like DuckDB and others, Tigerbeetle&apos;s storage engine is also using LSM-Trees. Let&apos;s dig into that a little:
&lt;/p&gt;

&lt;img src=&quot;../../../images/tbwriting.png&quot; 
     alt=&quot;Tigerbeetle&apos;s write path&quot; 
     style=&quot;width: 100%; max-width: 800px; height: auto; border: 1px solid #444; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);&quot;&gt;

&lt;p&gt;
In order to accept new transactions very quickly, Tigerbeetle writes new transactions into an unsorted mutable memory buffer (each transaction was safely written into a write ahead log on a quorum of nodes before this step, so it cannot be lost at this point). 
&lt;/p&gt;

&lt;p&gt;
The memory buffer has a fixed size and once it is full it becomes an immutable buffer and is flushed to disk. As noted above, LSM trees store data into internally sorted tables, and these tables are merged into larger ones as you get further down the tree. 
&lt;/p&gt;

&lt;p&gt;
To better explain the mechanism play with the following toy Tigerbeetle database: 
&lt;/p&gt;

&lt;div style=&quot;text-align: center; margin: 20px 0;&quot;&gt;
    &lt;a href=&quot;https://heyes-jones.com/tigerbeetlelsm.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot; style=&quot;text-decoration: none;&quot;&gt;
        &lt;img src=&quot;../../../images/tb1.png&quot; 
             alt=&quot;Tigerbeetle LSM Visualization&quot; 
             title=&quot;Click to launch interactive simulation&quot;
             style=&quot;width: 100%; max-width: 800px; height: auto; border: 1px solid #444; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);&quot;&gt;
        &lt;p style=&quot;margin-top: 8px; color: #666; font-size: 0.9em;&quot;&gt;
            👆 &lt;em&gt;Click to try the interactive simulation&lt;/em&gt;
        &lt;/p&gt;
    &lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;
Apart from this compaction step, Tigerbeetle also has the same problem when doing range based query scans; it will scan the tables in the various levels of the LSM tree and will need to combine each one into a single sorted result.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org063d6f2&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org063d6f2&quot;&gt;K-Way merges&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org063d6f2&quot;&gt;
&lt;p&gt;
The process of taking multiple sorted runs and outputting a new single sorted run of data is called k-way merging. k is the number of runs we are merging, so we are merging it in k-ways.
&lt;/p&gt;

&lt;p&gt;
Implementing k-way merging is not super complicated, but as we will see there are some different options depending on your use case, with the usual engineering trade offs.
&lt;/p&gt;

&lt;p&gt;
Contrary to some LSM implementations that might use k-way merge for all compactions, TigerBeetle uses it selectively. For example the mutable table actually consists of 32 sorted runs and when they are flushed to the immutable table they are all merged to a single sorted run before being flushed to the first disk level.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org3e83ba1&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org3e83ba1&quot;&gt;Linear scan&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org3e83ba1&quot;&gt;
&lt;p&gt;
As always, let&apos;s start with the simplest solution possible. In linear scan you take the smallest elements from each of the k runs, and that is your starting set. Each iteration we do the following:
&lt;/p&gt;

&lt;p&gt;
Algorithm.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Run through all k current candidates tracking the smallest one found.&lt;/li&gt;
&lt;li&gt;Output the smallest element.&lt;/li&gt;
&lt;li&gt;Replace the smallest element with the next element &lt;code&gt;from the run it came from&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
That last point is crucial. Why take the next element from that particular run? It&apos;s because after step 1 we have by definition the smallest elements from each of the runs. The next smallest element can only be one of the other k elements we are still considering, or the new element we didn&apos;t see yet from the &quot;winner&apos;s&quot; run. 
&lt;/p&gt;

&lt;p&gt;
Make sure to understand that point as all the algorithms below will do the same.
&lt;/p&gt;

&lt;p&gt;
As mentioned above, you can explore each algorithm interactively, just click on the image below. Each one has the same controls:
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;&lt;b&gt;Step&lt;/b&gt;. Go to the next step of the algorithm, updating the step description and animation.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Play&lt;/b&gt;. To unleash the animation and run through the algorithm until you stop it or the runs are all empty.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Seed&lt;/b&gt;. Change the seed to try different data sets.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Speed&lt;/b&gt; slider. Change the speed of the animation.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Reset&lt;/b&gt;. Restart the simulation.&lt;/li&gt;
&lt;/ul&gt;

&lt;div style=&quot;text-align: center; margin: 20px 0;&quot;&gt;
    &lt;a href=&quot;https://heyes-jones.com/externalsort/linearscan.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot; style=&quot;text-decoration: none;&quot;&gt;
        &lt;img src=&quot;../../../images/linear-scan-thumbnail.png&quot; 
             alt=&quot;K-Way Merge Tree of Winners Visualization&quot; 
             title=&quot;Click to launch interactive simulation&quot;
             style=&quot;width: 100%; max-width: 800px; height: auto; border: 1px solid #444; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);&quot;&gt;
        &lt;p style=&quot;margin-top: 8px; color: #666; font-size: 0.9em;&quot;&gt;
            👆 &lt;em&gt;Click to try the interactive simulation&lt;/em&gt;
        &lt;/p&gt;
    &lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;
Analysis.
&lt;/p&gt;

&lt;p&gt;
Since we must do k comparisons per output, with n total data items in all the runs the complexity is: \(O(kn)\)
&lt;/p&gt;

&lt;p&gt;
Whilst not bad, we can do better. However, for small values of k it may well be good enough, or even faster than the other solutions below, despite the asymptotic complexity saying otherwise. 
&lt;/p&gt;

&lt;p&gt;
In addition, on modern CPUs you can use SIMD instructions (AVX2 or AVX-512) to handle up to k=16 assuming 32 bit integers. However, since Tigerbeetle can have up to 32 runs and uses 128 bit identifiers, this is not a useful option.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org3c1a975&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org3c1a975&quot;&gt;Going faster with Tree Selection&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org3c1a975&quot;&gt;
&lt;p&gt;
As mentioned above we do \(O(k)\) comparisons per output, can we do better? Well, to be more precise for the first output we need do k-1 comparisons, since we start with the first element and that iterate them all, swapping out the first element with the first smaller one and so on. In order to speed things up we need to think about doing less comparisons.
&lt;/p&gt;

&lt;p&gt;
Although we need to do k-1 comparisons to get the 1st item, with some thought we can do far fewer to find the 2nd item, 3rd item and so on. 
&lt;/p&gt;

&lt;p&gt;
In Knuth (Art of Computer Programming vol3: Searching and Sorting) we find the discussion on selection sort which helps here&amp;#x2026;
&lt;/p&gt;

&lt;p&gt;
Quadratic selection (E H Friend, JACM 3, 1956) noted that we can do better by first grouping the sort items into groups based on the square root of n. For example, sorting 9 items we divide into groups of 3.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;Note: in selection sort you find the largest element at each step and move it to the end of the array. In k-way merge we output smallest first. Don&apos;t be confused by finding the largest element in this section.&lt;/code&gt;
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-right&quot;&gt;8&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;4&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;3&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;7&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;5&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;2&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;9&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;1&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;6&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-right&quot;&gt;8&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;4&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;3&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-right&quot;&gt;7&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;5&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;2&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-right&quot;&gt;9&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;1&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;6&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
Once you have the three groups find the largest in each.
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;code&gt;8&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;4&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;3&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;code&gt;7&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;5&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;2&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;code&gt;9&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;1&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;6&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
The largest element is now the largest of the three &quot;winners&quot;, 9.
&lt;/p&gt;

&lt;p&gt;
To find the second largest, it could be either of the two remaining winners or one of the others in 9&apos;s group. (Note that I replace removed elements with infinity so they can be ignored in subsequent steps.)
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;code&gt;8&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;4&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;3&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;code&gt;7&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;5&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;2&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;\(\infty\)&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;1&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;&lt;code&gt;6&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
We find it is 8. So the next winner is the larger of 7, 6 or the others in 8&apos;s group.
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;

&lt;col  class=&quot;org-right&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;\(\infty\)&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;&lt;code&gt;4&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;3&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;code&gt;7&lt;/code&gt;&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;5&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;2&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;\(\infty\)&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;1&lt;/td&gt;
&lt;td class=&quot;org-right&quot;&gt;&lt;code&gt;6&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
Proceeding this way the sort needs n sqrt n comparisons, much better than the original n&lt;sup&gt;2&lt;/sup&gt;.
&lt;/p&gt;

&lt;p&gt;
Friend noted that you can continue this process of dividing the search into smaller groups based on the cubic root, the quartic, and ultimately into groups of two. Friend called this nth degree selecting. Knuth calls it tree selection.
&lt;/p&gt;

&lt;p&gt;
This is what leads to the next three solutions to k-way merge, using tree structures essentially gives us a way to cache comparisons so we don&apos;t have to repeat them.
&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgc32f994&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;orgc32f994&quot;&gt;min heap&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-orgc32f994&quot;&gt;
&lt;p&gt;
As we saw above, modern databases make use of the min-heap for k-way merge. As a binary tree structure it&apos;s an obvious choice since elements are stored in partially sorted order and we can always remove the minimum element which is the one we want to emit next.
&lt;/p&gt;

&lt;p&gt;
In order to use the min-heap for k-way merge we do the following:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Populate a fixed size min-heap with the first (smallest) elements from the k runs.&lt;/li&gt;
&lt;li&gt;Pop the top item from the heap (the smallest) and replace it with the next from the same run.&lt;/li&gt;
&lt;li&gt;Sift the heap down to make the heap valid again.&lt;/li&gt;
&lt;li&gt;Repeat until the sort is complete.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Once again, you can step through the algorithm using the interactive visualization below.
&lt;/p&gt;

&lt;div style=&quot;text-align: center; margin: 20px 0;&quot;&gt;
    &lt;a href=&quot;https://heyes-jones.com/externalsort/minheapmerge.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot; style=&quot;text-decoration: none;&quot;&gt;
        &lt;img src=&quot;../../../images/min-heap-merge-thumbnail.png&quot; 
             alt=&quot;K-Way Merge Tree of Losers Visualization&quot; 
             title=&quot;Click to launch interactive simulation&quot;
             style=&quot;width: 100%; max-width: 800px; height: auto; border: 1px solid #444; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);&quot;&gt;
        &lt;p style=&quot;margin-top: 8px; color: #666; font-size: 0.9em;&quot;&gt;
            👆 &lt;em&gt;Click to try the interactive simulation&lt;/em&gt;
        &lt;/p&gt;
    &lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;
Analysis.
&lt;/p&gt;

&lt;p&gt;
With a min-heap the push and pop operations are both \(O(\log_2 k)\) giving a runtime complexity of \(O(n \log k)\).
&lt;/p&gt;

&lt;pre class=&quot;example&quot; id=&quot;orgdbf335b&quot;&gt;
                  a
                  |
      +-----------+-----------+
      |                       |
      b                       c
      |                       |
+-----+-----+           +-----+-----+
|           |           |           |
d           e           f           g
&lt;/pre&gt;

&lt;p&gt;
min-heaps are represented as a flat array. For example the tree above would be stored in memory like this:
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;
&lt;/colgroup&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;a&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;b&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;c&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;d&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;e&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;f&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;g&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
This is known as the Eytzinger Layout. A node at index \(i\) has children at \(2i+1\) and \(2i+2\). For a small tree size it is a cache friendly structure since it will fit in a few cache lines.
&lt;/p&gt;

&lt;p&gt;
In addition our use case allows us to do the push and pop in one move.
&lt;/p&gt;

&lt;p&gt;
During the sift down process after adding the new winner you need to:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Compare Left Child vs. Right Child (to find the smaller one).&lt;/li&gt;
&lt;li&gt;Compare the Smaller Child vs. The Current Node (to see if you swap).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
This costs \(2 \cdot \log_2 k\) comparisons per element.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s see how we can improve.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org222126e&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org222126e&quot;&gt;Tournament Trees&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org222126e&quot;&gt;
&lt;p&gt;
In Knuth we see the following diagram of a ping pong tournament. (section 5.2.3, Fig 22). Any sport works here really, the important thing is that when two people or teams compete the idea is that the best one will win. We will be dealing with sorting unchanging records so the analogy is not perfect. If Chris beats Pat on Sunday, he may still lose to Pat on Monday, but we can ignore that for the purposes of the algorithm.
&lt;/p&gt;

&lt;pre class=&quot;example&quot; id=&quot;org9d0cd52&quot;&gt;
                  Chris (Champion)
                      |
          +-----------+-----------+
          |                       |
        Chris                    Pat
          |                       |
    +-----+-----+           +-----+-----+
    |           |           |           |
   Kim        Chris        Pat        Robin
    |           |           |           |
 +--+--+     +--+--+     +--+--+     +--+--+
 |     |     |     |     |     |     |     |
Kim  Sandy Chris  Lou   Pat   Ray   Dale Robin
&lt;/pre&gt;

&lt;p&gt;
The result of a tournament can be thought of as a binary tree where the winner is at the root. The two children will be the two players that played the final, and so on. It is clear we can go down the tree starting at Chris and say that he was better than each of his opponents; Pat, Kim and Lou.
&lt;/p&gt;

&lt;p&gt;
The best player then, is Chris. But what if Chris had not shown up that day? Is Pat the best player? 
&lt;/p&gt;

&lt;p&gt;
Well all we know is that Pat beat all the opponents on her side of the tree, but we don&apos;t in fact know if she would have beaten the same opponents on Chris&apos;s side. So all we can say is that Chris was the best player overall, and Pat was the best player amongst the right subtree.
&lt;/p&gt;

&lt;p&gt;
&lt;img src=&quot;/../images/pure-julia-E4fNq7wYE2w-unsplash.jpg&quot; alt=&quot;book image of a page from alice in wonderland&quot; title=&quot;&quot; /&gt;
&lt;/p&gt;
&lt;span&gt;
Photo by &lt;a href=&quot;https://unsplash.com/@purejulia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;pure julia&lt;/a&gt; on &lt;a href=&quot;https://unsplash.com/photos/white-book-page-with-man-and-woman-print-E4fNq7wYE2w?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;Unsplash&lt;/a&gt;
&lt;/span&gt;

&lt;p&gt;
It is here that we take an interesting digression into Tennis Tournaments and whilst they are fair to the winner, they are not quite so fair when it comes to picking the runner up, third place and so on.
&lt;/p&gt;

&lt;p&gt;
Rev. Charles Lutwidge Dodgson, better known by his pen name, Lewis Carroll, author of Alice&apos;s Adventures in Wonderland was also a mathematician and logician at Christ Church, Oxford, with a deep obsession for fairness in rules and voting systems.
&lt;/p&gt;

&lt;p&gt;
“At a Lawn Tennis Tournament, where I chanced, some while ago, to be a spectator, the present method of assigning prizes was brought to my notice by the lamentations of one of the Players, who had been beaten (and had thus lost all chance of a prize) early in the contest, and who had had the mortification of seeing the 2nd prize carried off by a Player whom he knew to be quite inferior to himself.” - Charles Dodgson
&lt;/p&gt;

&lt;p&gt;
Dodgson came up with a scheme, not quite an algorithm as it was not precisely specified, to play the Tennis Tournament in a way that was more fair. His idea was that the losers could replay each other so that they get a second chance. In the tournament above, Lou lost to Chris, but he could get a chance to play Sandy, for example, and win a chance to play for second place. 
&lt;/p&gt;

&lt;p&gt;
If you want to read more about this I found an excellent blog post which includes an implementation of Dodgson&apos;s idea in the R language, with the missing specifications figured out.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://freerangestats.info/blog/2020/02/01/tennis-carroll&quot;&gt;Lewis Carroll&apos;s proposed rules for Tennis Tournaments&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Whilst the idea was good, it did not catch on because tournaments would take a variable amount of time depending on who won which games, and it&apos;s a bit more complex for the audience to follow. Besides, modern day tournaments use the seeding system which avoids top players playing each other in the early stages.
&lt;/p&gt;

&lt;p&gt;
For the tree of winners algorithm we will work slightly differently. Our job is to continuously replay the tournament by removing the winner and bringing in a new candidate from winners run.
&lt;/p&gt;

&lt;p&gt;
In the tournament above, Lou should play Kim and Pat should play the winner of that game. Notice that &quot;only two additional matches are required to find the second-best player, because of the structure we have remembered from the earlier games.&quot;
&lt;/p&gt;

&lt;p&gt;
Tree selection, then, proceeds by removing the winner of the tournament from our &quot;Tree of Winners&quot;, then replaying the tournament without that player, and each replay requires \(\log_2 k\) comparisons.
&lt;/p&gt;

&lt;p&gt;
To make this more concrete as a sort let&apos;s change the players to their numeric values that determine who will win. We want to sort in ascending order so the lowest values win, and are output first.
&lt;/p&gt;

&lt;p&gt;
Step 1 we remove 1 and output it as the first element.
&lt;/p&gt;

&lt;pre class=&quot;example&quot; id=&quot;org8555b4b&quot;&gt;
Sort output: 1
                    1 (Champion)
                        |
            +-----------+-----------+
            |                       |
            1                       3
            |                       |
      +-----+-----+           +-----+-----+
      |           |           |           |
      2           1           3           7
      |           |           |           |
   +--+--+     +--+--+     +--+--+     +--+--+
   |     |     |     |     |     |     |     |
   2     6     1     4     3     5     8     7
&lt;/pre&gt;

&lt;p&gt;
In step 2 we remove 1 from the tournament in preparation to replay without them.
&lt;/p&gt;

&lt;pre class=&quot;example&quot; id=&quot;org2086dae&quot;&gt;
Sort output: 1,2
                        2 (Champion)
                        |
            +-----------+-----------+
            |                       |
            2                       3
            |                       |
      +-----+-----+           +-----+-----+
      |           |           |           |
      2           4           3           7
      |           |           |           |
   +--+--+     +--+--+     +--+--+     +--+--+
   |     |     |     |     |     |     |     |
   2     6     X     4     3     5     8     7
&lt;/pre&gt;

&lt;p&gt;
We started at the bottom of the tree, 4 has nobody to play so it moves up, 2 beats 4 and moves up, 2 beats 3 and becomes the new winner.
&lt;/p&gt;

&lt;p&gt;
Now we remove 2. Replaying from the bottom gives the tree below and we output the 3.
&lt;/p&gt;

&lt;pre class=&quot;example&quot; id=&quot;orgae2d0ba&quot;&gt;
Sort output: 1,2,3
                        3 (Champion)
                        |
            +-----------+-----------+
            |                       |
            4                       3
            |                       |
      +-----+-----+           +-----+-----+
      |           |           |           |
      6           4           3           7
      |           |           |           |
   +--+--+     +--+--+     +--+--+     +--+--+
   |     |     |     |     |     |     |     |
   x     6     X     4     3     5     8     7
&lt;/pre&gt;

&lt;p&gt;
It&apos;s easy to see how this process can repeat until the tree is empty and we successfully completed our sort in n lg n time!
&lt;/p&gt;

&lt;p&gt;
Check out this interactive visualization to fully understand the algorithm.
&lt;/p&gt;

&lt;div style=&quot;text-align: center; margin: 20px 0;&quot;&gt;
    &lt;a href=&quot;https://heyes-jones.com/externalsort/treeofwinners.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot; style=&quot;text-decoration: none;&quot;&gt;
        &lt;img src=&quot;../../../images/tree-of-winners-thumbnail.png&quot; 
             alt=&quot;K-Way Merge Tree of Winners Visualization&quot; 
             title=&quot;Click to launch interactive simulation&quot;
             style=&quot;width: 100%; max-width: 800px; height: auto; border: 1px solid #444; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);&quot;&gt;
        &lt;p style=&quot;margin-top: 8px; color: #666; font-size: 0.9em;&quot;&gt;
            👆 &lt;em&gt;Click to try the interactive simulation&lt;/em&gt;
        &lt;/p&gt;
    &lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;
Analysis.
&lt;/p&gt;

&lt;p&gt;
Again we find the asymptotic complexity is \(O(n \log_2 k)\). However, it is expected to perform better than the min-heap for larger k for the following reasons:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;You traverse from a single leaf at the bottom up to the root of the tree to replace the winner.&lt;/li&gt;
&lt;li&gt;At each level you need compare only with the current sibling.&lt;/li&gt;
&lt;li&gt;The number of comparisons is cut to \(\log_2 k\), half that of the worse case min-heap.&lt;/li&gt;
&lt;li&gt;Hardware Sympathy: Tournament trees have a fixed path from leaf to root. There are no conditional checks to see &quot;which child is smaller&quot; before deciding which path to take down; you always move up from the leaf. This can be friendlier to CPU branch prediction.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
There is still some room for improvement thanks to an ingenious idea from the 1950&apos;s.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgc7f5290&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgc7f5290&quot;&gt;Tree of Losers&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgc7f5290&quot;&gt;
&lt;p&gt;
In Knuth&apos;s Sorting and Searching (specifically Section 5.4.1), Donald Knuth attributes the origin of the &quot;tree of losers&quot; (also known as a loser tree) to H. B. Demuth. Demuth introduced the concept in his 1956 PhD thesis, Electronic Data Sorting, as a refinement of the standard tournament (winner) tree.
&lt;/p&gt;

&lt;p&gt;
His idea once again reduces the amount of comparisons needed. In the tree of winners to recalculate the path to the root, you must compare the new item against its sibling at every level. This requires keeping track of which child (left or right) the path came from so you can locate the sibling.
&lt;/p&gt;

&lt;p&gt;
Demuth&apos;s idea was to store the losers at each level instead of the winners. Similar to the linear scan algorithm we started with, the winner can be stored in a register helping with performance. 
&lt;/p&gt;

&lt;p&gt;
The algorithm looks like this:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Populate the tree of losers in a similar way to the tree of winners, but store the loser in each node.&lt;/li&gt;
&lt;li&gt;Remove the winner.&lt;/li&gt;
&lt;li&gt;Take the next candidate from the winners run.&lt;/li&gt;
&lt;li&gt;Starting from its leaf compare with each loser. If the winner loses in this comparison then swap it, otherwise continue moving up the tree.&lt;/li&gt;
&lt;li&gt;When you get to the top, whoever is stored in the winner register gets output.&lt;/li&gt;
&lt;li&gt;Repeat until the runs are empty.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Interactive tree of losers:
&lt;/p&gt;

&lt;div style=&quot;text-align: center; margin: 20px 0;&quot;&gt;
    &lt;a href=&quot;https://heyes-jones.com/externalsort/treeoflosers.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot; style=&quot;text-decoration: none;&quot;&gt;
        &lt;img src=&quot;../../../images/tree-of-losers-thumbnail.png&quot; 
             alt=&quot;K-Way Merge Tree of Losers Visualization&quot; 
             title=&quot;Click to launch interactive simulation&quot;
             style=&quot;width: 100%; max-width: 800px; height: auto; border: 1px solid #444; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);&quot;&gt;
        &lt;p style=&quot;margin-top: 8px; color: #666; font-size: 0.9em;&quot;&gt;
            👆 &lt;em&gt;Click to try the interactive simulation&lt;/em&gt;
        &lt;/p&gt;
    &lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;
Analysis.
&lt;/p&gt;

&lt;p&gt;
Asymptotic complexity is \(O(n \log_2 k)\) again.
&lt;/p&gt;

&lt;p&gt;
We have performance improvements for larger values of k primarily due to efficiency in memory access and branch prediction during the &quot;replay&quot; phase.
&lt;/p&gt;

&lt;p&gt;
Memory access:
&lt;/p&gt;

&lt;p&gt;
Remember in the winner tree we have to gather two siblings from memory and compare them with the current winner. In the tree of losers we have the winner in a register and we only fetch the parent &quot;loser&quot; from memory at each step.
&lt;/p&gt;

&lt;p&gt;
Branch prediction:
&lt;/p&gt;

&lt;p&gt;
While replaying the Winner tree we execute the conditional logic  &lt;code&gt;if (came_from_left) compare(new_val, right_child) else compare(new_val, left_child)&lt;/code&gt; whilst in the tree of losers we always just go to the parent of the current node. In addition the winning node is always in a register.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org3f9ed7d&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org3f9ed7d&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org3f9ed7d&quot;&gt;
&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;K-Way merge is ubiquitous in database technology.&lt;/li&gt;
&lt;li&gt;For small k (merging 4-16 runs) you can often use simple select and consider using SIMD.&lt;/li&gt;
&lt;li&gt;Otherwise Tree of Losers is likely to be the best performance.&lt;/li&gt;
&lt;/ul&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Algorithm&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Complexity (per item)&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Comparisons (approx)&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Key Characteristic&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Pros&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Cons&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;b&gt;Linear Scan&lt;/b&gt;&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(O(k)\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(k\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Iterates all candidates&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;CPU Prefetch &amp;amp; SIMD friendly for small \(k\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Scales poorly as \(k\) increases (&amp;gt;16)&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;b&gt;Min-Heap&lt;/b&gt;&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(O(\log k)\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(2 \log k\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Sift-down (swap with smallest child)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Standard library; Compact memory layout&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Conditional branches (left vs right child); Higher comparison count&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;b&gt;Winner Tree&lt;/b&gt;&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(O(\log k)\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(\log k\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Replay path from leaf to root&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Fewer comparisons than Heap&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Requires sibling checks at every level (branch mispredictions)&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;b&gt;Tree of Losers&lt;/b&gt;&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(O(\log k)\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;\(\log k\)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Compare with parent (loser)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;&lt;b&gt;Winner stays in register&lt;/b&gt;; Fixed memory path (always parent)&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;Slightly more complex implementation&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
You can view the Tigerbeetle current implementation here.
&lt;a href=&quot;https://github.com/tigerbeetle/tigerbeetle/blob/main/src/lsm/k_way_merge.zig&quot;&gt;Tigerbeetle K-Way merge&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Thanks for reading, please contact me using the email and social links above with any comments and corrections.
&lt;/p&gt;

&lt;p&gt;
©2026 Justin Heyes-Jones. All Rights Reserved
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Mon, 19 Jan 2026 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2026/01/19/visualizing-k-way-merge.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2026/01/19/visualizing-k-way-merge.html</guid>
        
        <category>algorithms</category>
        
        <category>databases</category>
        
        
      </item>
    
      <item>
        <title>Optimizing training a GPT style Tokenizer with C++</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;

&lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;

&lt;style&gt;
  .chart-container {
      position: relative;
      width: 100%;
      max-width: 800px;
      margin-left: auto;
      margin-right: auto;
      height: 300px;
      max-height: 40vh;
  }
  @media (min-width: 768px) {
      .chart-container {
          height: 400px;
      }
  }
  .chart-btn {
      padding: 0.5rem 1rem;
      font-size: 0.875rem;
      font-weight: 500;
      border-radius: 0.375rem;
      transition: background-color 0.2s, color 0.2s;
      border: 1px solid #e2e8f0;
      color: #475569;
  }
  .chart-btn-active {
      background-color: #3b82f6;
      color: white;
      border-color: #3b82f6;
  }
&lt;/style&gt;

&lt;script&gt;
    document.addEventListener(&apos;DOMContentLoaded&apos;, () =&gt; {
        const benchmarkData = {
            taylorswift: {
                labels: [&apos;Python&apos;, &apos;C++ (First)&apos;, &apos;C++ (Lexical)&apos;],
                times: [11.0, 5.5, 0.04], // Using 0.04 instead of 0.0 for log scale
            },
            shakespeare: {
                labels: [&apos;Python&apos;, &apos;C++ (First)&apos;, &apos;C++ (Lexical)&apos;],
                times: [77.5, 36.5, 1.50],
            },
            bible: {
                labels: [&apos;Python&apos;, &apos;C++ (First)&apos;, &apos;C++ (Lexical)&apos;],
                times: [298.5, 107.0, 5.5],
            },
            wikitext: {
                labels: [&apos;Python&apos;, &apos;C++ (First)&apos;, &apos;C++ (Lexical)&apos;],
                times: [46080.0, 13500.0, 2217.5],
            }
        };

        const ctx = document.getElementById(&apos;benchmarkChart&apos;).getContext(&apos;2d&apos;);
        
        const benchmarkChart = new Chart(ctx, {
            type: &apos;bar&apos;,
            data: {
                labels: [],
                datasets: [{
                    label: &apos;Training Time (seconds)&apos;,
                    data: [],
                    backgroundColor: [
                        &apos;rgba(255, 99, 132, 0.2)&apos;,
                        &apos;rgba(54, 162, 235, 0.2)&apos;,
                        &apos;rgba(75, 192, 192, 0.2)&apos;
                    ],
                    borderColor: [
                        &apos;rgba(255, 99, 132, 1)&apos;,
                        &apos;rgba(54, 162, 235, 1)&apos;,
                        &apos;rgba(75, 192, 192, 1)&apos;
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: &apos;y&apos;,
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true,
                        type: &apos;logarithmic&apos;,
                        title: {
                            display: true,
                            text: &apos;Time in Seconds (Logarithmic Scale)&apos;
                        },
                        grid: {
                          display: false
                        }
                    },
                    y: {
                        grid: {
                          display: false
                        }

                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || &apos;&apos;;
                                if (label) {
                                    label += &apos;: &apos;;
                                }
                                if (context.parsed.x !== null) {
                                    label += context.parsed.x.toFixed(2) + &apos; seconds&apos;;
                                }
                                return label;
                            }
                        }
                    }
                }
            },
            plugins: [],
        });

        const buttons = document.querySelectorAll(&apos;.chart-btn&apos;);

        function updateChart(datasetName) {
            const newData = benchmarkData[datasetName];
            benchmarkChart.data.labels = newData.labels;
            benchmarkChart.data.datasets[0].data = newData.times;
            benchmarkChart.update();

            buttons.forEach(button =&gt; {
                if (button.dataset.corpus === datasetName) {
                    button.classList.add(&apos;chart-btn-active&apos;);
                } else {
                    button.classList.remove(&apos;chart-btn-active&apos;);
                }
            });
        }

        buttons.forEach(button =&gt; {
            button.addEventListener(&apos;click&apos;, () =&gt; {
                updateChart(button.dataset.corpus);
            });
        });

        // Set initial active state
        updateChart(&apos;taylorswift&apos;);
        
        // Smooth scrolling for nav links
        document.querySelectorAll(&apos;a[href^=&quot;#&quot;]&apos;).forEach(anchor =&gt; {
            anchor.addEventListener(&apos;click&apos;, function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute(&apos;href&apos;)).scrollIntoView({
                    behavior: &apos;smooth&apos;
                });
            });
        });
    });
&lt;/script&gt;

&lt;div id=&quot;outline-container-org2e0801c&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org2e0801c&quot;&gt;Introduction&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org2e0801c&quot;&gt;
&lt;p&gt;
In February 2024, renowned AI researcher and educator Andrej Karpathy, published the following video. 
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=zduSFxRajkE&quot;&gt;https://www.youtube.com/watch?v=zduSFxRajkE&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
An excellent introduction to the fascinating topic of tokenization,
something he considers a necessary evil right now. Maybe the need for
it will go away but for now it must be well understood by AI engineers
in order to get good results when building and using large language
models.
&lt;/p&gt;

&lt;p&gt;
As software engineers in 2025 the advent of large language models, and
generative AI in general, bring about a profound shift in how we
design, develop and implement software systems. As such I have been
delving into the details of how they they work, with Tokenization being
a significant side quest.
&lt;/p&gt;

&lt;p&gt;
In this blog, related video and accompanying C++ project, I will walk
through my exploration of the training aspect of tokenizers and look
at their performance characteristics and optimization opportunities.
&lt;/p&gt;

&lt;p&gt;
My main goal was to port the Python to C++ but also I became interested in optimizing the training stage.
&lt;/p&gt;

&lt;p&gt;
Training SOTA (State of the Art) models is a massive expense in terms of time and computation needed. The Llama 3 model was trained on 15 trillion tokens, and although it is not known, its tokenizer may also have been trained on the whole data set. Even if it used only a smaller representative sample, tokenizer training is also a huge expense.
&lt;/p&gt;

&lt;p&gt;
For that reason it stands to reason you would want to optimize it as much as possible so that changes to the data set or algorithm can be made more easily and quickly.
&lt;/p&gt;

&lt;p&gt;
Ultimately, I was able to reduce the training time by a factor of 23 (for the large wikitext input) as shown below.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgb8bea08&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb8bea08&quot;&gt;Optimization results&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb8bea08&quot;&gt;
&lt;div class=&quot;text-center mb-12&quot;&gt;
        &lt;p class=&quot;mt-2 text-lg text-slate-600&quot;&gt;The interactive chart below shows the time taken to train a Tokenizer on different text corpora. Use the buttons to switch between datasets and see the performance difference.&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;bg-white p-6 md:p-8 rounded-xl border border-slate-200 shadow-sm&quot; style=&quot;padding: 0.5em; background-color: #fcfcfc;&quot;&gt;
        &lt;div class=&quot;flex flex-wrap justify-center items-center mb-6 space-x-2 space-y-2&quot;&gt;
            &lt;button data-corpus=&quot;taylorswift&quot; class=&quot;chart-btn&quot;&gt;Taylor Swift&lt;/button&gt;
            &lt;button data-corpus=&quot;shakespeare&quot; class=&quot;chart-btn&quot;&gt;Shakespeare&lt;/button&gt;
            &lt;button data-corpus=&quot;bible&quot; class=&quot;chart-btn&quot;&gt;Bible&lt;/button&gt;
            &lt;button data-corpus=&quot;wikitext&quot; class=&quot;chart-btn&quot;&gt;Wikitext-103&lt;/button&gt;
        &lt;/div&gt;
        &lt;div class=&quot;chart-container&quot;&gt;
            &lt;canvas id=&quot;benchmarkChart&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;
         &lt;p class=&quot;text-center text-xs text-slate-500 mt-4&quot;&gt;Lower is better. Time in seconds.&lt;/p&gt;
    &lt;/div&gt;

&lt;p&gt;
Input data sets used:
&lt;/p&gt;
&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;taylorswift. Text of the Taylor Swift wikipedia page.&lt;/li&gt;
&lt;li&gt;shakespeare. The complete works of Shakespeare.&lt;/li&gt;
&lt;li&gt;bible. The old and new testament of the Bible.&lt;/li&gt;
&lt;li&gt;wikitext-103. &lt;a href=&quot;https://huggingface.co/datasets/Salesforce/wikitext&quot;&gt;https://huggingface.co/datasets/Salesforce/wikitext&lt;/a&gt; 100 million tokens of high quality wikipedia articles.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
These are included in the repository apart from wikitext which you can download from hugging face.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org5a48473&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org5a48473&quot;&gt;Briefly, Tokenization and BPE&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org5a48473&quot;&gt;
&lt;p&gt;
I don&apos;t want to even try and do a better job of explaining the need
for tokenization and the BPE algorithm than Karpathy, so I instead
recommend watching his video and, for additional insights, read the
paper below:
&lt;/p&gt;

&lt;p&gt;
[Neural Machine Translation of Rare Words with Subword Units](&lt;a href=&quot;https://arxiv.org/pdf/1508.07909&quot;&gt;https://arxiv.org/pdf/1508.07909&lt;/a&gt;)
&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org457d3c1&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org457d3c1&quot;&gt;The need for tokenization&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org457d3c1&quot;&gt;
&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;Large language models deal with numbers not words or characters, so we must map input text to numbers.&lt;/li&gt;
&lt;li&gt;The model requires a fixed size vocabulary.&lt;/li&gt;
&lt;li&gt;Unfortunately, that vocabulary would have to be enormous to fit all words from all languages.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org61241d9&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org61241d9&quot;&gt;Sub word unit tokenization&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org61241d9&quot;&gt;
&lt;p&gt;
The solution to these issues is sub-word tokenization; splitting words
up into numbers representing components of words. Once you have that
you can handle:
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;&lt;b&gt;Open-Vocabulary&lt;/b&gt; Part of the token set is the basic characters of each language so you can represent every word.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Rare words&lt;/b&gt; Because the vocabulary set is open it means any rare word is handled.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Translation of Novel Words&lt;/b&gt; The model can translate and generate words it has not encountered before by composing them from sub-word units.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Here is a diagram showing how the fixed sized vocabulary of tokens maps to an array of learned embedding vectors that feed into the Transformer model underlying all LLMs.
&lt;/p&gt;

&lt;pre class=&quot;example&quot; id=&quot;org1d5d662&quot;&gt;
      Input Text
          │
          ▼
     &quot;I love NLP&quot;
          │
┌─────────┴─────────┐
│   Tokenizer       │
└─────────┬─────────┘
          │
          ▼
      Tokens
   [&quot;i&quot;, &quot;love&quot;, &quot;nlp&quot;]
          │
┌─────────┴─────────┐
│ Vocabulary Lookup │
└─────────┬─────────┘
          │
          ▼
      Token IDs
      [25, 2097, 12510]
          │
          │         ┌───────────────────────────────────┐
          │         │          Embedding Matrix         │
          │         │ (Size: |V| x d_model)            │
          │         ├───────────────────────────────────┤
          ├────────►│ Row 25:   [0.1, -0.4, 0.2, ...]   │  ───►  Embedding for &quot;i&quot;
          │         ├───────────────────────────────────┤
          ├────────►│ Row 2097: [-0.8, 0.5, 0.9, ...]   │  ───►  Embedding for &quot;love&quot;
          │         ├───────────────────────────────────┤
          ├────────►│ Row 12510: [0.3, 0.7, -0.1, ...]  │  ───►  Embedding for &quot;nlp&quot;
          │         ├───────────────────────────────────┤
          │         │                ...                │
          │         └───────────────────────────────────┘
          │
          ▼
  Input Embeddings
(Dense Vectors fed to the model)
&lt;/pre&gt;

&lt;p&gt;
Tokenization means taking text and splitting it into sub-word (and whole-word or even multi-word) units. An input text like &lt;code&gt;&quot;My cat, Blivarian, is making a mess.&quot;&lt;/code&gt; may be tokenized into something like this:
&lt;/p&gt;

&lt;p&gt;
You can explore this tokenization here:
&lt;a href=&quot;https://platform.openai.com/tokenizer&quot;&gt;https://platform.openai.com/tokenizer&lt;/a&gt;
&lt;/p&gt;

&lt;p class=&quot;text-4xl flex&quot;&gt;
  &lt;span style=&quot;background-color: #d1c4e9;&quot;&gt;My &lt;/span&gt;
  &lt;span style=&quot;background-color: #c8e6c9;&quot;&gt;cat&lt;/span&gt;
  &lt;span style=&quot;background-color: #f0f4c3;&quot;&gt;, &lt;/span&gt;
  &lt;span style=&quot;background-color: #ffcdd2;&quot;&gt;Bl&lt;/span&gt;
  &lt;span style=&quot;background-color: #b3e5fc;&quot;&gt;iv&lt;/span&gt;
  &lt;span style=&quot;background-color: #d1c4e9;&quot;&gt;arian&lt;/span&gt;
  &lt;span style=&quot;background-color: #f0f4c3;&quot;&gt;, &lt;/span&gt;
  &lt;span style=&quot;background-color: #c8e6c9;&quot;&gt; is&lt;/span&gt;
  &lt;span style=&quot;background-color: #ffcdd2;&quot;&gt; making&lt;/span&gt;
  &lt;span style=&quot;background-color: #b3e5fc;&quot;&gt; a&lt;/span&gt;
  &lt;span style=&quot;background-color: #d1c4e9;&quot;&gt; mess&lt;/span&gt;
  &lt;span style=&quot;background-color: #c8e6c9;&quot;&gt;.&lt;/span&gt;
&lt;/p&gt;

&lt;p&gt;
[5444, 9059, 11, 3130, 569, 21203, 11, 382, 4137, 261, 13017, 13]
&lt;/p&gt;

&lt;p&gt;
Notice that the commas have the same token value when appearing in
different places. Also that common words like cat and mess have their
own tokens.
&lt;/p&gt;

&lt;p&gt;
I deliberately made up a name for the made up Cat that is not a real
word &quot;Blivarian&quot;. You can see that it is split up into 3 sub
words. Without tokenization this would instead have been stored with a
special &quot;Out of vocabulary&quot; token, that means it carries no semantic
meaning. When dealing with sub word tokens however, the LLM has the
opportunity to build up meaning for those components that may help
with overall model quality.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org5b03015&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org5b03015&quot;&gt;Byte Pair Encoding - BPE&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org5b03015&quot;&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-org6a0c0da&quot; class=&quot;outline-4&quot;&gt;
&lt;h4 id=&quot;org6a0c0da&quot;&gt;Why BPE?&lt;/h4&gt;
&lt;div class=&quot;outline-text-4&quot; id=&quot;text-org6a0c0da&quot;&gt;
&lt;p&gt;
From above we understand that we should split words into sub-word
components to handle the vast space of human vocabulary in the finite
space of the LLMs vocabulary.
&lt;/p&gt;

&lt;p&gt;
How to do that is the next question. Why not, for example, just have a
vocabulary consisting of the punctuation and alphabetic characters of
every language?
&lt;/p&gt;

&lt;p&gt;
It won&apos;t work well because in the LLM training it will build up an
embedding vector for each token, the unit of vocabulary. This vector
is an array of numbers that represents a direction in multidimensional
space. To us those numbers mean nothing, but in LLM training those
numbers, when used in conjunction with the rest of the models weights,
can be used to learn and represent all kinds of meaning.
&lt;/p&gt;

&lt;p&gt;
Models like Transformers have a finite context window. When sequences
are excessively long, it becomes much harder for the model to capture
long-range dependencies and relationships between words that are far
apart. The model has to work harder to understand the overall context.
&lt;/p&gt;

&lt;p&gt;
Instead we want something that splits things into meaningful chunks, morphemes, as well as capturing commonly used words with tokens. This ends up looking something like Huffman Encoding:
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://en.wikipedia.org/wiki/Huffman_coding&quot;&gt;https://en.wikipedia.org/wiki/Huffman_coding&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
It represents more frequently occurring substrings with less bits, giving us a more efficient data size.
&lt;/p&gt;

&lt;p&gt;
Similarly, BPE, is data-driven algorithm that creates a vocabulary of meaningful and frequently occurring subword units.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgcab669d&quot; class=&quot;outline-4&quot;&gt;
&lt;h4 id=&quot;orgcab669d&quot;&gt;BPE algorithm&lt;/h4&gt;
&lt;div class=&quot;outline-text-4&quot; id=&quot;text-orgcab669d&quot;&gt;
&lt;p&gt;
First you need to train across a large corpus of realistic text. For
state of the art (SOTA) LLMs this is likely in the trillions of
characters of data.
&lt;/p&gt;

&lt;p&gt;
The algorithm itself is very simple, it works as follows:
&lt;/p&gt;

&lt;p&gt;
Start with 256 tokens (0 to 255), our basic character set.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;First turn the text into its underlying numeric representation (typically just the bytes of a UTF-8 input).&lt;/li&gt;
&lt;li&gt;Count all the pairs of bytes. &lt;/li&gt;
&lt;li&gt;Pick the most frequently occurring pair and generate the next new token (257, 258&amp;#x2026;).&lt;/li&gt;
&lt;li&gt;Replace that pair wherever it occurs with the new token.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Repeat until you have your full vocabulary. You can then save the
merge pairs and these are then used by end users to encode their text
before sending to the model.
&lt;/p&gt;

&lt;p&gt;
They can also be used to reconstruct the original text in the decoding
process when the response comes from the model.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org60512a5&quot; class=&quot;outline-4&quot;&gt;
&lt;h4 id=&quot;org60512a5&quot;&gt;Conflict Resolution&lt;/h4&gt;
&lt;div class=&quot;outline-text-4&quot; id=&quot;text-org60512a5&quot;&gt;
&lt;p&gt;
An important decision in tokenization is how to handle pairs with the same frequency. In this post I&apos;ll consider two methods:
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;First in corpus wins. &lt;/li&gt;
&lt;li&gt;Lexicographical ordering.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
With any tokenization algorithm design we need to consider efficiency
of implementation alongside methods that give the best results. Some
of these concerns will be highlighted below.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org12ceb67&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org12ceb67&quot;&gt;minbpe-cc an exercise in optimization&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org12ceb67&quot;&gt;
&lt;p&gt;
With these algorithmic decisions in mind, I was ready to dive into the
C++ implementation and see how they performed in practice. This led to
my project, minbpe-cc. I find the best way to learn a topic is to get
my hands dirty, and as such I decided to reimplement Karpathy&apos;s Python
code in C++.
&lt;/p&gt;

&lt;p&gt;
I also wanted to focus on optimization of the training stage, for no
other reason than curiosity.
&lt;/p&gt;

&lt;p&gt;
Why C++?
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;It&apos;s a low level language with generally low to zero cost abstractions.&lt;/li&gt;
&lt;li&gt;I&apos;ve recently been catching up with modern C++ and wanted to try out some of the new features (C++23 required).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The final code here fully implements all the facets of Karpathy&apos;s minbpe including encoding, decoding and training. I&apos;ve included end to end tests and tested in a linux and MacOS environment. I have not tested on Windows yet, but I expect it will work without much modification.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/minbpe-cc&quot;&gt;https://github.com/justinhj/minbpe-cc&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org75441f7&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org75441f7&quot;&gt;Implementation tales&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org75441f7&quot;&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-orgd71570e&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;orgd71570e&quot;&gt;Speed bumps&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-orgd71570e&quot;&gt;
&lt;p&gt;
Converting from Python to C++ is fairly straightforward although I hit some speed bumps on the way:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Python dictionary behaviour. The Python dictionary is designed to be flexible for multiple purposes rather than optimized, so getting the same behaviour from C++ containers required some additional thought.&lt;/li&gt;
&lt;li&gt;Polymorphism. I didn&apos;t really like Karpathy&apos;s polymorphic version and instead decided to use a single class design with flags and other parameters to handle whether special tokens are used, what the conflict strategy was, and whether to use a regex or not. It was quite easy to make this work with some tweaks to the original code. Ironically I did use polymorphism on the PairCount class so I can use different implementations at runtime depending on the users preferences.&lt;/li&gt;
&lt;li&gt;CMake. CMake is not a casual tool. I found I could just about get my project to build and run using it, but after switching to Zig build instead I found it much easier to manage. In other words to effectively use CMake would require me to read the manual in a lot more detail.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-orgfb58706&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;orgfb58706&quot;&gt;Regex compatibility&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-orgfb58706&quot;&gt;
&lt;p&gt;
Firstly, what are regexes needed for? 
&lt;/p&gt;

&lt;p&gt;
In the GPT series of tokenizers, OpenAI realized that it is beneficial to
try and keep parts of text together, as such rather than run BPE on
the whole input text, they first divide it up into sections by the
following regular expressions:
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;GPT2 &lt;code&gt;&quot;&apos;(?:[sdmt]|ll|ve|re)| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+&quot;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;GPT4 &lt;code&gt;&quot;&apos;(?i:[sdmt]|ll|ve|re)|[^\\r\\n\\p{L}\\p{N}]?+\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]++[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+&quot;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
These expressions are designed to preserve various aspects of English text rather than allow them to be split up during the merge process.
&lt;/p&gt;

&lt;p&gt;
Whilst there are a few established regex libraries for C++ (writing my own being out of scope for this project), finding one that was capable of handling these regular expressions took some looking. 
&lt;/p&gt;

&lt;p&gt;
These expressions need support for unicode matchers and also negative lookahead.
&lt;/p&gt;

&lt;p&gt;
I compared several libraries:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;RE2 from Google.&lt;/li&gt;
&lt;li&gt;std::regex in the C++ standard library.&lt;/li&gt;
&lt;li&gt;Boost::regex&lt;/li&gt;
&lt;li&gt;Re-Flex&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
None of these met the requirements. 
&lt;/p&gt;

&lt;p&gt;
In the end I found the Perl compatible PRE2 library worked the best.
&lt;/p&gt;

&lt;p&gt;
The biggest footgun was that the Boost::regex library was asserting
because Boost was not linking properly with the ICU
(internationalization) library. I suspect this could be made to work
but I gave up.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org268ef34&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org268ef34&quot;&gt;Optimization mantras&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org268ef34&quot;&gt;
&lt;p&gt;
In System&apos;s Performance, Enterprise and the Cloud by Brendan Gregg (2021) the following mantras for performance are listed, ordered from most to least effective. I find these useful when considering optimization.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Don’t do it.&lt;/li&gt;
&lt;li&gt;Do it, but don’t do it again.&lt;/li&gt;
&lt;li&gt;Do it less.&lt;/li&gt;
&lt;li&gt;Do it later.&lt;/li&gt;
&lt;li&gt;Do it when they’re not looking.&lt;/li&gt;
&lt;li&gt;Do it concurrently.&lt;/li&gt;
&lt;li&gt;Do it more cheaply.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
We can refer to these during the post.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgdf21769&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;orgdf21769&quot;&gt;Data structures&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-orgdf21769&quot;&gt;
&lt;p&gt;
The first step to port the Python code and make it more efficient is to think about the data involved and how that data needs to accessed. 
&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orge5842ea&quot; class=&quot;outline-4&quot;&gt;
&lt;h4 id=&quot;orge5842ea&quot;&gt;Data&lt;/h4&gt;
&lt;div class=&quot;outline-text-4&quot; id=&quot;text-orge5842ea&quot;&gt;
&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;Body text. We will store this as a vector (array) of numbers representing the input text for training.&lt;/li&gt;
&lt;li&gt;Pair frequencies. We need to keep track of all the pairs in the body text and their frequencies. &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgee29ac0&quot; class=&quot;outline-4&quot;&gt;
&lt;h4 id=&quot;orgee29ac0&quot;&gt;Access patterns&lt;/h4&gt;
&lt;div class=&quot;outline-text-4&quot; id=&quot;text-orgee29ac0&quot;&gt;
&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;Body text. We need sequential access to scan for pairs. Then we need to be able to delete elements as part of the merge process.&lt;/li&gt;
&lt;li&gt;Pair frequencies. We need to be able to store the pairs and their frequencies and efficiently update them as we scan the body text. In addition we need fast access to the next most frequent pair.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgcfe6a9b&quot; class=&quot;outline-4&quot;&gt;
&lt;h4 id=&quot;orgcfe6a9b&quot;&gt;Implementation&lt;/h4&gt;
&lt;div class=&quot;outline-text-4&quot; id=&quot;text-orgcfe6a9b&quot;&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-org6edd3b9&quot; class=&quot;outline-5&quot;&gt;
&lt;h5 id=&quot;org6edd3b9&quot;&gt;Body text&lt;/h5&gt;
&lt;div class=&quot;outline-text-5&quot; id=&quot;text-org6edd3b9&quot;&gt;
&lt;p&gt;
Because the body text required sequential access and the ability to quickly remove elements I used a singly linked list, or &lt;code&gt;forward_list&lt;/code&gt;. This has the desirable properties of sequential access and O(1) deletions.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;forward_list&lt;/code&gt; has the lowest memory overhead of all std C++ containers (a single pointer to the next element.
&lt;/p&gt;

&lt;p&gt;
Other valid options considered:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Keep in a vector but use tombstones for removed items. This has the&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
   advantage of eliminating the memory moves for each replacement, and
   it doesn&apos;t have the problem forward list has with giving us a way
   to know the position in the input text (see later). This is quite a
   tricky implementation but perfectly feasible.
&lt;/p&gt;
&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Keep in a vector and do the memory moves. Requires a lot of memory&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
   bandwidth and cpu for the copying but it is simple.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org7c71903&quot; class=&quot;outline-5&quot;&gt;
&lt;h5 id=&quot;org7c71903&quot;&gt;Pair frequencies&lt;/h5&gt;
&lt;div class=&quot;outline-text-5&quot; id=&quot;text-org7c71903&quot;&gt;
&lt;p&gt;
Ultimately I needed multiple structures here as I wanted to support more than one conflict resolution strategy and since these are picked by the user at runtime we need dynamic dispatch. So first I made a virtual class with the required interface for both:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-c++&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCount&lt;/span&gt; {
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;public&lt;/span&gt;:
&amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Virtual destructor to ensure proper cleanup of derived classes.&lt;/span&gt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;virtual&lt;/span&gt; ~PairCount() = &lt;span style=&quot;color: #b6a0ff;&quot;&gt;default&lt;/span&gt;;

&amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Gets the total number of unique pairs stored.&lt;/span&gt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;virtual&lt;/span&gt; size_t get_count() = 0;

&amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Retrieves the count for a specific pair.&lt;/span&gt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;virtual&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;optional&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt;&amp;gt; get_pair(&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;mp&lt;/span&gt;) = 0;

&amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Creates a new pair or modifies the frequency of an existing one.&lt;/span&gt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;virtual&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;bool&lt;/span&gt; create_or_modify_pair(&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;freq&lt;/span&gt;) = 0;

&amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Gets the pair with the highest count.&lt;/span&gt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;virtual&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;optional&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;gt; get_top_pair_count() = 0;

&amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Retrieves all pairs and their counts.&lt;/span&gt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;virtual&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;std&lt;/span&gt;::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;vector&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #00bcff;&quot;&gt;std&lt;/span&gt;::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;vector&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;gt; get_all() = 0;
};
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that the class has a template parameter, as the Tokenizer can be recompiled with different underlying numeric types for the tokens.
&lt;/p&gt;
&lt;/div&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;&lt;a id=&quot;org007443d&quot;&gt;&lt;/a&gt;Conflict resolution strategy: First seen in input&lt;br /&gt;
&lt;div class=&quot;outline-text-6&quot; id=&quot;text-org007443d&quot;&gt;
&lt;p&gt;
Imagine a sequence as follows:
&lt;/p&gt;

&lt;p&gt;
1,2,8,9,3,4&amp;#x2026;
&lt;/p&gt;

&lt;p&gt;
After counting all the pairs we find that [1,2] and [3,4] have the same frequency.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;[1,2] =&amp;gt; 20 &lt;/li&gt;
&lt;li&gt;[3,4] =&amp;gt; 20&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
In this case we pick the one added first, which means the one first seen
in the input text.
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
In Python this insertion order comes for free because of Raymond
Hettinger&apos;s 2012 redesign of the Python dictionary. Implemented in
Python 3.6 (released December 23, 2016), introduced compact
dictionaries with key-sharing and faster performance. A side effect of
this redesign was that dictionaries began preserving insertion order
as an implementation detail. This was later formalized as a language
guarantee in Python 3.7 (released June 27, 2018), meaning dictionaries
officially maintain the order of key-value pairs as they are inserted.
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
In Karpathy&apos;s code you can see that he simply relies on this behaviour
to get the consistent result based on above.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-python&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;# &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;count up the number of times every consecutive pair appears&lt;/span&gt;
&lt;span style=&quot;color: #00d3d0;&quot;&gt;stats&lt;/span&gt; = get_stats(ids)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;# &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;find the pair with the highest count&lt;/span&gt;
&lt;span style=&quot;color: #00d3d0;&quot;&gt;pair&lt;/span&gt; = &lt;span style=&quot;color: #f78fe7;&quot;&gt;max&lt;/span&gt;(stats, key=stats.get)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
And from the Python documentation: &lt;a href=&quot;https://docs.python.org/3/library/functions.html#max&quot;&gt;https://docs.python.org/3/library/functions.html#max&lt;/a&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
If multiple items are maximal, the function returns the first one
encountered. This is consistent with other sort-stability preserving
tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and
heapq.nlargest(1, iterable, key=keyfunc).
&lt;/p&gt;

&lt;p&gt;
In order to implement that we must track the insertion order. Rather
than let the user deal with that I built it into the PairCount
class. As elements are added, new ones get the current count and the
count is incremented.
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Picking a data structure here is tricky because we want to be able to
quickly store and modify pair frequencies (unordered&lt;sub&gt;map&lt;/sub&gt;), and a way
to get the most frequent (priority&lt;sub&gt;queue&lt;/sub&gt;). Furthermore, we want to
keep track of insertion order?
&lt;/p&gt;

&lt;p&gt;
Sometimes you need to use multiple data structures to support a use case with conflicting requirements. For this purpose I used the &lt;code&gt;boost::multi_index&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://www.boost.org/doc/libs/1_88_0/libs/multi_index/doc/index.html&quot;&gt;https://www.boost.org/doc/libs/1_88_0/libs/multi_index/doc/index.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
There&apos;s nothing to stop you from using a set and a priority queue and
tracking them yourself, but multi&lt;sub&gt;index&lt;/sub&gt; handles that for you based on
the declaration of which indexes and access patterns you need.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s take a look at the implementation of &lt;code&gt;PairCountInsertOrder&lt;/code&gt;:
&lt;/p&gt;

&lt;p&gt;
First the data; we need to store pair, the count and the insert order.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-c++&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;struct&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt; {
&amp;#160; &amp;#160; ::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt; pair;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt; count;
&amp;#160; &amp;#160; size_t insert_order;

&amp;#160; &amp;#160; PairCountOrder(::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;p&lt;/span&gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;c&lt;/span&gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;size_t&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;fo&lt;/span&gt;) : pair(p), count(c), insert_order(fo) {}
&amp;#160; &amp;#160; PairCountOrder(::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;p&lt;/span&gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;c&lt;/span&gt;) : pair(p), count(c), insert_order(&lt;span style=&quot;color: #00bcff;&quot;&gt;std&lt;/span&gt;::&lt;span style=&quot;color: #00bcff;&quot;&gt;numeric_limits&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;size_t&lt;/span&gt;&amp;gt;::max()) {}
};

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Comparison struct for sorting. Sorts by count (descending), then by insertion order (ascending).&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;struct&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;CompareCountOrder&lt;/span&gt; {
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;bool&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;operator&lt;/span&gt;()(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;amp; &lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;, &lt;span style=&quot;color: #b6a0ff;&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;amp; &lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;const&lt;/span&gt; {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt;(a.count == b.count) {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; a.insert_order &amp;lt; b.insert_order;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; } &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; a.count &amp;gt; b.count; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;higher count is greater&lt;/span&gt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; }
&amp;#160; &amp;#160; }
};
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Next we define the container itself. We just specify the indexes required and Boost takes care of picking the underlying data structures.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-c++&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;using&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountStore&lt;/span&gt; = &lt;span style=&quot;color: #00bcff;&quot;&gt;boost&lt;/span&gt;::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;multi_index_container&lt;/span&gt;&amp;lt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;,
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;indexed_by&lt;/span&gt;&amp;lt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Index 0: Hashed unique index on the &apos;pair&apos; member for fast lookups.&lt;/span&gt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;hashed_unique&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;member&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;, &amp;amp;&lt;span style=&quot;color: #00bcff;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;::pair&amp;gt;&amp;gt;,
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Index 1: Ordered non-unique index for sorting by count and insertion order.&lt;/span&gt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;ordered_non_unique&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;identity&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;CompareCountOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;gt;
&amp;#160; &amp;#160; &amp;gt;
&amp;gt;;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Index 0 explanation:
It is hashed so we should get an O(1) lookup type, and unique meaning keys are unique, each pair can occur once only.
The rest of the declaration explains how to get the key for this index (use the pair member).
&lt;/p&gt;

&lt;p&gt;
Index 1 explanation: 
This needs to be an ordered collection so we can extract the highest
frequency. It also needs to be non-unique (in its sort criteria),
because we can have multiple elements with the same frequency.
&lt;/p&gt;

&lt;p&gt;
Now in our code we can grab the appropriate index depending on the
current purpose and when we make modifications to the data the boost
library will ensure the changes are synchronized across all the
indexes in the container.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-C++&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;auto&lt;/span&gt;&amp;amp; &lt;span style=&quot;color: #00d3d0;&quot;&gt;index_by_key&lt;/span&gt; = pcs.&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt; get&amp;lt;0&amp;gt;();
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;auto&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;f&lt;/span&gt; = index_by_key.find(mp);
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt;(f != pcs.end()) {
&amp;#160; &amp;#160; index_by_key.modify(f, [&lt;span style=&quot;color: #00bcff;&quot;&gt;freq&lt;/span&gt;](&lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountOrder&lt;/span&gt;&amp;lt;T&amp;gt;&amp;amp; &lt;span style=&quot;color: #00d3d0;&quot;&gt;pc&lt;/span&gt;) { pc.count += freq; });
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;;
} &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; {
&amp;#160; &amp;#160; pcs.insert(PairCountOrder&amp;lt;T&amp;gt;(mp, freq, next_insert++));
&amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;;
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a id=&quot;org68fb120&quot;&gt;&lt;/a&gt;Conflict resolution strategy: Lexicographical&lt;br /&gt;
&lt;div class=&quot;outline-text-6&quot; id=&quot;text-org68fb120&quot;&gt;
&lt;p&gt;
Referred to as lexical in my implementation to save typing, this method means we pick from pairs based on which comes first. For example given the following two pairs:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;[1,2] =&amp;gt; 20 &lt;/li&gt;
&lt;li&gt;[3,4] =&amp;gt; 20&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
They have the same frequency so we pick pair 1) as 1 &amp;lt; 3. The second member
of the pair is used as the tie-breaker, and of course if both members
are the same then they would be combined to a single entry in the
PairCount.
&lt;/p&gt;

&lt;p&gt;
Again a multi&lt;sub&gt;index&lt;/sub&gt; container is needed here. Let&apos;s start with the data:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-c++&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;struct&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexical&lt;/span&gt; {
&amp;#160; &amp;#160; ::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt; pair;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt; count;

&amp;#160; &amp;#160; PairCountLexical(::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;p&lt;/span&gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;int&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;c&lt;/span&gt;) : pair(p), count(c) {}
};

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Comparison struct for sorting. Sorts by count (descending), then by pair (lexical ascending).&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;struct&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;CompareLexicalOrder&lt;/span&gt; {
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;bool&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;operator&lt;/span&gt;()(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexical&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;amp; &lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;, &lt;span style=&quot;color: #b6a0ff;&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexical&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;amp; &lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;const&lt;/span&gt; {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt;(a.count == b.count) {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; (a.pair.first == b.pair.first) {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; a.pair.second &amp;lt; b.pair.second;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; } &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; a.pair.first &amp;lt; b.pair.first;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; }
&amp;#160; &amp;#160; &amp;#160; &amp;#160; } &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; {
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;return&lt;/span&gt; a.count &amp;gt; b.count; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;higher count is greater&lt;/span&gt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; }
&amp;#160; &amp;#160; }
};
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
And the container looks like this:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-c++&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;template&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;typename&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;using&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexicalStore&lt;/span&gt; = &lt;span style=&quot;color: #00bcff;&quot;&gt;boost&lt;/span&gt;::&lt;span style=&quot;color: #6ae4b9;&quot;&gt;multi_index_container&lt;/span&gt;&amp;lt;
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexical&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;,
&amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;indexed_by&lt;/span&gt;&amp;lt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Index 0: Hashed unique index on the &apos;pair&apos; member for fast lookups.&lt;/span&gt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;hashed_unique&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;member&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexical&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;pair&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;,&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;, &amp;amp;&lt;span style=&quot;color: #00bcff;&quot;&gt;PairCountLexical&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;::pair&amp;gt;&amp;gt;,
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Index 1: Ordered non-unique index for sorting by count and lexical order.&lt;/span&gt;
&amp;#160; &amp;#160; &amp;#160; &amp;#160; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;ordered_non_unique&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;identity&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;PairCountLexical&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;gt;, &lt;span style=&quot;color: #6ae4b9;&quot;&gt;CompareLexicalOrder&lt;/span&gt;&amp;lt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;&amp;gt;&amp;gt;
&amp;#160; &amp;#160; &amp;gt;
&amp;gt;;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Index 0 explanation:
Same as above this gives us fast insert, modify and lookup for the pair frequencies.
&lt;/p&gt;

&lt;p&gt;
Index 1 explanation:
Same as above except the outcome is different because of the implementation of &lt;code&gt;CompareLexicalOrder&lt;/code&gt;.
&lt;/p&gt;
&lt;/div&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a id=&quot;orgecc25d2&quot;&gt;&lt;/a&gt;Optimization of frequency counts&lt;br /&gt;
&lt;div class=&quot;outline-text-6&quot; id=&quot;text-orgecc25d2&quot;&gt;
&lt;p&gt;
When running the code I see that the biggest cost is regenerating the
frequency map each step. For example when churning through wikitext (a
500mb text corpus) it takes the Python code 28 seconds on my Macbook
to count all the pairs.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s work through Brendan Gregg&apos;s impactful optimizations:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Don’t do it.&lt;/li&gt;
&lt;li&gt;Do it, but don’t do it again.&lt;/li&gt;
&lt;li&gt;Do it less.&lt;/li&gt;
&lt;li&gt;Do it later.&lt;/li&gt;
&lt;li&gt;Do it when they’re not looking.&lt;/li&gt;
&lt;li&gt;Do it concurrently.&lt;/li&gt;
&lt;li&gt;Do it more cheaply.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Don&apos;t do it is not an option, we need those updated counts each step. 
Do it but not again is fruitful though. 
&lt;/p&gt;

&lt;p&gt;
The key insight here is that we only need to do a full frequency count
one time. Then we can incrementally update the pair frequencies as we
walk through doing the merge process. Essentially we are removing and
adding a number of pairs on each replacement.
&lt;/p&gt;

&lt;p&gt;
I noticed that the authors of the paper mentioned this too: 
&lt;/p&gt;

&lt;p&gt;
&quot;In practice, we increase efficiency by indexing all pairs, and updating data structures incrementally.&quot;
&lt;/p&gt;

&lt;p&gt;
You can see their incremental update code here:
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/rsennrich/subword-nmt/blob/92d6139d07d30e12735a0af9e7f7f925ebe62c54/subword_nmt/learn_bpe.py#L159&quot;&gt;https://github.com/rsennrich/subword-nmt/blob/92d6139d07d30e12735a0af9e7f7f925ebe62c54/subword_nmt/learn_bpe.py#L159&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
In addition to this optimization they use a pruning technique that
drops frequencies of pairs below some threshold. This makes sense
because the Python max function iterates the whole collection. In my
case our data structures do not, so pruning is probably not worth the
additional complexity. Worth trying maybe?
&lt;/p&gt;

&lt;p&gt;
In any case, for my lexicographical conflict strategy I do implement
this optimization and it is a huge win on performance as shown in the
charts.
&lt;/p&gt;

&lt;p&gt;
Crucially, it is not implemented for the first occurring strategy,
because the current implementation gives now way to easily keep track
of the first occurence of a pair in the input corpus.
&lt;/p&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org3054bba&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org3054bba&quot;&gt;Next steps&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org3054bba&quot;&gt;
&lt;p&gt;
For me the project is at a good point to move on to other things but there are some things I would do next otherwise:
&lt;/p&gt;
&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Port to Zig. Currently I&apos;m using Zig for some other projects and would be interested in the porting experience and how the performance compares.&lt;/li&gt;
&lt;li&gt;Work on different data structures for the input text to support incremental frequency counting for the first strategy.&lt;/li&gt;
&lt;li&gt;Optimization of the encode and decode steps.&lt;/li&gt;
&lt;li&gt;Implement download and conversion of GPT merges like Karpathy does in his gpt4 code.&lt;/li&gt;
&lt;li&gt;Look at implementations of other Tokenization algorithms.&lt;/li&gt;
&lt;li&gt;Optimization by parallel computation. At face value it seems possible to do the merge process on multiple cores using a divide and conquer approach. Edge cases where the sections overlap may be tricky.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-orge16fdc5&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orge16fdc5&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orge16fdc5&quot;&gt;
&lt;p&gt;
I had a lot of pain and a lot of fun working on the code. I highly recommend this kind of process to fully understand the nuances and implementation details required for AI engineering.
&lt;/p&gt;

&lt;p&gt;
As a refresher on modern C++ this was a great project. (I recommend (Tour of C++)[&lt;a href=&quot;https://www.amazon.ca/Tour-C-2nd-Bjarne-Stroustrup/dp/0134997832&quot;&gt;https://www.amazon.ca/Tour-C-2nd-Bjarne-Stroustrup/dp/0134997832&lt;/a&gt;] and &lt;a href=&quot;https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines&quot;&gt;https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Apart from the complexity of CMake I found that using C++ today is a pleasant and safe experience as long as you carefully tread the recommended path.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-org9d17545&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org9d17545&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org9d17545&quot;&gt;
&lt;p&gt;
Karpathy&apos;s youtube
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=zduSFxRajkE&quot;&gt;https://www.youtube.com/watch?v=zduSFxRajkE&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
And his Python code
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/karpathy/minbpe&quot;&gt;https://github.com/karpathy/minbpe&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
If you want to dive into the code or run the benchmarks yourself, you can find the full project on GitHub.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/minbpe-cc&quot;&gt;https://github.com/justinhj/minbpe-cc&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
An early paper on bpe for tokenization is &quot;Neural Machine Translation of Rare Words with Subword Units&quot;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://arxiv.org/pdf/1508.07909&quot;&gt;https://arxiv.org/pdf/1508.07909&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
The original source code from the paper.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/rsennrich/subword-nmt&quot;&gt;https://github.com/rsennrich/subword-nmt&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Thanks for reading!
&lt;/p&gt;

&lt;p&gt;
&amp;copy;2025 Justin Heyes-Jones. All Rights Reserved
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Wed, 30 Jul 2025 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2025/07/30/journey-in-optimizing-a-bpe-tokenizer.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2025/07/30/journey-in-optimizing-a-bpe-tokenizer.html</guid>
        
        <category>ai</category>
        
        <category>cpp</category>
        
        <category>c++</category>
        
        <category>python</category>
        
        <category>optimization</category>
        
        <category>performance</category>
        
        <category>llm</category>
        
        <category>tokenizer</category>
        
        
      </item>
    
      <item>
        <title>The Magic of Lazy Lists</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;

&lt;style&gt;
.img.special {
  width: 600px;
  border:2px solid #fff;
  box-shadow: 6px 6px 2px #ccc;
  -moz-box-shadow: 6px 6px 2px #ccc;
  -webkit-box-shadow: 6px 6px 2px #ccc;
  -khtml-box-shadow: 6px 6px 2px #ccc;
  margin-bottom: 40px;
}
&lt;/style&gt;

&lt;figure&gt;
  &lt;img class=&quot;img special&quot; src=&quot;../../../images/dollar-gill-0V7_N62zZcU-unsplash.jpg&quot; border=&quot;0&quot; alt=&quot;A mysterious book on a table with a glowing globe&quot; width=&quot;600&quot;/&gt;
  &lt;figcaption&gt;
    Photo by &lt;a href=&quot;https://unsplash.com/@dollargill?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;Dollar Gill&lt;/a&gt; on &lt;a href=&quot;https://unsplash.com/s/photos/magic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;Unsplash&lt;/a&gt;
  &lt;figcaption&gt;
&lt;/figure&gt;

&lt;div id=&quot;outline-container-orgb7894ea&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb7894ea&quot;&gt;Introduction&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb7894ea&quot;&gt;
&lt;p&gt;
As the &lt;a href=&quot;https://docs.scala-lang.org/scala3/book/taste-collections.html&quot;&gt;Scala 3 - book&lt;/a&gt; points out, Scala has a rich set of collection
classes. As well as &lt;code&gt;List&lt;/code&gt;, of course, it also has a solid implementation of &lt;code&gt;LazyList&lt;/code&gt;. If you&apos;re not sure what that is, or what is used for, read on and find out, plus even better I will walk through a full implementation of LazyList that can do some magical things.
&lt;/p&gt;

&lt;p&gt;
Scala &lt;code&gt;List&lt;/code&gt; can represent collections of &lt;code&gt;zero or more&lt;/code&gt;, stored as a linked list, with the details of the underlying data structure abstracted away. 
In my video &lt;a href=&quot;https://youtu.be/7A2xuRkCZBg&quot;&gt;NonEmptyLists more or less&lt;/a&gt; I talked about how
you can build a variant of &lt;code&gt;List&lt;/code&gt; that can only be a collection with &lt;code&gt;one or more&lt;/code&gt; items. 
&lt;/p&gt;

&lt;p&gt;
In this video, I will present the theory and practice of building a &lt;code&gt;LazyList&lt;/code&gt; type, that adds the additional capability of controlling &lt;code&gt;when elements are evaluated&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
All the code written in this post, and the accompanying video &lt;a href=&quot;https://youtu.be/laB15gG5bjY&quot;&gt;The Magic of Lazy Lists&lt;/a&gt; can be found in my new educational Scala library &lt;a href=&quot;https://github.com/justinhj/duct/&quot;&gt;Duct&lt;/a&gt;. In order to produce this implementation I studied the code of the 
Scala standard library (both the current version and history versions which are less sophisticated but also easier to read), as well as other implementations
such as that of the ScalaZ Ephemeral list. The resulting code is a combination of these with some of the best parts of both, as well as taking some advantage of Scala 3 features along the way.
&lt;/p&gt;

&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/laB15gG5bjY&quot; title=&quot;YouTube video player&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org283ea86&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org283ea86&quot;&gt;Implementing Lazy Thing&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org283ea86&quot;&gt;
&lt;p&gt;
&lt;code&gt;LazyList&lt;/code&gt; is easier to understand if you have a good grasp of different evaluation models in Scala, so let&apos;s explore that with a custom class called &lt;code&gt;LazyThing&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
With this implementation, LazyThing is just a wrapper of values, with a get function that returns the value. This is what we call eager, or strict evaluation. When I pass 
the expression &lt;code&gt;{println(&quot;evaluated&quot;); 10&lt;/code&gt; is passed into the &lt;code&gt;LazyThing&lt;/code&gt; constructor it is evaluated immediately and stored in the class. Later when the user calls the get method 
we find that we just get the value; nothing is evaluated again.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;get&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;lt&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;({println(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;evaluated&quot;&lt;/span&gt;); &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;})
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;evaluated&lt;/span&gt;
lt.get
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res4: Int = 10&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
When working with a &lt;code&gt;LazyList&lt;/code&gt; we want to be able to populate it with expressions but without having them evaluated until we are ready (what Haskell refers to
as call by need). What else can we use in Scala that only evaluates when we want it to? Functions! If the argument was a function, we could simply
call it when the user calls get, making it lazy.
&lt;/p&gt;

&lt;p&gt;
Now when we create the class nothing is evaluated until we call get, and then it is evaluated every time. This evaluation mode is called &lt;code&gt;always&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; () &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;get&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a()

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;lt&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;(() &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; {println(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;evaluated&quot;&lt;/span&gt;); &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;})

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;scala&amp;gt; lt.get&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;evaluated&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res15: Int = 10&lt;/span&gt;

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;scala&amp;gt; lt.get&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;evaluated&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res16: Int = 10&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The &lt;code&gt;LazyList&lt;/code&gt; structure is not about always evaluation though, it is about &lt;code&gt;lazy&lt;/code&gt; or &lt;code&gt;call by need&lt;/code&gt; evaluation. We want to be able to remember the result 
of evaluated list elements, and never evaluate them again. This &lt;code&gt;memoization&lt;/code&gt; is the next step.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; () &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;var&lt;/span&gt; &lt;span style=&quot;color: #d0bc00;&quot;&gt;evaluated&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;var&lt;/span&gt; &lt;span style=&quot;color: #d0bc00;&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;get&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; evaluated then value
     &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt;
         evaluated &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
         value &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a()

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;lt&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;(() &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; {println(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;evaluated&quot;&lt;/span&gt;); &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;})

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;scala&amp;gt; lt.get&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;evaluated&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res17: Any = ()&lt;/span&gt;

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;scala&amp;gt; lt.get&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res18: Any = 10&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now you can see that the value is evaluated only once and we can retrieve it multiple times. Memoization is good because it saves us from recomputing 
values, but it also means we must be mindful of memory use and hanging on to references to the internal structure of our &lt;code&gt;LazyList&lt;/code&gt; so as not 
to consume memory that is no longer needed.
&lt;/p&gt;

&lt;p&gt;
Two final simplifications using Scala features make this much more succinct. The mechanism of passing an argument as a function executed only on first 
reference is implemented within Scala and known as call by name. Rewriting like below uses that mechanism instead.
&lt;/p&gt;

&lt;p&gt;
Secondly, we can replace the manual memoization code that remembers the evaluated value with &lt;code&gt;lazy val&lt;/code&gt; which does the same thing but, again, is built into the compiler.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #f78fe7;&quot;&gt;lazy&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;get&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;lt&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyThing&lt;/span&gt;({println(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;evaluated&quot;&lt;/span&gt;); &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;})
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;scala&amp;gt; lt.get&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;evaluated&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res24: Int = 10&lt;/span&gt;

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;scala&amp;gt; lt.get&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res25: Int = 10&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;outline-container-org462128a&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org462128a&quot;&gt;Beginning LazyList&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org462128a&quot;&gt;
&lt;p&gt;
Let&apos;s begin by representing the &lt;code&gt;LazyList&lt;/code&gt; as a &lt;code&gt;sealed trait&lt;/code&gt;, which will be the object through which users interact with the collection.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;sealed&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;trait&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;OurLazyList&lt;/span&gt;[+&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;head&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;tail&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;OurLazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;isEmpty&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Boolean&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Of note here is the &lt;code&gt;+A&lt;/code&gt; variance notation. It&apos;s important to know about and understand variance when making libraries in Scala, slightly less
important when writing application code. A short explanation of variance is that it is short for &quot;variance under inheritance&quot;.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s say we have a type &lt;code&gt;Loan&lt;/code&gt; and two other subtypes of Loan, &lt;code&gt;Credit Card&lt;/code&gt; and &lt;code&gt;Amortized Loan&lt;/code&gt;. If you have some function that takes Loan 
and prints the outstanding balance, you would expect through normal rules of inheritance to be able to pass in a Credit card or an amortized 
loan in place of the Loan. You can use a subtype of loan wherever the compiler is expecting a loan. That is what is known as behavioural 
subtyping. 
&lt;/p&gt;

&lt;p&gt;
What variance under inheritance refers to, is what inheritance means when we have some parameterized type such as a collection. If I have a function 
that takes a list of Loans, should it accept a list of subtypes? Credit cards for example. Because the answer to this is, no not always, Scala 
includes variance annotations so that you can choose the variance relationship you want as needed. I&apos;ll come back to this topic in more detail in a later 
video.
&lt;/p&gt;



&lt;p&gt;
&lt;code&gt;LazyList&lt;/code&gt; will have a companion object containing all the static methods that will be used to create and manipulate lazy lists. The first thing 
we need is a representation of empty list. We add that to a new companion object.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;empty&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Nothing&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;head&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;NoSuchElementException&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Cannot get head of empty lazy list&quot;&lt;/span&gt;)
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;tail&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;UnsupportedOperationException&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;No tail of empty lazy list&quot;&lt;/span&gt;)
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;isEmpty&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Lazy list has the type Nothing. Nothing is at the bottom of Scala&apos;s type hierarchy meaning it is the subtype of everything. Now it&apos;s not a useful type
in itself, because you can&apos;t do anything with it, but it is really useful in this context&amp;#x2026; our empty list is a singleton value shared by all lazy 
lists, we only need one. Why does this work? Because of the variance annotation above. We said that a list of subtypes of &lt;code&gt;A&lt;/code&gt; would be acceptable as 
list of &lt;code&gt;A&lt;/code&gt;. 
&lt;/p&gt;

&lt;p&gt;
So now we are able to create lazy lists with nothing in them using &lt;code&gt;LazyList.empty&lt;/code&gt;. The next step is to be able to create lists with elements inside. We will call this the &lt;code&gt;cons&lt;/code&gt; method, 
as it will be used to construct lists one lazy element at a time.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;object LazyList continued:&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;cons&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](hd&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, tl&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #f78fe7;&quot;&gt;lazy&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;head&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; hd
  &lt;span style=&quot;color: #f78fe7;&quot;&gt;lazy&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;tail&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; tl
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;isEmpty&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
With this small amount of code we have a functional (no pun intended) lazy list.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;ll&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.cons({println(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;evaluated!&quot;&lt;/span&gt;);&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;}, &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;nothing is printed yet!&lt;/span&gt;
ll.head
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;evaluated!&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res9: Int = 10&lt;/span&gt;

ll.head
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val res10: Int = 10&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here you can see that constructing the list did not evaluate the value we passed in to be the head of the collection. Once we retrieved the head we got the 
evaluation happen, but subsequently we did not not. Nice.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org06dcc57&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org06dcc57&quot;&gt;Pattern matching and the &quot;cons operator&quot;&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org06dcc57&quot;&gt;
&lt;p&gt;
In Scala you can construct lists using the so-called &lt;code&gt;cons&lt;/code&gt; operator &lt;code&gt;::&lt;/code&gt;. For example:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt; :: &lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt; :: &lt;span style=&quot;color: #00bcff;&quot;&gt;3&lt;/span&gt; :: &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;.empty
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Creates a List[Int] = List(1, 2, 3)&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This is convenient so Scala&apos;s standard &lt;code&gt;LazyList&lt;/code&gt; also implements this using the syntax &lt;code&gt;#::&lt;/code&gt;. Let&apos;s do the same for Duct. There are two things to note here:
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;To make this work we want #:: to be a right associative function that &lt;code&gt;cons&lt;/code&gt;&apos;s a new head for the list to the tail which is to the right&lt;/li&gt;
&lt;li&gt;The type of the operation should be a cons operation on a list.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
To append &lt;code&gt;1&lt;/code&gt; to the list &lt;code&gt;val ll = (2,3)&lt;/code&gt; we need to write &lt;code&gt;1 #:: ll&lt;/code&gt; and we want the compiler to evaluate this as:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;ll.#::(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;where the type of LL is LazyList[Int]&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that in Scala, by convention, anything ending in a colon is right associative, which is what we want here. Also not that in Scala 3 we can write this as an extension method. In the standard library you&apos;ll see code like the following:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;toDeferrer&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Deferrer&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Deferrer&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](() &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; l)

&lt;span style=&quot;color: #f78fe7;&quot;&gt;final&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Deferrer&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #f78fe7;&quot;&gt;private&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;] (&lt;span style=&quot;color: #f78fe7;&quot;&gt;private&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; () &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;AnyVal&lt;/span&gt; {
  &lt;span style=&quot;color: #b0d6f5;&quot;&gt;/** Construct a LazyList consisting of a given first element followed by elements&lt;/span&gt;
&lt;span style=&quot;color: #b0d6f5;&quot;&gt;    *  from another LazyList.&lt;/span&gt;
&lt;span style=&quot;color: #b0d6f5;&quot;&gt;    */&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;#::&lt;/span&gt; [&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;&amp;gt;:&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](elem&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; newLL(sCons(elem, newLL(l().state)))
  &lt;span style=&quot;color: #b0d6f5;&quot;&gt;/** Construct a LazyList consisting of the concatenation of the given LazyList and&lt;/span&gt;
&lt;span style=&quot;color: #b0d6f5;&quot;&gt;    *  another LazyList.&lt;/span&gt;
&lt;span style=&quot;color: #b0d6f5;&quot;&gt;    */&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;#:::&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;&amp;gt;:&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](prefix&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; prefix lazyAppendedAll l()
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/scala/scala/blob/39148e4ec34a5c53443dd1b25ceec2308cd097fe/src/library/scala/collection/immutable/LazyList.scala#L1136&quot;&gt;scala.collection.immutable.LazyList.scala&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
With Scala 3 we can simply implement this as an extension method on the &lt;code&gt;LazyList&lt;/code&gt; trait. Much nicer.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;extension [&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](hd&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;#::&lt;/span&gt;(tl&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; 
   &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.cons(hd, tl)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now we can create lazy lists more easily as follows:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;ll&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt; #:: &lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt; #:: &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;val ll: LazyList[Int] = LazyList$$anon$2@687292c5&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Creating a lazy list with the cons operators is one thing but users will expect to be able to deconstruct lists in a pattern match expression to. Let&apos;s add that functionality next.
&lt;/p&gt;

&lt;p&gt;
In Scala you implement pattern matching on a particular type by implementing &lt;code&gt;unapply&lt;/code&gt; on an object with that types name, in our case &lt;code&gt;#::&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;#::&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;unapply&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Option&lt;/span&gt;[(&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
        &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; !s.isEmpty then &lt;span style=&quot;color: #00bcff;&quot;&gt;Some&lt;/span&gt;((s.head, s.tail)) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The way unapply works is the opposite of a constructor. Given a constructed type, unapply tries to extract the pieces. This is a partial function, it does not have to succeed, so it returns the pieces as an Option.
&lt;/p&gt;

&lt;p&gt;
Now we can write lazy code using pattern matching:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;ourMap&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](ll&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  ll &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;hd&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;#::&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;tl&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
      &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.cons(f(hd), ourMap(tl, f))
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
      &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty
  }
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org026cfab&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org026cfab&quot;&gt;Iterating over Lazy List&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org026cfab&quot;&gt;
&lt;p&gt;
Note that although the destructuring (pattern matching) of lazy lists is often useful, in my final implementation for the Duct library I opted for the following more simple approach to the map function, shared here because I implemented many of the functions that iterate over lazy lists in the following way:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;map&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; isEmpty then &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.cons(f(head), tail.map(f))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Another useful function is &lt;code&gt;forEach&lt;/code&gt;, which you can use to execute some action across the lazy list. This function highlights a couple of interesting things.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;When working with laziness always consider when you want preserve it versus lose it. The forEach function by definition must visit every element of the list and therefore does not preserve laziness.&lt;/li&gt;
&lt;li&gt;If possible you should make recursive functions tail recursive, otherwise they are limited by the stack. This implementation is tail recursive. We can tell the compiler to make sure that it is with the annoation.&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #ff9077;&quot;&gt;@tailrec&lt;/span&gt;
&lt;span style=&quot;color: #f78fe7;&quot;&gt;final&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;forEach&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Unit&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Unit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; !isEmpty then
    f(head)
    tail.forEach(f)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
And you can use it as follows. Note that I&apos;m using the &lt;a href=&quot;https://github.com/justinhj/duct/blob/2ebe7e3ea25edf4c668ca6e044959396ae3cb265/core/src/main/scala/org/justinhj/duct/datatypes/LazyList.scala#L123&quot;&gt;LazyList.apply&lt;/a&gt; method here is a convenience to create a lazy list from a variable argument list.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;list1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;3&lt;/span&gt;)

println(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;forEach list1&quot;&lt;/span&gt;)
list1.forEach { a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
  println(a)
}

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;forEach list1&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;1&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;2&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;3&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org21af617&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org21af617&quot;&gt;Filtering&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org21af617&quot;&gt;
&lt;p&gt;
Another part of the implementation worth looking at is dropping elements that pass or fail some filter, namely &lt;code&gt;filter&lt;/code&gt; and &lt;code&gt;dropWhile&lt;/code&gt;. Let&apos;s first think about what the semantics are here in terms of laziness.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Given a lazy list and a filter function we want the user to be able to iterate through them &lt;code&gt;by need&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When the user calls head on a lazy list where many elements fail the filter before a good one comes, many elements are evaluated.&lt;/li&gt;
&lt;li&gt;We must stop evaluating the elements as soon as we find one that passes the filter, and return that as a lazy list to the caller.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
We have to be careful about laziness then. Let&apos;s first think about &lt;code&gt;dropWhile&lt;/code&gt;. This takes lazy list with all the failing elements dropped.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #ff9077;&quot;&gt;@tailrec&lt;/span&gt;
&lt;span style=&quot;color: #f78fe7;&quot;&gt;final&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;dropWhile&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Boolean&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; isEmpty then &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; f(head) then tail.dropWhile(f)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;this&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now since we want this to work on many elements potentially, it is important to be tail recursive. With &lt;code&gt;dropWhile&lt;/code&gt; we can take list such as &lt;code&gt;LazyList(1,2,3,4,5)&lt;/code&gt; and drop all elements less than 3. What we get back is LazyList beginning with 3.
&lt;/p&gt;

&lt;p&gt;
Take a moment to think about which elements have been evaluated at this point.
&lt;/p&gt;

&lt;p&gt;
Whether you reason about it by looking at the code or thinking about it semantically, the answer is that the 3 is evaluated and the &lt;code&gt;4,5&lt;/code&gt; elements are in a lazy tail. &lt;code&gt;dropWhile&lt;/code&gt; then will evaluate elements &lt;code&gt;up to and including the first one that should not be dropped&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Once you implement &lt;code&gt;dropWhile&lt;/code&gt; it can be used to implement &lt;code&gt;filter&lt;/code&gt; with the requirements we came up with above.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;filter&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Boolean&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;dropped&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;this&lt;/span&gt;.dropWhile(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; !f(a))
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; dropped.isEmpty then &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.cons(dropped.head, dropped.tail.filter(f))    
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org2f8dc3f&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org2f8dc3f&quot;&gt;Infinite lists&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org2f8dc3f&quot;&gt;
&lt;p&gt;
Quite a few years ago I was working through a Haskell tutorial for beginners. Some of the examples worked with infinite lists; mapping them, filtering them, and zipping them together. At the time my knowledge of evaluation and laziness was 
not sophisticated. As they say, any sufficiently advanced technology is indistinguishable from magic. Since Haskell was doing things more advanced than I understood at the time, I thought of infinite lists as being a magic trick.
&lt;/p&gt;

&lt;p&gt;
As you&apos;ve seen so far, I hope, the mechanisms of lazy evaluation make working with infinite lists possible and don&apos;t require a lot of work. Let&apos;s look at how what we&apos;ve done so far scales effortlessly from small lists to infinite ones.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;repeat&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a #:: repeat(a)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;from&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; n #:: from(n+&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;iterate&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;)(next&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a #:: iterate(next(a))(next)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note how these functions build on what we did so far, and give us ways to declaratively create infinite lists.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;repeat&lt;/code&gt; provides a lazy list with a head of type &lt;code&gt;A&lt;/code&gt;. When the use takes the tail they get the same thing and so on forever. This gives us a definition of an infinitely repeating constant.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;from&lt;/code&gt; shows how we can incrementally generate numbers from some starting value n. Note that the tail is a function that takes input from the previous call; in this way we can pass information through an infinite chain of computation!
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;iterate&lt;/code&gt; is a generalisation of this allowing you to take some function that creates a new A from the previous one, forever.
&lt;/p&gt;

&lt;p&gt;
Of course, we don&apos;t want to actually evaluate infinite lists because we don&apos;t have time for that, so you would use &lt;a href=&quot;https://github.com/justinhj/duct/blob/2ebe7e3ea25edf4c668ca6e044959396ae3cb265/core/src/main/scala/org/justinhj/duct/datatypes/LazyList.scala#L57&quot;&gt;take&lt;/a&gt; and drop and other filtering mechanisms to work with only the values you are interested in. As we will see, there are times when you don&apos;t know how many of a thing you need and it may be expensive to generate them, so &lt;code&gt;call by need&lt;/code&gt; evaluation is what we want.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orga762366&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga762366&quot;&gt;Fusion of operations&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga762366&quot;&gt;
&lt;p&gt;
Imagine the following code.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;lotsOfThings&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;.fill(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)(&lt;span style=&quot;color: #00bcff;&quot;&gt;10000000&lt;/span&gt;)
lotsOfThings.map(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; expensiveCalculation(a)).filter(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a &amp;lt; &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;).map(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; expensiveCalculation2(a)).take(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;).sum
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
With a strictly evaluated list what happens here?
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;&lt;code&gt;map&lt;/code&gt; will iterate over the large list, doing expensiveCalculation 10m times and making a new list of 10m elements.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;filter&lt;/code&gt; will walk that new list and create a new list with up to 10m elements that pass the filter.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;map&lt;/code&gt; will take those elements and create a new list after calling expensiveCalculation2 on each element&lt;/li&gt;
&lt;li&gt;&lt;code&gt;take&lt;/code&gt; will drop all elements after the 10th one&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sum&lt;/code&gt; iterates over the elements&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Whilst this kind of code is not typical, you are hopefully not working with lists this big, but if the use case requires it, then lazy lists provide a &lt;code&gt;potentially&lt;/code&gt; much more efficient way of working.
&lt;/p&gt;

&lt;p&gt;
The same code as a lazy list would work this way.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li value=&quot;1&quot;&gt;&lt;code&gt;map&lt;/code&gt; takes the large list and returns a lazy list where, when evaluated, head will have expensiveCalculation applied to it. This is O(1).&lt;/li&gt;
&lt;li value=&quot;2&quot;&gt;&lt;code&gt;filter&lt;/code&gt; will internally call &lt;code&gt;dropWhile&lt;/code&gt;. Let&apos;s pretend the filter is true because a &amp;lt; 10 and we return a new lazy list with the filter but paused at the first element.&lt;/li&gt;
&lt;li value=&quot;3&quot;&gt;&lt;code&gt;map&lt;/code&gt; will take that list and again, return a new lazy list that is unevaluated and ready to run expensiveCalculation2 if anyone asks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Observation&amp;#x2026; we are turning our list of values into a &lt;code&gt;list of delayed computations&lt;/code&gt;. This takes up more memory than a list of values because each step is wrapped in a Function object.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li value=&quot;4&quot;&gt;&lt;code&gt;take&lt;/code&gt; will now return a lazy list that keeps track of a counter and stops (returns an empty tail) when it runs out, so we set a bound on our computation.&lt;/li&gt;
&lt;li value=&quot;5&quot;&gt;&lt;code&gt;sum&lt;/code&gt; okay now we&apos;re going to do a bit more work. sum calls &lt;code&gt;foldLeft&lt;/code&gt; (see below), which by definition must evaluate all the items and combine them to a single result&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #ff9077;&quot;&gt;@tailrec&lt;/span&gt;
&lt;span style=&quot;color: #f78fe7;&quot;&gt;final&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;foldLeft&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](z&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt;)(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; isEmpty then z
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; tail.foldLeft(f(z, head))(f)
&lt;/pre&gt;
&lt;/div&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li value=&quot;6&quot;&gt;Now more serious evaluation will happen. What we have at this point is a sort of stack of computations for each successive element. We will call expensiveCalculation1 and expensiveCalculation2 &lt;code&gt;only as often as needed&lt;/code&gt; to evaluate the 10 elements.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
This is all rather hard to conceptualize, so here&apos;s a picture that may help. The call stack shown in the middle of the &lt;code&gt;foldLeft&lt;/code&gt; shows that the lazy list we evaluate consists of a stack of function calls that are waiting to happen.
&lt;/p&gt;

&lt;img class=&quot;img&quot; src=&quot;../../../images/nestedlazylist.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;A callstack snapshot&quot; width=&quot;600&quot;/&gt;

&lt;p&gt;
Fusion of operations means that a sequence of complex, expensive operations, can be limited to only the number of elements you are interested in and performed per element, not across the whole collection. This is the essence of being able to control evaluation for your own needs.
&lt;/p&gt;

&lt;p&gt;
This gives us some insight on when to use a lazy list (or equivalent structures such as streams, iterators), rather than concrete immutable containers.
&lt;/p&gt;

&lt;p&gt;
Use lazy lists when you need to execute an expensive sequence of operations and you don&apos;t expect to consume the majority of the collection.
&lt;/p&gt;

&lt;p&gt;
You need to use some discretion here. If you can&apos;t guarantee that the whole list won&apos;t be executed, it&apos;s probably not a good use case. But this technique translates well to a computation where we never see the whole list (streaming applications that work with Kafka and Kinesis for example).
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgf4d244e&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgf4d244e&quot;&gt;Laziness for convenience&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgf4d244e&quot;&gt;
&lt;p&gt;
Some algorithms require you to provide a list of things but you don&apos;t know how many things you need in advance. Here&apos;s an example that appears in the paper &lt;a href=&quot;https://www.staff.city.ac.uk/~ross/papers/Applicative.html&quot;&gt;Applicative Programming with Effects&lt;/a&gt; that transposes a matrix.
&lt;/p&gt;

&lt;p&gt;
You can see this code also in my post about the paper at &lt;a href=&quot;./2020/04/04/whats-ap.html&quot;&gt;What&apos;s Ap?&lt;/a&gt;, although the coverage there is more about how this operation can be written in &quot;the applicative style&quot;.
&lt;/p&gt;

&lt;p&gt;
First, let&apos;s represent a 2-dimensional matrix as a lazy list of lazy lists.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;matrix&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;11&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;12&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;13&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;14&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;15&lt;/span&gt;),
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;21&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;22&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;23&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;24&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;25&lt;/span&gt;),
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;31&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;32&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;33&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;34&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;35&lt;/span&gt;)
)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The idea of transposing a matrix is you &quot;rotate&quot; it such that if you started with n rows and m columns, you would end up with a rotated matrix with m rows and n columns.
&lt;/p&gt;

&lt;p&gt;
Rotated by hand and represented in code, this 3 by 5 matrix should be transposed to the following.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;matrix&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;11&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;21&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;31&lt;/span&gt;),
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;12&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;22&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;32&lt;/span&gt;),
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;13&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;23&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;33&lt;/span&gt;),
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;14&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;24&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;34&lt;/span&gt;),
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;15&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;25&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;35&lt;/span&gt;)
)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
In order to implement this a nicely functional, declarative way, we first need a helper function &lt;code&gt;zipWith&lt;/code&gt; that takes two empty lists and lets us combine them with a function.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;zipWith&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;](as&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], bs&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;])
  (f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; as.zip(bs).map { &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;, &lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; f(a, b) }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
An important property of zip is that given two lists it combines them together into a new list of tuples, the length of which is bounded by the shortest one. This means we can combine zip and lazy lists to 
zip together two lists, one of which is infinite and the other is bounded. That&apos;s the technique used here.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;transpose&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](
    matrix&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; matrix.isEmpty then &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.repeat(&lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.empty) then
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; zipWith(matrix.head, transpose(matrix.tail))(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; #:: &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Is it easy to understand? No, it takes a bit of thinking about to understand what is going on (as an exercise I&apos;d suggest adding some println to see how it works). What&apos;s more 
interesting though, is that this is a much more functional, declarative version of matrix transpose. Imagine writing this in Go and you will do it as a for loop, taking care not to 
make any mistakes. Even though matrix transpose is simple, functional programming &lt;code&gt;scales up&lt;/code&gt; to bigger more complex programs, whereas the imperative version is more 
of a one-off implementation.
&lt;/p&gt;

&lt;p&gt;
The &quot;trick&quot; in the code above is in the &lt;code&gt;LazyList.repeat&lt;/code&gt;. The iteration of the transpose works along each row of the matrix producing the new columns with cons, but at some point it runs out of rows and it needs another row of empty lists to finish the new rows off. How many empty lists does it need? Well, we could work it out by counting, but why not just say 
here is an infinite number, and let the zip figure out when to stop?
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org946c355&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org946c355&quot;&gt;Folding left and right&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org946c355&quot;&gt;
&lt;p&gt;
There are a couple of interesting things to say about folding lazy lists. Firstly let&apos;s look at stack safety.
&lt;/p&gt;

&lt;p&gt;
As we saw earlier the amount of memory used by a lazy list can be
higher than with a regular list since with fusion between operations
we can end up with a stack of function objects before it is
evaluated. For that reason and just in general we may want to operate
on large lists, it&apos;s important to consider which operations are stack
safe and which are not.
&lt;/p&gt;

&lt;p&gt;
For a stack safe function I present &lt;code&gt;foldLeft&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #ff9077;&quot;&gt;@tailrec&lt;/span&gt;
&lt;span style=&quot;color: #f78fe7;&quot;&gt;final&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;foldLeft&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](z&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt;)(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; isEmpty then z
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; tail.foldLeft(f(z, head))(f)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This is a so-called aggregate function that takes a collection, in this case, iterates over it and produces some aggregate value. The supplied function
from the user is applied to each element along with some accumulating value. In the case of this implementation, the foldLeft recursive call is in &lt;code&gt;tail position&lt;/code&gt; 
which means we can assume it uses tail call optimization. We add the annotation to tell the compiler we think so, and it will both complain if it is not eligible.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;incN&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;, inc&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.cons(n, incN(n + inc, inc))

println(
  incN(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;).take(&lt;span style=&quot;color: #00bcff;&quot;&gt;10000000&lt;/span&gt;).foldLeft(&lt;span style=&quot;color: #00bcff;&quot;&gt;BigInt&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;)) { &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;acc&lt;/span&gt;, &lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; acc + a }
)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This function adds up 10m integers and as such takes up a lot of stack space and crashes. Except it doesn&apos;t! Why? Because of the tail call optimization.
&lt;/p&gt;

&lt;p&gt;
Now it will, in fact, take a good few seconds on modern hardware, which is a long time, and it may in fact crash with out of memory or be pathologically slow. Why? Because we are creating a lot of garbage here, in the order of gigabytes, and that takes a lot of work to clear up.
&lt;/p&gt;

&lt;p&gt;
Make sure you have a decent amount of heap and use the G1 garbage collector via these settings (this is for running sbt, you can set the same JAVA&lt;sub&gt;OPTS&lt;/sub&gt; for IDE&apos;s and so on).
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-bash&quot;&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;SBT_OPTS&lt;/span&gt;=&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;-XX:+UseG1GC -Xmx4G&quot;&lt;/span&gt; sbt
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
So foldLeft is stack safe, how about foldRight?
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;foldRight&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](z&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; isEmpty then z
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; f(head, tail.foldRight(z)(f))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that the problem here is that the recursive call is not a tail
call position, in this case, the user function &lt;code&gt;f&lt;/code&gt; is. That means we
can&apos;t use the tailrec annotation and it will not be tail call
optimized.
&lt;/p&gt;

&lt;p&gt;
Can we infer from this situation that &lt;code&gt;foldRight&lt;/code&gt; is useless? No actually. It has a property that foldLeft does not, that of being able to &lt;code&gt;terminate early&lt;/code&gt;. Just like with fusion of operations, 
the early termination of &lt;code&gt;foldRight&lt;/code&gt; can be used to save us work, and make code more efficient.
&lt;/p&gt;

&lt;p&gt;
How does that work? The &quot;trick&quot; here is that the second argument of the user function, the accumulator, is a call by-name value. It&apos;s lazy! That means we don&apos;t have to evaluate it.
&lt;/p&gt;

&lt;p&gt;
This example code uses &lt;code&gt;foldRight&lt;/code&gt; to find &quot;tuna&quot; in a list of fish. 
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;hasTuna&lt;/span&gt;(ll&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;LazyList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Boolean&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  ll.foldRight(&lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;){
    (next, z) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
      println(next)
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; next == &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;tuna&quot;&lt;/span&gt; then
        &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt;
        z
  }

hasTuna(&lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;salmon&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;shark&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;tuna&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;moray&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;goldfish&quot;&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;eel&quot;&lt;/span&gt;))
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;prints:&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;//   &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;salmon&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;//   &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;shark&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;//   &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;tuna&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This is simply not possible with foldLeft, nor is it possible if you don&apos;t use a call by-name argument for the accumulator in foldRight. If you&apos;re not sure why it is not possible for 
foldLeft, try putting some println statements into things that you foldLeft and foldRight and see the order in which things are done.
&lt;/p&gt;

&lt;p&gt;
By the way, if you try this with the standard library you&apos;ll find it does not work the same way. The signature of foldRight is as follows:
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;foldRight&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](z&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt;)(op&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Without even trying it we know that it must expand the whole collection, although feel free to try it if you need to prove it to yourself. There has been some
discussion on this, for example. 
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://stackoverflow.com/questions/7830471/foldright-on-infinite-lazy-structure&quot;&gt;https://stackoverflow.com/questions/7830471/foldright-on-infinite-lazy-structure&lt;/a&gt;
&lt;a href=&quot;http://voidmainargs.blogspot.com/2011/08/folding-stream-with-scala.html&quot;&gt;http://voidmainargs.blogspot.com/2011/08/folding-stream-with-scala.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
As noted in the second example the following code will work with a lazy aware foldRight only.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #00bcff;&quot;&gt;LazyList&lt;/span&gt;.repeat(&lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;).foldRight(&lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;){&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; || &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;}
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orge975925&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orge975925&quot;&gt;Last words&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orge975925&quot;&gt;
&lt;p&gt;
Maybe LazyList is not something you will use very often but I think some of the ideas here are central to functional programming. When you are working 
with streaming libraries like fs2, or effect libraries like Zio, this idea of building up some structure first, then evaluating it, is very powerful, and understanding 
lazy lists in some depth will hopefully help your way of thinking in your day to day Scala code!
&lt;/p&gt;

&lt;p&gt;
Thanks for reading, if you enjoyed this content please share with a friend. If not, drop me a note and tell me what I can do better next time.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org9f10093&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org9f10093&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org9f10093&quot;&gt;
&lt;p&gt;
Functional Programming in Scala (aka the red book) - has a great chapter on lazy lists
&lt;a href=&quot;https://www.manning.com/books/functional-programming-in-scala&quot;&gt;Functional Programming in Scala - Manning Press&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
LazyList Scala standard library 2.13 - modern day production ready code
&lt;a href=&quot;https://www.scala-lang.org/api/2.13.x/scala/collection/immutable/LazyList.html&quot;&gt;https://www.scala-lang.org/api/2.13.x/scala/collection/immutable/LazyList.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Stream from Scala standard library 2.7 - older and simpler version which I found easier to understand
&lt;a href=&quot;https://github.com/scala/scala/blob/v2.7.7/src/library/scala/Stream.scala&quot;&gt;https://github.com/scala/scala/blob/v2.7.7/src/library/scala/Stream.scala&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Scalaz Ephemeral Stream - did some things I liked too
&lt;a href=&quot;https://github.com/scalaz/scalaz/blob/ea81ca782a634d4cd93c56529c082567a207c9f6/core/src/main/scala/scalaz/EphemeralStream.scala&quot;&gt;https://github.com/scalaz/scalaz/blob/ea81ca782a634d4cd93c56529c082567a207c9f6/core/src/main/scala/scalaz/EphemeralStream.scala&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
All of the code for the Lazy List class can be found in the Duct library here
&lt;a href=&quot;https://github.com/justinhj/duct/blob/video17/core/src/main/scala/org/justinhj/duct/datatypes/LazyList.scala&quot;&gt;https://github.com/justinhj/duct/blob/video17/core/src/main/scala/org/justinhj/duct/datatypes/LazyList.scala&lt;/a&gt;
If you dig around in the code, or find in files for LazyList, you will see there is also a test suite and a few examples.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Sat, 05 Nov 2022 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2022/11/05/magic-of-lazy-lists.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2022/11/05/magic-of-lazy-lists.html</guid>
        
        <category>pure-functional-programming</category>
        
        <category>cats</category>
        
        <category>scala</category>
        
        <category>applicative</category>
        
        <category>monads</category>
        
        <category>comonads</category>
        
        <category>kleisli</category>
        
        <category>zio</category>
        
        <category>popular</category>
        
        
      </item>
    
      <item>
        <title>Monad Transformers - the prelude to ZPure</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;

&lt;div style=&quot;padding: 30px;&quot;&gt;
  &lt;img class=&quot;img&quot; src=&quot;../../../images/monadtransformers.png&quot; border=&quot;1&quot; alt=&quot;Diagram of monad transformers with the ZPure type&quot; width=&quot;600&quot;/&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orga6db714&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga6db714&quot;&gt;Readers and Writers and Transformers&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga6db714&quot;&gt;
&lt;p&gt;
BTW you can check out the video here instead: 
&lt;a href=&quot;https://youtu.be/tEnZZlOn-jI&quot;&gt;Functional Justin - Another Angle on Monad Transformers&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
There are twenty pages here or over an hour of videos, so let me help you decide if it&apos;s worth your time.
&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org9365b75&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org9365b75&quot;&gt;Who are you?&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org9365b75&quot;&gt;
&lt;p&gt;
You are a Scala programmer or interested in Scala and may have some Haskell or interest in pure functional programming.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org027dc19&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org027dc19&quot;&gt;What do I cover?&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org027dc19&quot;&gt;
&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;Introduction to Monad transformers&lt;/li&gt;
&lt;li&gt;Implement the WriterT monad in Scala 3 from scratch and used in a program&lt;/li&gt;
&lt;li&gt;Implement the ReaderT monad in Scala 3, also from scratch, and use it&lt;/li&gt;
&lt;li&gt;Why not both? Stack the Reader and Writer monads on top of each other&lt;/li&gt;
&lt;li&gt;Effect rotation and ZIO Prelude&apos;s ZPure, another approach to combining effects&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org5369a1f&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org5369a1f&quot;&gt;Evaluating expressions&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org5369a1f&quot;&gt;
&lt;p&gt;
In previous blogs and videos, I&apos;ve described a program that evaluates
arithmetic expressions as this is a nice testbed for various
functional effects. So far I&apos;ve demonstrated how by using different
data types and type classes one can make the same program behave
differently.
&lt;/p&gt;

&lt;p&gt;
This is important for a couple of reasons. It means that you can
compose interesting programs from smaller, well-understood components,
and because we can understand and change the behaviour of our program
by using different types.
&lt;/p&gt;

&lt;p&gt;
As a starting point, lets begin with a version of the program that has
error handling using the Either data type and Numeric which is a
generic implementation of numbers.
&lt;/p&gt;

&lt;p&gt;
If you didn&apos;t catch up on earlier posts let&apos;s recap. An example run of
the program requires an environment (symbol table) provided using the
Scala 3 implicit mechanism (using the given keyword). I call eval on a
sample expression tree which yields either a Right or a Left result
since I&apos;m using Either as the result effect type.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;  given envMap&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;7&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;6&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;22&lt;/span&gt;)

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;exp1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Sub&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt;))))

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;eval1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(exp1)

  println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Eval exp gives &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$eval1&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;[info] running Scala3EvalEither &lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Eval exp gives Right(242)&lt;/span&gt;

&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
I represent the errors as a Scala 3 enum which is a nice way to create
ADT&apos;s (algebraic data types), similar to how you would do it in Rust.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;InvalidSymboName&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;DivisionByZero&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The next things to look at are an ADT to represent the program steps a return type.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;
enum &lt;span style=&quot;color: #00bcff;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], &lt;span style=&quot;color: #00d3d0;&quot;&gt;right&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Sub&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], &lt;span style=&quot;color: #00d3d0;&quot;&gt;right&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], &lt;span style=&quot;color: #00d3d0;&quot;&gt;right&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Div&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], &lt;span style=&quot;color: #00d3d0;&quot;&gt;right&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;identifier&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;import&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Exp&lt;/span&gt;.&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The &lt;code&gt;Env&lt;/code&gt; type is a simple map for strings to values that we will use
as a symbol table so that variables can be looked up at runtime. The
&lt;code&gt;?-&amp;gt;&lt;/code&gt; syntax indicates that the return type is a context function. An
earlier blog discusses that, but in short, it allows us to thread our
Env symbol table through the computation easily.
&lt;/p&gt;

&lt;p&gt;
Here is the main body of the code.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;eval&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](exp&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  exp &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt;
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;id&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleVar(id)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleAdd(l,r)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Sub&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleSub(l,r)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Div&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleDiv(l,r)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleMul(l,r)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleAdd&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] , r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] )&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) + eval(r)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleSub&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] , r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] )&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) - eval(r)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleMul&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] , r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] )&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) * eval(r)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleDiv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] , r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] )&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) / eval(r)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  summonEnv.get(s) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;.&lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;)
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Those arithmetic operators you see are operating not on integers,
doubles or some other concrete type, but are working on a type A that
has a Numeric instance. You may wonder then how that &lt;code&gt;+&lt;/code&gt; operator
knows what to do? The answer is that I implemented an instance of
Numeric for the type &lt;code&gt;Numeric[Either[EvalError,A]]&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Implement Numeric for EvalResult&lt;/span&gt;
given evalResultNumeric[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt; {

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], fb&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    fa.map2(fb)((a,b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + b)
  }
  &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;... and so on&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Whilst this is a lot of overhead for a simple program, as your
programs scale in complexity, this level of abstraction lets you
control effects as well as swap them in and out as your requirements
change without having to rewrite the core logic.
&lt;/p&gt;

&lt;p&gt;
As an example, let&apos;s introduce a Monad Transformer and show how to
integrate it with the program above.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org1d9e441&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org1d9e441&quot;&gt;WriterT&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org1d9e441&quot;&gt;
&lt;p&gt;
Let&apos;s say we want to take an existing effectful program and add a new
effect to it. The effect I will demonstrate is logging. There is a
data type called Writer which represents a value and a log. 
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #00bcff;&quot;&gt;Writer&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](run&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This is not very interesting on its own but if you make a program from
Writers, sequencing them together using the Monad&apos;s flatMap operation
for example, then the end result consists of a final value and a log
for &lt;code&gt;each step of the program&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
But since I already committed to using Either, if I change the type to
Writer then I would lose the ability to handle errors. Instead what I
want is to keep the Either effect and &lt;code&gt;wrap&lt;/code&gt; it with the capability of
the Writer monad.
&lt;/p&gt;

&lt;p&gt;
Monad transformers are the answer. Now the trouble with monads is that
they don&apos;t compose manually together. As I covered in a previous blog,
applicatives do. You can take any two applicative effects such as
Either and List and compose them with simple functions. 
&lt;/p&gt;

&lt;p&gt;
With Monads the composition of any particular monad has to be
hand-crafted, so if I want to stack a Reader on top of an Either,
which I do, then I need to implement a ReaderT (reader transformer).
&lt;/p&gt;

&lt;p&gt;
It only needs to be implemented once and for all and can then be applied
to any other Monad (not just for Either). The idea is to make an
implementation of Reader that wraps another Monadic data type.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](&lt;span style=&quot;color: #f78fe7;&quot;&gt;private&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;wrapped&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[(&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;)])
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here you can see the definition of the WriterT data type. The
difference between WriterT and Writer is that the WriterT wraps an
existing monad. Note that there is no need to constrain the
higher-kinded type F to be a Monad, but later on when we use it in
various ways it is possible to constrain F to be a Functor,
Applicative or Monad depending on the use-case. Choosing the type
bounds that constrain what the wrapped type must support based on the
individual functions needs gives you more flexibility.
&lt;/p&gt;

&lt;p&gt;
For example, if you have a data type that has a map operation but no
meaningful way to make a flatMap, you can still use the Monad
transformer as long as you only use Functor level methods.
&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org24d8b6c&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org24d8b6c&quot;&gt;Lifting&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org24d8b6c&quot;&gt;
&lt;p&gt;
To use WriterT there needs to be a mechanism to take your inner data
type (Either in this case) and make an instance of WriterT.  That can
be done like this in my implementation by using the WriterT
constructor. For example let&apos;s say we have an Either instance we can
transform it to a WriterT like this.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;w1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;(e1.map(n &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;.empty[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;], n)))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
It&apos;s not straightforward because the WriterT wrapped type must be
&lt;code&gt;F[(W,A)]&lt;/code&gt; and we had an F[A]. That is why I need to use the map
operation to take any value the Either may have and combine it with an
empty log. Here we assume the log is a list of strings and Scala is
able to infer that too.
&lt;/p&gt;

&lt;p&gt;
Since this needed often the lift method is often added which takes
care of creating an empty log message and mapping it for us.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;lift&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])(using m&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monoid&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Functor&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
    &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;.map(fa)(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; (m.zero, a)))

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;... &lt;/span&gt;

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;w1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; 
    &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;.lift(e1)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Couple of interesting things to note about the lift method type
signature. For one you can see that the log must be a Monoid. A Monoid
is a type that must have two useful operations that make it useful for
logs: It must be able to produce an empty element of whatever type it
is specialized for, and it must be able to join that type together.
&lt;/p&gt;

&lt;p&gt;
This gives the user the flexibility to use any data type for the log
and not have to worry about providing an empty log or an append
function. The example here is a monoid since it is a list of
strings. Obviously we can produce an empty list, and the append
function is also trivial, so if you look at my Monoid instance for
lists you can see the implementation is trivial.
&lt;/p&gt;

&lt;p&gt;
Another interesting thing is the Functor type constraint. As I
mentioned above, although we call them Monad transformers, they can be
used with Functors, Applicatives and Monads. Since the lift function
only needs map, it needs only the Functor type constraint.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org3132388&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org3132388&quot;&gt;Evaluating expressions with a log&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org3132388&quot;&gt;
&lt;p&gt;
Now I&apos;ll walk through the changes needed to convert the expression
evaluator from having the return type Either, to being one of
WriterT[Either]
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Without log&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;With log&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The next step is to make small changes to my programs implementation
to manage this new type. As you can see, the simplest change, handling
a basic numeric value, just involves lifting our original Either and
adding a log entry.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span class=&quot;linenr&quot;&gt;1: &lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;eval&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](exp&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
&lt;span class=&quot;linenr&quot;&gt;2: &lt;/span&gt;  exp &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt;
&lt;span class=&quot;linenr&quot;&gt;3: &lt;/span&gt;    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;id&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleVar(id)
&lt;span class=&quot;linenr&quot;&gt;4: &lt;/span&gt;    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;.lift[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](&lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value)).tell(&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Val &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$value&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;))
&lt;span class=&quot;linenr&quot;&gt;5: &lt;/span&gt;    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleAdd(l,r)
&lt;span class=&quot;linenr&quot;&gt;6: &lt;/span&gt;    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Sub&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleSub(l,r)
&lt;span class=&quot;linenr&quot;&gt;7: &lt;/span&gt;    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Div&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleDiv(l,r)
&lt;span class=&quot;linenr&quot;&gt;8: &lt;/span&gt;    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleMul(l,r)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
You can see in line 4 the code is a matter of lifting the value
wrapped in an Either. The type annotation is needed and creates some
noise.  I use the tell function to add a log entry for this step.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;tell&lt;/code&gt; is a method on the WriterT data type itself, and it takes
advantage of the log types monoid to combine this new log entry with
any prior ones. 
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;tell&lt;/span&gt;(l1&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;W&lt;/span&gt;)(using m&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monoid&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;], f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Functor&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;(wrapped.map{
    (l2,a) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
      (m.combine(l2, l1), a)
  })
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
By this technique at the end of a computation we
should see a log of entries.
&lt;/p&gt;

&lt;p&gt;
For example, the expression &lt;code&gt;Val(10)&lt;/code&gt; would be logged as &lt;code&gt;&quot;Val
10&quot;&lt;/code&gt;. Having a step-by-step log of your application has various uses
including the following.
&lt;/p&gt;

&lt;ol class=&quot;org-ol&quot;&gt;
&lt;li&gt;Debugging. View the state of your computation in detail&lt;/li&gt;
&lt;li&gt;Auditing and statistics. Analyze the log of your computation for business information.&lt;/li&gt;
&lt;li&gt;Restore a failed computation. You can log at each step enough information to resume an expensive computation that may have been interrupted.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
These kinds of benefits come with traditional logging, but building it
into your application in a pure and type rich way can amplify the
benefits.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s take a look at the symbol table lookup part of the program.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  summonEnv.get(s) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; {
      &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;.lift[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](&lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value)).tell(&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Var &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$s&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$value&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;)&quot;&lt;/span&gt;))
    }
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;.lift(&lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;.&lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;))
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Again the change is virtually mechanical. We lifted our old code and
added the tell call to add some logging information. When we view
variable lookups in the log you will see something like &lt;code&gt;Var(&quot;x&quot;)&lt;/code&gt;
written as &lt;code&gt;Var x (7)&lt;/code&gt; where 7 is its value in the symbol table.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org44604ed&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org44604ed&quot;&gt;Extending numeric&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org44604ed&quot;&gt;
&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleAdd&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] , r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] )&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) + eval(r)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The remainder of the program involves expressions like this one. We
use the &lt;code&gt;+&lt;/code&gt; operator to add two other expressions together. How that
works is a combination of operator overloading, extension methods and
implementing an implicit implementation of Numeric for our new WriterT
return type.
&lt;/p&gt;

&lt;p&gt;
Here I&apos;m defining an implicit instance of Numeric that handles things
are Writers around Eithers. In previous posts, this is where I first
implemented addition for different types of number, and then added the
ability to handle errors in a type safe and functional manner.
&lt;/p&gt;

&lt;p&gt;
I&apos;m just extending that technique to handle a more complicated type.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;given evalResultWNumeric[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt;
  &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;... implementations&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The implementation of Add assuming a Monadic instance is available is as follows.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;M&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; writerTMonad[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;]]

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], fb&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    &lt;span style=&quot;color: #00bcff;&quot;&gt;M&lt;/span&gt;.flatMap(fa) {
      a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;M&lt;/span&gt;.map(fb){
        b &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
          a + b
      }
    } &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Which does the job but it doesn&apos;t include any logging. We can add that too.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], fb&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    &lt;span style=&quot;color: #00bcff;&quot;&gt;M&lt;/span&gt;.flatMap(fa) {
      a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;M&lt;/span&gt;.flatMap(fb){
        b &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
          &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;result&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a + b 
          &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;w1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;.lift(&lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(result))
          w1.tell(&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Added &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$a&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; and &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$b&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; giving &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$result&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;))
      }
    }
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that by nesting the flatMaps we have access to a,b and the result
of the computation so we can put all of that into the tell call,
resulting in a log like &lt;code&gt;Added 22 and 23 giving 45&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
There&apos;s nothing really wrong with this implementation, but it&apos;s
important to always think about the principle of least power. Did I
really need a Monad here? Well in fact there is a great function for
applying a computation across two different effects and that is
&lt;code&gt;map2&lt;/code&gt;. It also requires only Applicative, so I can use that instead.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;App&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; writerTApplicative[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A1&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;]]

 &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], fb&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
   &lt;span style=&quot;color: #00bcff;&quot;&gt;App&lt;/span&gt;.map2(fa)(fb) {
     &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + b
   }
 }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This simplifies the code greatly but notice that I am no longer
logging anything. Unfortunately, I no longer have access to the result
of the computation. One clean solution I found here was to write a
helper method that is like a logging version of map2. Like map2 it
takes a function of two arguments to map the effect values, but it
takes a second function that takes the two values and their result and
lets you build a log entry from them.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mapTell2&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;](fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;],fb&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;],fabc&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;,fabcw&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; (&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;)
                           (using m&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monoid&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;], f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monad&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;W&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; fa.unwrap().map2(fb.unwrap()){
     &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; ((&lt;span style=&quot;color: #00d3d0;&quot;&gt;al&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;),(&lt;span style=&quot;color: #00d3d0;&quot;&gt;bl&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;)) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
       &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;c&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; fabc(a,b)
       &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;w&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; fabcw(a,b,c)
       &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;prev&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; m.combine(al,bl)
       (m.combine(prev,w),c)
   }
   &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;(r)
 }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
While this looks like a handful what it is really doing is
straightforward. Like map2 the input is two effects. First I unwrap
them which gives us the inner effect, and running map2 on those gives
the log and the value of each effect.
&lt;/p&gt;

&lt;p&gt;
Once I&apos;ve run the user function fabc on those values, I have the
result value c and I can use that to build a log with the fabcw
function. Finally, we need to combine the prior logs with the new log
and return the result.
&lt;/p&gt;

&lt;p&gt;
Here&apos;s the function in action.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;sub&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResultW&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
     mapTell2(a,b,(a, b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a / b,(a,b,c) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$c&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;: subtracted &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$a&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; from &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$b&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;))
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
By moving all that complexity into a helper function, each operator is now quite simple.
&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
[info] running Scala3EvalEitherTWriter 
WriterT(Right((List(Var y (6), Var x (7), Val 10, Var z (22)),45)))
Var y (6)
Var x (7)
Val 10
Var z (22)
exp01 WriterT(Left(DivisionByZero))
&lt;/pre&gt;

&lt;p&gt;
In summary, you can use WriterT to convert any effectful program into
one with step-by-step logging.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org697c96c&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org697c96c&quot;&gt;ReaderT&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org697c96c&quot;&gt;
&lt;p&gt;
Another useful data type with a Monad instance is the Reader. As the
name may imply, this is the conceptual opposite of Writer. i.e.,
instead of a computation writing its progress to a log, the Reader
provides an environment of some type that the application can read
from as it progresses.
&lt;/p&gt;

&lt;p&gt;
In the program so far I&apos;ve been using Scala 3 context functions to
pass around the symbol table. There are reasons you may want to do
that with a Reader instead. Perhaps you want to take advantage of the
compositionality and lawfulness of Reader. Perhaps you want the
context function reserved for some other purpose. Of course you may be
using Scala 2 and not have access to the context function feature at
all.
&lt;/p&gt;

&lt;p&gt;
In one of my videos, I show the process of replacing context functions
with the ReaderT monad transformer. Let&apos;s walk through the process
here.
&lt;/p&gt;

&lt;p&gt;
First of all let&apos;s look at the data type. Like the WriterT, the
ReaderT wraps another higher kinded type F. As you can see, there is a
second type parameter R, which is the type of the read-only
environment. Also, you can see from the signature is that what the
ReaderT contains is a function from R to the F[A]. How that is used
will become clear.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;ReaderT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;R&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](run&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;R&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Just like with WriterT we also would benefit from a lift function that
lets us take any instance of F and wrap it. Here I&apos;m saying if you
have some effect &lt;code&gt;F[A]&lt;/code&gt; I will give you a ReaderT that wraps it. You
can run it with some environment and it will yield that &lt;code&gt;F[A]&lt;/code&gt; again.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;lift&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;R&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;ReaderT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;R&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; fa)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
When rewriting the program above we can now look up variables from the
symbol table. We are returning a function that when given an
environment can search it for the required symbol. 
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;RResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
   &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;((env&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
     env.get(s) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
       &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value)
       &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;.&lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;)
     })
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Literal values are also simple, just lift the Either from before.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;.lift(&lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The arithmetic operations don&apos;t change at all since ReaderT has an
applicative instance we can just go ahead and use map2.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], fb&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    fa.map2(fb)((a,b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + b)
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here is what needs to be done to run the code. The main difference is
that we build a chain of Reader effects then execute them by passing
an environment to the run method.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;env1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;100&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;exp1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt;)),&lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt;))
println(eval(exp1).run(env1)) 

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Right(100))&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgae19976&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgae19976&quot;&gt;WriterT and ReaderT&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgae19976&quot;&gt;
&lt;div style=&quot;padding: 30px;&quot;&gt;
  &lt;img class=&quot;img&quot; src=&quot;../../../images/monadtransformer.png&quot; border=&quot;1&quot; alt=&quot;Diagram of monad transformers&quot; width=&quot;600&quot;/&gt;
&lt;/div&gt;

&lt;p&gt;
One thing I find wonderful about functional programming is its
compositionality. I&apos;ve shown that you can stack WriterT and ReaderT on
top of any effect to imbue that effect with more capabilities.
&lt;/p&gt;

&lt;p&gt;
Now given that WriterT can wrap a monadic effect to give that effect
logging, and further that ReaderT itself is a monad, it follows that
you can wrap WriterT around ReaderT to give some effect the powers of
both! This would work the other way around, and of course, you could
also make an EitherT monad transformer, giving even more
possibilities.
&lt;/p&gt;

&lt;p&gt;
The next step is to change the programs return type to be&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;[
  [&lt;span style=&quot;color: #00bcff;&quot;&gt;RA&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;EA&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;EA&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;RA&lt;/span&gt;],
  &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;],
  &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Next to modify the program to handle the new effect types.
&lt;/p&gt;

&lt;p&gt;
The implementation to get a value is easy enough. Starting from the
inside out the value is put into an Either, lifted into ReaderT and
lifted once more into WriterT.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;.lift(
     &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;.lift(
       &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(value))).tell(&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Literal value &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$value&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Handling variable lookup we take care of the lookup first then wrap
that into a writer.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WriterT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;RA&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;EA&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;EA&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;RA&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;((env&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
    env.get(s) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Looked up var &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$s&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$value&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;)&quot;&lt;/span&gt;),value)
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;.&lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;)
  }))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
I&apos;ll skip the rest of the program since the theme is the same; wrap
the reader code with the writer code and you&apos;re done. Let&apos;s take a
look at how to run the program.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;envMap&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;7&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;6&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;22&lt;/span&gt;)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;eval1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(exp1).unwrap().run(envMap)

eval1.foreach {
  (log, value) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
    println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Result is &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$value\n&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
    log.foreach {
      println(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;)
    }
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here you can see that our program has to be run sort of inside
out. &lt;code&gt;eval(exp1)&lt;/code&gt; gives us a &lt;code&gt;WriterT&lt;/code&gt;. By calling &lt;code&gt;unwrwap&lt;/code&gt; I get the
&lt;code&gt;ReaderT&lt;/code&gt; inside it, which I can then run by passing the environment.
&lt;/p&gt;

&lt;p&gt;
The response is either an error or a tuple of our log and result,
which we can then iterate over to print it out.
&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
Result is 990

Looked up var z (22)
Literal value 10
Literal value 2
Divided 10 by 2 (5)
Literal value 2
Subtracted 2 from 5 (3)
Looked up var x (7)
Looked up var y (6)
Multiplied 7 by 6 (42)
Added 3 to 42 (45)
Multiplied 22 by 45 (990)

&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org7a383cf&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org7a383cf&quot;&gt;Monad Transformers - some takeaways&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org7a383cf&quot;&gt;
&lt;p&gt;
You can see that monad transformers offer some expressive power since
they allow us to manually combine different effect types to get the
benefit of them all at once. 
&lt;/p&gt;

&lt;p&gt;
This comes at significant cost though. All this nesting creates
additional JVM objects that take up heap space and may cause extra
work for the garbage collector. 
&lt;/p&gt;

&lt;p&gt;
For the programmer, the ergonomics are not great. You have to remember
the level of nesting you&apos;re at at each point of your program and make
sure to do the right amount of lifting.
&lt;/p&gt;

&lt;p&gt;
Just look at this single simple expression. So much space is taken up
by the type signature, all the simplicity and elegance is lost.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleAdd&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] , r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] )&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; 
  &lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;RA&lt;/span&gt;] =&amp;gt;&amp;gt; 
    &lt;span style=&quot;color: #00bcff;&quot;&gt;ReaderT&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;EA&lt;/span&gt;] =&amp;gt;&amp;gt; 
      &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;EA&lt;/span&gt;], 
      &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;RA&lt;/span&gt;],
    &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;],
    &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) + eval(r)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now there ways to help out the Scala compiler and reduce the amount of
boilerplate, namely &quot;kinda curried type parameters&quot; which is a
technique used heavily in Scalaz and Zio.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://tpolecat.github.io/2015/07/30/infer.html&quot;&gt;https://tpolecat.github.io/2015/07/30/infer.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Thinking that the poor type inference is maybe my fault I&apos;ve also
written this code using Scalaz and Cats and you can see that each
implementation has its pros and cons. (BTW in these libraries ReaderT
is called Kleisli)
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/ZPurePlay/blob/master/src/main/scala/EvalScalaz.scala&quot;&gt;Reader Writer example in Scalaz&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/ZPurePlay/blob/master/src/main/scala/EvalCats.scala&quot;&gt;Reader Writer example in Typelevel Cats&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Both implementations had the same problem as I did when not writing
out the types in full. Scalaz had the same trouble inferring that my
type was applicative so I had to summon the instance explicitly.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;rwApply&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Apply&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;WriterT&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;Kleisli&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Error&lt;/span&gt;,?],&lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;],?],?]]
rwApply.apply2(x,y) {
       &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + b
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Cats was able to handle it resulting in less code and needed less type
annotations in general.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;x.map2(y) {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + b
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org0f5756a&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org0f5756a&quot;&gt;Effect rotation with Zio Prelude&apos;s ZPure&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org0f5756a&quot;&gt;
&lt;p&gt;
&lt;a href=&quot;https://github.com/zio/zio-prelude&quot;&gt;Zio Prelude&lt;/a&gt; is a new library that acts as a sort of add on library to
&lt;a href=&quot;https://github.com/zio/zio&quot;&gt;ZIO&lt;/a&gt; (a zero-dependency Scala library for asynchronous and concurrent
programming) which provides an alternative approach to functional
abstractions in Scala.
&lt;/p&gt;

&lt;p&gt;
For the purposes of this blog I&apos;m interested in particular
experimental data type within the library called &lt;code&gt;ZPure&lt;/code&gt;. ZPure has 6
type parameters and supports the operations of monads, applicatives
and functors, albeit the names are changed and some of the
abstractions too.
&lt;/p&gt;

&lt;p&gt;
From Prelude&apos;s own source code &quot;&lt;code&gt;ZPure&lt;/code&gt; can be used to model a variety
of effects including context, state, failure, and logging.&quot;, let&apos;s see
how it compares to monad transformers to implement the program above.
&lt;/p&gt;

&lt;p&gt;
ZPure has six type parameters, which may seem like a lot, but bear in
mind that every time you combine monads you get more type parameters,
but they are stacked vertically not horizontally. With ZPure you start
with all the different effect types one might need but you don&apos;t need
to keep adding more and more, and you don&apos;t suffer from creating
multiple objects per layer of effect.
&lt;/p&gt;

&lt;div style=&quot;padding: 30px;&quot;&gt;
  &lt;img class=&quot;img&quot; src=&quot;../../../images/zpure.png&quot; border=&quot;1&quot; alt=&quot;ZPure type parameters&quot; width=&quot;600&quot;/&gt;
&lt;/div&gt;

&lt;p&gt;
In the diagram the parameters are.
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;&lt;code&gt;W&lt;/code&gt; Logging. The type of logs that this effect produces, analogous to Writer&lt;/li&gt;
&lt;li&gt;&lt;code&gt;S&lt;/code&gt; State. There are two S&apos;s because the type encodes an input and output state type&lt;/li&gt;
&lt;li&gt;&lt;code&gt;R&lt;/code&gt; Reader. The type of the read-only environment&lt;/li&gt;
&lt;li&gt;&lt;code&gt;E&lt;/code&gt; Error. The type of the error channel&lt;/li&gt;
&lt;li&gt;&lt;code&gt;A&lt;/code&gt; Value. The type of the happy path computed value&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Just as before all I need to do is change my programs effect type and
modify the implementation accordingly. The code for this section can
be found &lt;a href=&quot;https://github.com/justinhj/ZPurePlay/blob/master/src/main/scala/EvalZpure.scala&quot;&gt;here&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Although Prelude supports Scala 3 now I rewrote my program in Scala 2
in order to do the Scalaz and Cats versions, so the following is also
pre Scala 3 friendly code. First I made a sealed trait to represent
the error types and an alias to indicate that my log will be
strings. 
&lt;/p&gt;

&lt;p&gt;
Note that ZPure is opinionated about the logging type. In the more
conventional approach, the log has to be a monoid instance. With ZPure
the log is handled using the ZIO &lt;code&gt;Chunk&lt;/code&gt; data type which is a
high-performance data structure with a pure functional interface. What
that means for us is that we can consider our log type as a single
entity and not worry about how it is appended.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;sealed&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;trait&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Error&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Error&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;DivisionByZero&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Error&lt;/span&gt;

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Log&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
These types will represent the &lt;code&gt;E&lt;/code&gt; or error, and &lt;code&gt;W&lt;/code&gt; or log. We can
encode our symbol table using the &lt;code&gt;R&lt;/code&gt; parameter.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The final type looks like this.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Log&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Any&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Any&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], &lt;span style=&quot;color: #00bcff;&quot;&gt;Error&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that I am not using the initial or updated state here so I use
Any for those parameters so as not to constrain them.
&lt;/p&gt;

&lt;p&gt;
Once again let&apos;s start with the implementation of literal values.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
  &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;.succeed(value).log(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Literal value &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$value&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
What&apos;s going on here is simple and refreshingly free of type
annotation. Firstly I construct a ZPure consisting of the literal
value, and then add a log using ZPure&apos;s log method. 
&lt;/p&gt;

&lt;p&gt;
Now let&apos;s implement the symbol table lookup of variables.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span class=&quot;linenr&quot;&gt; 1: &lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
&lt;span class=&quot;linenr&quot;&gt; 2: &lt;/span&gt;    &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;.environment[&lt;span style=&quot;color: #00bcff;&quot;&gt;Any&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]].flatMap {
&lt;span class=&quot;linenr&quot;&gt; 3: &lt;/span&gt;      env &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
&lt;span class=&quot;linenr&quot;&gt; 4: &lt;/span&gt;       &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;.fromOption(env.get(s)).
&lt;span class=&quot;linenr&quot;&gt; 5: &lt;/span&gt;       mapError(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;EvalZPure&lt;/span&gt;.&lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;).
&lt;span class=&quot;linenr&quot;&gt; 6: &lt;/span&gt;       flatMap{
&lt;span class=&quot;linenr&quot;&gt; 7: &lt;/span&gt;        a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
&lt;span class=&quot;linenr&quot;&gt; 8: &lt;/span&gt;          &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;.log(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Var &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$s&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; value &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$a&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;).as(a)
&lt;span class=&quot;linenr&quot;&gt; 9: &lt;/span&gt;       }      
&lt;span class=&quot;linenr&quot;&gt;10: &lt;/span&gt;    }
&lt;span class=&quot;linenr&quot;&gt;11: &lt;/span&gt;}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
First I use the ZPure.environment to summon the symbol table and
flatMap over it so we can access it as a concrete value &lt;code&gt;env&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Remember that looking up the variable in the symbol table
is going to return an Option since it is a normal map get. We can then
use the ZPure.fromOption to convert that to a ZPure.
&lt;/p&gt;

&lt;p&gt;
We may be a ZPure at that point but we have the wrong error type. In
ZPure and option is simulated by yielding a success value A for Some,
or giving Unit in the error channel to indicate None. This reuse of
the error channel is neat, but since I would like a homogenous error
type for the program I need to convert that error channel from unit to
my own custom Error type. 
&lt;/p&gt;

&lt;p&gt;
To do that I use mapError which takes a function to map the error from
one type to another.
&lt;/p&gt;

&lt;p&gt;
The final step is to add a log. Since I would like the log to show
both the variable name and the actual value I have to nest it inside a
flatMap so we can access the success value. The last thing to note
here is the &lt;code&gt;as&lt;/code&gt; which helps the type system make a ZPure of the right
type.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;numericZResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; 
  &lt;span style=&quot;color: #00bcff;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(x&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], y&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
      x.zip(y).flatMap{&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
        &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;.succeed(a + b).log(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Add &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$a&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; and &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$b&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)}
  }
  &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;and so on&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The final component is to make an instance of Numeric. Prelude takes
the approach to naming that concepts should be plain English where
possible, so it uses &lt;code&gt;succeed&lt;/code&gt; instead of &lt;code&gt;pure&lt;/code&gt; or &lt;code&gt;unit&lt;/code&gt; and
similarly &lt;code&gt;zip&lt;/code&gt; instead of applicative terminology.
&lt;/p&gt;

&lt;p&gt;
That being the case, we use zip here to combine the left and right
side effects and apply the appropriate arithmetic operator.
&lt;/p&gt;

&lt;p&gt;
So far so good, but we can&apos;t log the result of the computation. This
is easily solved.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(x&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], y&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Result&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    x.zip(y).flatMap{&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; (&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;  {
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;result&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a + b
      &lt;span style=&quot;color: #00bcff;&quot;&gt;ZPure&lt;/span&gt;.succeed(result).log(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Add &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$a&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; and &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$b&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$result&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;)&quot;&lt;/span&gt;)}
    }
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The last part to note is the driver code to run the program.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;eval1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(exp1).provide(env1).runAll()

eval1._2 &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
    println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Succeeded with value &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;${value._2}&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
    eval1._1.foreach {
      l &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
        println(l)
  }
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;err&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
    println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;oops! &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$err&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here I run eval to create the effect, provide to give it the runtime
environment and runAll. To be clear what eval does is not run a
program, but build a data structure of objects based on the ZPure
operations, and that data structure is evaluated in Prelude using an
efficient interpreter, that yields the result of the program, the log
and any state changes.
&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
Succeeded with value 200
Literal value 10
Var x value 1
Mul 10 with 1 (10)
Var y value 10
Mul 10 with 10 (100)
Var z value 100
Add 100 and 100 (200)
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgcd6c223&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgcd6c223&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgcd6c223&quot;&gt;
&lt;p&gt;
In this post I implemented and motivated ReaderT and WriterT and
transforming monads to combine effects. Even in Haskell where they
originated, monad transformers come with caveats about performance and
ergonomics. In Scala they are not used often.
&lt;/p&gt;

&lt;p&gt;
There are techniques and libraries to make their use more
convenient. Although I have not used it &lt;a href=&quot;https://github.com/typelevel/cats-mtl&quot;&gt;Cats MTL&lt;/a&gt; offers solutions to
some of the problems, but it is not widely used.
&lt;/p&gt;

&lt;p&gt;
Although ZIO Prelude&apos;s ZPure is still somewhat experimental it seems
offer the benefits of monad transformers such as composability and a
prinicipled type safe api. But, it is also much easier to work with
and anecdotally more performant on the JVM.
&lt;/p&gt;

&lt;p&gt;
In the future I&apos;m looking forward to exploring some traditional
functional programming problems using Prelude and ZPure.
&lt;/p&gt;

&lt;p&gt;
Hope you enjoyed this post and got to the end. You can find my contact
details at the top of the page; I always welcome feedback and
questions.
&lt;/p&gt;

&lt;p&gt;
(C)2021 Justin Heyes-Jones, All Rights Reserved.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Fri, 04 Jun 2021 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2021/06/04/monad-transformers-the-prelude-to-zpure.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2021/06/04/monad-transformers-the-prelude-to-zpure.html</guid>
        
        <category>scala</category>
        
        <category>scala-3</category>
        
        <category>dotty</category>
        
        <category>monads</category>
        
        <category>category-theory</category>
        
        <category>popular</category>
        
        
      </item>
    
      <item>
        <title>Monads in Scala 3 for the Genius</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;
&lt;div id=&quot;outline-container-org9e88539&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org9e88539&quot;&gt;Introduction&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org9e88539&quot;&gt;
&lt;p&gt;
This is a companion blog the seventh Functional Justin YouTube video
which you can find here:
&lt;a href=&quot;https://www.youtube.com/watch?v=B1FSxbmZpCE&quot;&gt;https://www.youtube.com/watch?v=B1FSxbmZpCE&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
The source code shown in the video and in the fragments below can be found here:
&lt;a href=&quot;https://github.com/justinhj/evalexample/blob/video-7-r3/src/main/scala/livevideos/Video7.scala&quot;&gt;https://github.com/justinhj/evalexample/blob/video-7-r3/src/main/scala/livevideos/Video7.scala&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
The goal here is to make 10-15 minute videos that each cover an
isolated topic in pure functional programming with Scala. There is an
also overarching goal to cover a certain number of base topics you
need in functional programming. Once that is complete I will start
doing deep dives into FP libraries such as Cats and Zio.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgb5739ff&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb5739ff&quot;&gt;Monads for the Genius&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb5739ff&quot;&gt;
&lt;p&gt;
The title may sound like clickbait, and it most surely is, but the
point is that for most Scala programmers, even those working with
functional programming libraries, most of what you need to know about
Monads is what the type signatures of the methods are and how you can
leverage those in your code. For bonus points you can learn the Monad
laws and implement your own lawful Monad instances.
&lt;/p&gt;

&lt;p&gt;
If you want to know why Monad consists of pure (or unit) and flatMap,
and why Monads are functors (they have map) you need to dig a little
deeper, and for that reason I targeted this post at the genius, but
perhaps the curious would be a better way to put it, it hopefully will
not be a really difficult topic to follow.
&lt;/p&gt;

&lt;p&gt;
In this post and the accompanying video I will show the category
theory you need to understand monad and derive an implementation of
the monad type class from that theoretical foundation. From there the
next step is to show the monad in use on effects and how to implement
and use flatMap (or bind).
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org1353719&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org1353719&quot;&gt;Just enough Category Theory&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org1353719&quot;&gt;
&lt;p&gt;
Category theory is a candidate for a theory that describes all of mathematics, and has been applied to a number of areas.&lt;sup&gt;&lt;a id=&quot;fnr.1&quot; class=&quot;footref&quot; href=&quot;#fn.1&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;. If you want to know more about it than the very basics then I recommend Category Theory for Progammers.&lt;sup&gt;&lt;a id=&quot;fnr.2&quot; class=&quot;footref&quot; href=&quot;#fn.2&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;
&lt;/p&gt;

&lt;p&gt;
The essence of category theory is the category itself, which consists of objects and morphisms that transition from one object to another. 
&lt;/p&gt;

&lt;img class=&quot;img&quot; src=&quot;../../../images/Categories3.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;Category theory diagram&quot; width=&quot;600&quot;/&gt;

&lt;p&gt;
In addition there must be an identity morphism on each object. This simply gives you a way to transition from an object to itself.
&lt;/p&gt;

&lt;img class=&quot;img&quot; src=&quot;../../../images/Categories4.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;Category theory diagram&quot; width=&quot;600&quot;/&gt;

&lt;p&gt;
Morphisms between objects can compose. Here we have a morphism from A to B (f) and another from B to C (g). We can compose f and g, giving us a single morphism from A to C.
&lt;/p&gt;

&lt;img class=&quot;img&quot; src=&quot;../../../images/Categories5.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;Category theory diagram&quot; width=&quot;600&quot;/&gt;

&lt;p&gt;
Composition must follow the associative law. As shown below that means if we have three morphisms f,g and h, it doesn&apos;t matter how we compose them as long we don&apos;t change the order they are applied. We can compose them in two different ways.
&lt;/p&gt;

&lt;img class=&quot;img&quot; src=&quot;../../../images/Categories6.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;Category theory diagram&quot; width=&quot;600&quot;/&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org1e6352a&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org1e6352a&quot;&gt;The category of Scala types and functions&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org1e6352a&quot;&gt;
&lt;p&gt;
Let&apos;s make the concept of a category more concrete by seeing how it can be encoded in Scala. One example of a category is the category of Scala types and functions.
&lt;/p&gt;

&lt;p&gt;
In the code below we have a lawful category. The objects are the Scala
types (Ints, Booleans, Strings) and the morphisms that take us from
one object to the next are ordinary Scala functions. There are three
examples f,g and h.
&lt;/p&gt;

&lt;p&gt;
Remember to be a category we need an identity morphism, which turns out to be simply the Scala &lt;code&gt;identity&lt;/code&gt;. (A =&amp;gt; A).
&lt;/p&gt;

&lt;p&gt;
The other thing we need is a way to combine morphisms that must be associative. We have that with the built in function &lt;code&gt;compose&lt;/code&gt;!
&lt;/p&gt;

&lt;p&gt;
As you can see in the code it is straightforward to show the laws of the category are upheld.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Category of Scala functions&lt;/span&gt;

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;g&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Boolean&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; b &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt;(b == &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;h&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Boolean&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; c &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt;(c == &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;) &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Winner!&quot;&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Loser!&quot;&lt;/span&gt;

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Identity&lt;/span&gt;
f.compose((a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; identity(a))(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;) == f(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;)

f(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;) == f.compose((a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; identity(a))(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;)

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Composition must be associative&lt;/span&gt;
h.compose(g.compose(f))(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;) == (h.compose(g.compose(f)))(&lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Above you can see composing the identity function with f gives the same result as calling f alone. 
&lt;/p&gt;

&lt;p&gt;
You can also see that composition is associative. We compose h with g
and f in different ways, without changing the order, and get the same
results.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgda19ef9&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgda19ef9&quot;&gt;A monad is just a functor in the category of Kleisli arrows&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgda19ef9&quot;&gt;
&lt;p&gt;
What&apos;s the problem?
&lt;/p&gt;

&lt;p&gt;
Well there are two problems here. For one many readers may be saying
&quot;What? Surely a monad is a just a monoid in the category of
endofunctors!&quot;&lt;sup&gt;&lt;a id=&quot;fnr.3&quot; class=&quot;footref&quot; href=&quot;#fn.3&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;
&lt;/p&gt;

&lt;p&gt;
Perhaps another group are completely lost. Well the famous quote about
monads is absolutely right, but that is a different way to arrive at
Monads than the simpler one we are looking at here.
&lt;/p&gt;

&lt;p&gt;
Instead we will arrive at Monads by making a simple change to the
Category of Scala types and functions. The only change we will make is
instead of Scala functions of the form &lt;code&gt;A =&amp;gt; B&lt;/code&gt; we will instead use
what is known as a Kliesli arrow, which has the form &lt;code&gt;&quot;A =&amp;gt; F[B]&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
You may recognize that shape of function from the argument to Scala&apos;s
flatMap. In other words it is the type of function that maps a pure
value to an effectful value.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s look at how we can encode this new category directly in Scala as a monad!
&lt;/p&gt;

&lt;p&gt;
Note I will call the Monad type class Monad1 to avoid confusion with
the more usual Monad definition in the code.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;trait&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monad1&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;]]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;unit&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;compose&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;](lf&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;], rf&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
In the definition above we have all we need to implement the category
of Scala objects and Kliesli arrows (and incidentally this is, by
definition, a monad).
&lt;/p&gt;

&lt;p&gt;
Firstly what are the objects? Just like before the objects are Scala types.
&lt;/p&gt;

&lt;p&gt;
Next what are the morphisms? We stated the morphisms would be of the form &lt;code&gt;A =&amp;gt; F[B]&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Finally what is the identity? The identity has the same form as any
other morphism except that it maps a type to itself, so the identity
is &lt;code&gt;A =&amp;gt; F[A]&lt;/code&gt;. We can implement that in Scala with the &lt;code&gt;unit&lt;/code&gt;
function above.
&lt;/p&gt;

&lt;p&gt;
With Scala functions we used the compose function. Here we need to
write our own code that composes two Kleisli arrows returning a new
one. This is the direct analog of the compose function that works with
simple functions.
&lt;/p&gt;

&lt;p&gt;
For convenience, just like with any other Scala 3 type class we need a
way to summon a Monad of a particular type into existence and for that
we write the apply function as follows.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Monad1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;apply&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;]](using m&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monad1&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; m
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org4f60c84&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org4f60c84&quot;&gt;Implementation of Monad for Option&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org4f60c84&quot;&gt;
&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;given optionMonad1&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monad1&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;unit&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;(a)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;compose&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;](lf&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;], rf&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
      lf(a) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
        &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
          rf(b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
            &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;b&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; rf(b)
            &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt;
          }
        &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt;          
      } 
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
You can see that unit is just a call to the Option constructor, whilst
compose will return a new function that first applies &lt;code&gt;lf&lt;/code&gt; to the
input, then if that yields a value and not a None, it will apply &lt;code&gt;rf&lt;/code&gt;
to that yielding a new Option. Please note I made an overly complex
version of this in the video, and only realized once it was too late.
&lt;/p&gt;

&lt;p&gt;
Now we can write code that composes &quot;effect generating&quot; functions (or
Kliesli arrows) together. Here I make three simple functions that
operate on Scala values and produce Options.
&lt;/p&gt;

&lt;p&gt;
Here we use the Monad1 option to compose f,g and h&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;f&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Option&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; n == &lt;span style=&quot;color: #00bcff;&quot;&gt;4&lt;/span&gt; then &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;(n)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;g&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Option&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Boolean&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; n%&lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;==&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt; then &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;h&lt;/span&gt;(b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;Boolean&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Option&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; b then &lt;span style=&quot;color: #00bcff;&quot;&gt;Some&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Winner!&quot;&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;None&lt;/span&gt;

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;fcomposed&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Monad1&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;].compose(f,g)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;fghComposed&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Monad1&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Option&lt;/span&gt;].compose(fcomposed, h)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;i&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Float&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;0.0&lt;/span&gt;

println(fghComposed(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;))
println(fghComposed(&lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;))
println(fghComposed(&lt;span style=&quot;color: #00bcff;&quot;&gt;3&lt;/span&gt;))
println(fghComposed(&lt;span style=&quot;color: #00bcff;&quot;&gt;4&lt;/span&gt;))

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Output:&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Some(Winner!)&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;None&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Some(Winner!)&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;None&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgd24b5d9&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgd24b5d9&quot;&gt;The Monad laws&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgd24b5d9&quot;&gt;
&lt;p&gt;
At this point we&apos;ve shown that one implementation of a Monad involves
the unit and compose functions. We can now see a demonstration of the
monad laws in this form.
&lt;/p&gt;

&lt;p&gt;
Left and right indentity laws are shown by composing a function with
unit. This is equivalent to what we did with Scala functions.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;left and right identity&lt;/span&gt;
m1.compose(f, m1.unit)(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) == f(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
f(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) == m1.compose(f, m1.unit)(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
We can also demonstrate the associtive law in action, whereby
composing f,g and h works both ways.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;m1.compose(m1.compose(f,g), h)(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) == m1.compose(f, m1.compose(g,h))(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org10cc5ed&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org10cc5ed&quot;&gt;What about flatMap?&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org10cc5ed&quot;&gt;
&lt;p&gt;
So far so good, we conjured up a monad from just category theory and a
simple twist on the category of types and functions. You may be
wondering how we get from this new definition of Monad to the one we
see in Cats and Scalaz, and why even in the Scala standard library we
have flatMap but not compose for Kliesli arrows.
&lt;/p&gt;

&lt;p&gt;
Well fortunately flatMap can be written in terms of compose, so we can
be assured that the more convenient and familiar representation of
Monads is exactly equivalent!
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;flatMap&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](fa&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;])(using m&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monad1&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;F[A] =&amp;gt; F[A]&lt;/span&gt;
  &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;A =&amp;gt; F[B]&lt;/span&gt;
  m.compose((a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; identity(a), a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; f(a))(fa)
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
I found this implementation a bit tricky to understand at first but if
you look at it and reference the Option instance above it should make
sense after a little thought. The &quot;trick&quot; is that we are given an
&lt;code&gt;F[A]&lt;/code&gt; and so we pass that as the first argument to compose using the
identity function to get it back unchanged. (Mapping an F[A] to itself
is actually the map function of Functor!)
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org63d0031&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org63d0031&quot;&gt;compose from flatMap&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org63d0031&quot;&gt;
&lt;p&gt;
Should your starting point be the more traditional Monad with pure and
flatMap, you can in fact derive the compose function as follows.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;import&lt;/span&gt; org.justinhj.typeclasses.monad.{given,&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;}

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;compose&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;],&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;](lf&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;], rf&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;B&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;])(using m&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Monad&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;C&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; 
  a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; lf(a).flatMap(rf) 
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org67d3bb6&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org67d3bb6&quot;&gt;Final remarks&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org67d3bb6&quot;&gt;
&lt;p&gt;
One last thing you may be interested in is that you can implement monad as pure and flatmap, pure and compose or as third set pure, map and flatten.
&lt;/p&gt;

&lt;p&gt;
My favourite reference for exploring Monads in Scala is the so called
red book which devotes chapter 11 to the subject.&lt;sup&gt;&lt;a id=&quot;fnr.4&quot; class=&quot;footref&quot; href=&quot;#fn.4&quot;&gt;4&lt;/a&gt;&lt;/sup&gt; The nice thing about
that particular book is it encourages the sort of exploration and
discovery of these concepts that makes them so fun to work with!
&lt;/p&gt;

&lt;p&gt;
There is some duplication in the names when we use category theory in Scala that can cause confusion. Here&apos;s a little guide.
&lt;/p&gt;

&lt;table border=&quot;2&quot; cellspacing=&quot;0&quot; cellpadding=&quot;6&quot; rules=&quot;groups&quot; frame=&quot;hsides&quot;&gt;


&lt;colgroup&gt;
&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;

&lt;col  class=&quot;org-left&quot; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Purpose&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Functions&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;Kleislis&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/th&gt;
&lt;th scope=&quot;col&quot; class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Identity&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;identity&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;unit&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;pure&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;return&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;point&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Sequence two effects&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;n/a&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;flatMap&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;bind&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;org-left&quot;&gt;Flatten a nested effect&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;n/a&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;flatten&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;join&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/td&gt;
&lt;td class=&quot;org-left&quot;&gt;&amp;#xa0;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
Finally it was really my goal here to show that there is not much to
categories and therefore not much to monads. The terminology is
unfamiliar but I think the concepts are quite straightforward. I would
love to know if this blog and/or video failed to make sense, so feel
free to reach out to be on the youtube comments or via the contact
details above and I will take on board your suggestions.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;footnotes&quot;&gt;
&lt;h2 class=&quot;footnotes&quot;&gt;Footnotes: &lt;/h2&gt;
&lt;div id=&quot;text-footnotes&quot;&gt;

&lt;div class=&quot;footdef&quot;&gt;&lt;sup&gt;&lt;a id=&quot;fn.1&quot; class=&quot;footnum&quot; href=&quot;#fnr.1&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; &lt;div class=&quot;footpara&quot;&gt;&lt;p class=&quot;footpara&quot;&gt;
Uses of Category Theory &lt;a href=&quot;https://math.stackexchange.com/a/1210742/2914&quot;&gt;https://math.stackexchange.com/a/1210742/2914&lt;/a&gt;
&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;footdef&quot;&gt;&lt;sup&gt;&lt;a id=&quot;fn.2&quot; class=&quot;footnum&quot; href=&quot;#fnr.2&quot;&gt;2&lt;/a&gt;&lt;/sup&gt; &lt;div class=&quot;footpara&quot;&gt;&lt;p class=&quot;footpara&quot;&gt;
Category Theory for Programmers &lt;a href=&quot;https://github.com/hmemcpy/milewski-ctfp-pdf&quot;&gt;https://github.com/hmemcpy/milewski-ctfp-pdf&lt;/a&gt;
&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;footdef&quot;&gt;&lt;sup&gt;&lt;a id=&quot;fn.3&quot; class=&quot;footnum&quot; href=&quot;#fnr.3&quot;&gt;3&lt;/a&gt;&lt;/sup&gt; &lt;div class=&quot;footpara&quot;&gt;&lt;p class=&quot;footpara&quot;&gt;
James Iry and the famous monad quote &lt;a href=&quot;https://stackoverflow.com/questions/3870088/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem#3870310&quot;&gt;https://stackoverflow.com/questions/3870088/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem#3870310&lt;/a&gt;
&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;footdef&quot;&gt;&lt;sup&gt;&lt;a id=&quot;fn.4&quot; class=&quot;footnum&quot; href=&quot;#fnr.4&quot;&gt;4&lt;/a&gt;&lt;/sup&gt; &lt;div class=&quot;footpara&quot;&gt;&lt;p class=&quot;footpara&quot;&gt;
Functional Programming in Scala &lt;a href=&quot;https://www.manning.com/books/functional-programming-in-scala&quot;&gt;https://www.manning.com/books/functional-programming-in-scala&lt;/a&gt;
&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;


&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Tue, 02 Feb 2021 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2021/02/02/monads-in-scala-3-for-the-genius.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2021/02/02/monads-in-scala-3-for-the-genius.html</guid>
        
        <category>scala</category>
        
        <category>scala-3</category>
        
        <category>dotty</category>
        
        <category>monads</category>
        
        <category>category-theory</category>
        
        
      </item>
    
      <item>
        <title>Functional Error Handling with Applicative in Scala 3</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;
&lt;div id=&quot;outline-container-org56d8e82&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org56d8e82&quot;&gt;Introduction&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org56d8e82&quot;&gt;
&lt;p&gt;
This is a companion blog my sixth Functional Justin YouTube video
which you can find here: &lt;a href=&quot;https://youtu.be/3GPXEzO14ZE&quot;&gt;https://youtu.be/3GPXEzO14ZE&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
In the video I talked about the Functor Laws and continued working on
the example program that evaluates arithmetic expressions. I use
Monad, then Applicative, to show how we can make a Numeric instance
for Either, so we can handle errors in a nice functional way.
&lt;/p&gt;

&lt;p&gt;
Since the episode I spent a bit of time cleaning up the code and
putting what we already saw (Numeric and Functor) into their own
packages. I also went ahead and implemented Applicative and Monad
which will be used in the the video and below.
&lt;/p&gt;

&lt;p&gt;
You can find the typeclasses here:
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/evalexample/tree/video6/src/main/scala/org/justinhj/typeclasses&quot;&gt;https://github.com/justinhj/evalexample/tree/video6/src/main/scala/org/justinhj/typeclasses&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orga7f44da&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga7f44da&quot;&gt;Functor Laws&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga7f44da&quot;&gt;
&lt;p&gt;
Our Functor type class really only exists to implement the map
function, and we already have a map function in the Scala standard
library for such things as Options, Lists and Futures. You might
wonder why we would go the trouble of making our own abstraction just
to write a function that we already had.
&lt;/p&gt;

&lt;p&gt;
The goal of abstractions like Functor is not just to provide useful
functions like map, but to provide a principled layer that we can
build further abstractions upon. For example we will see that
Applicative can be built on top of Functor, Monad on top of
Applicative, and this is only possible because Functor behaves in
accordance to strict rules that it brought with it from Category
Theory.
&lt;/p&gt;

&lt;p&gt;
You can read more about Functors on the Haskell documentation pages:
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://wiki.haskell.org/Functor&quot;&gt;https://wiki.haskell.org/Functor&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Another great resource is the famous &quot;red book&quot;&amp;#x2026; 
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://www.manning.com/books/functional-programming-in-scala&quot;&gt;https://www.manning.com/books/functional-programming-in-scala&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgdf1599b&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;orgdf1599b&quot;&gt;Functors preserve identity morphisms&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-orgdf1599b&quot;&gt;
&lt;p&gt;
What this law states is that if we map over some effect with the
identity function, then neither the effect nor any value inside it
will change.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Identity law for functors...&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;l1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;3&lt;/span&gt;)
assert(l1 == l1.fmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; identity(a)))

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;)
assert(e1 == e1.fmap(identity))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
In the two examples we mapped an Either and a List using the identity
function and nothing changed.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org49b33c1&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org49b33c1&quot;&gt;Functors preserve composition of morphisms&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org49b33c1&quot;&gt;
&lt;p&gt;
If we have two functions, f and g, it doesn&apos;t matter if we map over
some effect with f first then map over it with g, or we map over it
one time with the composition of f and g. Using the either and list
from above we can show this the case here.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;f&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;g&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a - &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;

assert(e1.fmap(f).fmap(g) == e1.fmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; g(f(a))))
assert(l1.fmap(f).fmap(g) == l1.fmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; g(f(a))))
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org2564946&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org2564946&quot;&gt;Importing given instances&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org2564946&quot;&gt;
&lt;p&gt;
Note that in Scala pre version 3 if you use a wildcard import &lt;code&gt;_&lt;/code&gt; then
you get all everything exposed in that package. That means you get all
the implicit instances too. It was a source of confusion for beginners
and even experienced Scala programmers to know which file to import
and sometimes to know where instances you are using are defined.
&lt;/p&gt;

&lt;p&gt;
To help with that NO implicits are imported with a regular wildcard
and instead you must import them with the new given syntax.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;import&lt;/span&gt; org.justinhj.typeclasses.functor.{given, &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
If you want you can also import only specific instances. This, in my
opinon, will make things a lot simpler and more precise.
&lt;/p&gt;

&lt;p&gt;
One caveat here is that the given wildcard must appear before the
underscore wildcard.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org43d9bbb&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org43d9bbb&quot;&gt;Implementing Numeric for Either&lt;/h2&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orga9f41c5&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga9f41c5&quot;&gt;Functor isn&apos;t enough&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga9f41c5&quot;&gt;
&lt;p&gt;
The following code implements an arithmetic expression evaluator using
the Numeric type class developed in a previous video and adds error
handling by using Either. Each step of our evaluator has this signature.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WithEnv&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Which means it is a function takes an input environment (our symbol
table) as an implicit argument, and returns an Either where the error
(or Left) type is EvalError. EvalError represents the different errors
our code will handle. It is a sum type implemented as a Scala 3 enum
(seen in a previous video).
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;InvalidSymboName&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
In previous blogs/videos I showed how we can implement a Numeric
instance so we can do arithmetic on many different types, just so long
as we create an instance of Numeric to handle them. Now we must
implement Numeric for the following type &lt;code&gt;Numeric[Either[EvalError, A]]&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
The instance signature is
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;given evalResultNumeric[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt; {
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now we must implement the methods of Numeric. Because our numeric
values are inside the EvalResult (an Either) we can&apos;t just implement
the multiply directly. We need a way to get inside it. As we saw in
the previous blog/video, Functor gives us a way to apply a pure
function to an effect. Since mul is a pure function, maybe we can use
it?
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mul&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  a.fmap { &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;DOES NOT COMPILE, WRONG TYPE&lt;/span&gt;
    aa &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
    b.fmap {
      bb &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
        aa * bb
    }
  }
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note I am using the name fmap and fflatMap to make it clear we are not
using the standard library implementations here. This is just for
clarity but is not a good practise because, for example, you will lose
the ability to use for comprehensions.
&lt;/p&gt;

&lt;p&gt;
What went wrong here is that Functor&apos;s map operation has the signature
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;extension [&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](x&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;ffmap&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
which means it takes our &lt;code&gt;Either[EvalError, Numeric[A]]&lt;/code&gt; and a pure
function, which it will apply to the Numeric. Unfortunately we end up
with an extra layer of Either! Let&apos;s see why&amp;#x2026;
&lt;/p&gt;

&lt;img class=&quot;img&quot; src=&quot;../../../images/flatmapcallout1.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;flatmap types diagram reproduced in code&quot; width=&quot;600&quot;/&gt;
&lt;img class=&quot;img&quot; src=&quot;../../../images/flatmapcallout2.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;flatmap types diagram reproduced in code&quot; width=&quot;600&quot;/&gt;
&lt;img class=&quot;img&quot; src=&quot;../../../images/flatmapcallout3.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;flatmap types diagram reproduced in code&quot; width=&quot;600&quot;/&gt;
&lt;img class=&quot;img&quot; src=&quot;../../../images/flatmapcallout4.png&quot; border=&quot;0&quot; style=&quot;padding: 30px;&quot; alt=&quot;flatmap types diagram reproduced in code&quot; width=&quot;600&quot;/&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org25495d6&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org25495d6&quot;&gt;Monad to the rescue&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org25495d6&quot;&gt;
&lt;p&gt;
So instead of Functor with its map function, we need Monad and its
flatMap which let&apos;s us implement all the arithmetic functions in a
straightforward manner.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/evalexample/blob/video6/src/main/scala/org/justinhj/typeclasses/monad/Monad.scala&quot;&gt;https://github.com/justinhj/evalexample/blob/video6/src/main/scala/org/justinhj/typeclasses/monad/Monad.scala&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
I&apos;ve implemented Monad in the file above and made it available to the
code. The implementation is simple and based on the example given in
the Dotty documentation. The main difference is I&apos;ve also implemented
Applicative, since we will use that in a moment, and Monad extends
Applicative.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/contextual/type-classes.html&quot;&gt;https://dotty.epfl.ch/docs/reference/contextual/type-classes.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Now each arithmetic operator can be implemented as follows, which
achieves our goal of being principled and functional and let&apos;s us
handle errors at the type level.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mul&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  a.fflatMap {
    aa &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; 
      b.map {
        bb &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt;
          aa * bb
      }
  }
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org957c8d2&quot; class=&quot;outline-3&quot;&gt;
&lt;h3 id=&quot;org957c8d2&quot;&gt;Map2 we love you&lt;/h3&gt;
&lt;div class=&quot;outline-text-3&quot; id=&quot;text-org957c8d2&quot;&gt;
&lt;p&gt;
Unfortunately it&apos;s bit verbose. Monad is more powerful than we need in
fact. We could use Applicative instead. I will talk more about Monad
and Applicative in a later video, but in short you can think of Monads
as being good for putting two effects together and flattening the
result, whilst Applicative is good for passing multiple effect values
as parameters to some pure function.
&lt;/p&gt;

&lt;p&gt;
You can see the Applicative implementation here. 
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/evalexample/blob/video6/src/main/scala/org/justinhj/typeclasses/applicative/Applicative&quot;&gt;https://github.com/justinhj/evalexample/blob/video6/src/main/scala/org/justinhj/typeclasses/applicative/Applicative&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Now, Functor has map, Monad has flatMap and Applicative has its own
mapping function called ap. Whilst it&apos;s out of scope for right now,
the ap mapping function makes it possible to apply two or more effects
as parameters to a pure function, which is exactly what we need
here. From ap you can derive methods that make this much simpler, map2
for example. Here we use map 2 to take any two input effects and apply
the multiply operator to them&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mul&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; 
  a.map2(b)((a,b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a * b)
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org6accaa4&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org6accaa4&quot;&gt;Division by Zero&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org6accaa4&quot;&gt;
&lt;p&gt;
What we have at this point is a nice implementation of Numeric that
uses Either&apos;s for error handling, which in turn is built on
Applicative. Let&apos;s see how easy it is to add new errors and
capabilities to the expression evaluator.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;InvalidSymboName&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;SymbolNotFound&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;DivisionByZero&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
First we add a new error type DivisionByZero. The next thing we need
is for Numeric to have a concept of whether a number is zero or
not. Remember that we can implement Numeric for many different types
and not all of them represent zero the same way. We can therefore add
an isZero predicate to the type class.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;isZero&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Boolean&lt;/span&gt; 
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Next every instance of Numeric needs an implementation of it, so for
exapmle in the Int instance we have the following.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;isZero&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a == &lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
The implementation for Numeric Either let&apos;s us write the isZero for
any value in an either as long as that value has a numeric instance of
its own.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;given evalResultNumeric[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;isZero&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Boolean&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; summon[&lt;span style=&quot;color: #00bcff;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]].isZero(a) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;true&lt;/span&gt;
      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;false&lt;/span&gt;
    }
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Finally we can implement the division operator for Numeric Either like this.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;div&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;], b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;EvalResult&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;if&lt;/span&gt; isZero(b) then
    &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;EvalError&lt;/span&gt;.&lt;span style=&quot;color: #00bcff;&quot;&gt;DivisionByZero&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;else&lt;/span&gt; 
    a.map2(b)(&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt; / &lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;)
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org2c69f4b&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org2c69f4b&quot;&gt;Wrap up&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org2c69f4b&quot;&gt;
&lt;p&gt;
That&apos;s all for now, I hope you enjoyed this post and video. Please
contact me using the methods above with any questions, suggestions or
corrections!
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Thu, 21 Jan 2021 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2021/01/21/functional-error-handling-with-applicative-in-scala-3.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2021/01/21/functional-error-handling-with-applicative-in-scala-3.html</guid>
        
        <category>scala</category>
        
        <category>scala-3</category>
        
        <category>dotty</category>
        
        <category>applicative</category>
        
        <category>monads</category>
        
        <category>applicative-functor</category>
        
        
      </item>
    
      <item>
        <title>Handling Errors functionally with Scala 3</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;
&lt;div id=&quot;outline-container-org98c4581&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org98c4581&quot;&gt;Introduction&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org98c4581&quot;&gt;
&lt;p&gt;
This is a companion blog my fifth Functional Justin YouTube video
which you can find here: &lt;a href=&quot;https://youtu.be/wNVQ75KM8-4&quot;&gt;https://youtu.be/wNVQ75KM8-4&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
If you&apos;re new to the series I&apos;m exploring Scala 3 and functional
programming using a simple expression evaluator, and adding features
to it every week. Most of the videos are coffee break sized (10-15
minutes) but this one took a bit longer as I needed more time to
explain the concepts. Next time will probably be back down to the more
bite-sized format.
&lt;/p&gt;

&lt;p&gt;
In video 1, &lt;a href=&quot;https://youtu.be/J01u_Dmrx5U&quot;&gt;https://youtu.be/J01u_Dmrx5U&lt;/a&gt;, I showed how you can use
Scala 3 features like Context Functions to pass context around. The
eval function below is an expression evaluator that takes expressions
of type &lt;code&gt;Exp&lt;/code&gt;, returns a result of type &lt;code&gt;Int&lt;/code&gt; and has an implicit
environment &lt;code&gt;Env&lt;/code&gt; which is a symbol table of values.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt; ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;eval&lt;/span&gt;(exp&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  exp &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt;
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;id&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleVar(id)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; value
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleAdd(l,r)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;(s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  summon[&lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;].get(s).get
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This is a nice example of context functions, but not so good an
example of a pure functional program, let&apos;s see why.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org1650438&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org1650438&quot;&gt;Purity&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org1650438&quot;&gt;
&lt;p&gt;
What is a pure function? In short it has three properties&amp;#x2026; it is a
total function, it is deterministic and it has no side effects.
&lt;/p&gt;

&lt;p&gt;
A &lt;code&gt;total function&lt;/code&gt; has an answer (of a fixed type) for everything. Our
expression evaluator is a total function because every expression you
put in can be evaluated and returns a value. Now let&apos;s say we had a
divide function, and you can pass in a divisor that is zero and the
answer is infinity. That is not representable by Int so the function
is not total. We can only throw an error at this point.
&lt;/p&gt;

&lt;p&gt;
By &lt;code&gt;deterministic&lt;/code&gt;, we mean that the evaluator gives the same answer for
every input expression, which may seem self-evident, but imagine if we
had a random number command. When used it would return different
answers every time and the program would not be deterministic.
&lt;/p&gt;

&lt;p&gt;
Finally, by &lt;code&gt;no side effects&lt;/code&gt;, we mean the program does nothing
impure. It is not going to print to the screen, send an email, or
throw errors.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgb716616&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb716616&quot;&gt;Is the expression evaluator code pure?&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb716616&quot;&gt;
&lt;p&gt;
If your nose wrinkled when you saw this code above
&lt;code&gt;summon[Env].get(s).get&lt;/code&gt; then you&apos;re probably an experienced Scala
programmer who knows that you should not call get on an option.
&lt;/p&gt;

&lt;p&gt;
What&apos;s happening there is a symbol table look up. First I &apos;summon&apos; the
symbol table (see video 1 to understand context functions and where
the symbol table is coming from), then I look up the symbol using
&lt;code&gt;get&lt;/code&gt;. This returns an &lt;code&gt;Option&lt;/code&gt; because the symbol may be missing!
&lt;/p&gt;

&lt;p&gt;
I hopefully pointed out at the time that you shouldn&apos;t call &lt;code&gt;get&lt;/code&gt; on
an Option in serious code because it will throw an error. That means
that as a program that can throw errors, our program is not pure.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org21a7f0e&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org21a7f0e&quot;&gt;Handling errors with Either&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org21a7f0e&quot;&gt;
&lt;p&gt;
Since the 90s the Haskell folk have been dealing with impurity by
wrapping it up in data types that describe the effects, and
manipulating them with type classes. If that sounds hopelessly
abstract, then fear not, in practise it&apos;s quite simple and we will fix
our problems with a few lines of code.
&lt;/p&gt;

&lt;p&gt;
Firstly let&apos;s look at what we mean by a data type&amp;#x2026; it is usually a
higher kinded type that &quot;contains&quot; things of another type that you can
define at compile time.
&lt;/p&gt;

&lt;p&gt;
Scala&apos;s Either is a great example of a data type. It encodes the
concept of errors. Our pure code does not deal with errors but we can
still encode errors by wrapping them as follows.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e2&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Oops&quot;&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
By encoding our values like this we can represent a computation that
has succeeded as a &lt;code&gt;Right&lt;/code&gt; value, and a computation that has failed
with some error as a &lt;code&gt;Left&lt;/code&gt; value.
&lt;/p&gt;

&lt;p&gt;
What this means is we can no longer apply pure functions these values
directly. That is sort of the point. What we wanted to do was isolate
pure functions from having to deal with errors at all. So how do we
operate on Eithers? Well you are probably familiar with the &lt;code&gt;map&lt;/code&gt;
function, and that can be used to apply a pure function to an either!
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e3&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e1.map(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Right(11)&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e4&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e2.map(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Left(&quot;Oops&quot;)&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org203832a&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org203832a&quot;&gt;Categorically Speaking&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org203832a&quot;&gt;
&lt;p&gt;
You may not really think of it as Category Theory, but whenever you
map an Either you are using Functors!
&lt;/p&gt;

&lt;p&gt;
The Haskell documentation is a nice place to learn about Functors. If
you think of a normal pure function as a mapping of values from A to
B, a Functor can map values that have been embellished, or wrapped in
some special data type.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://wiki.haskell.org/Functor&quot;&gt;https://wiki.haskell.org/Functor&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Helpfully, the kind folks behind Scala 3 have added how to implement
type classes to their documentation. We can use that a starting point
to build our own Functor and then make an instance that works with
Eithers.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;trait&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Functor&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;]]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
  extension [&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](x&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;ffmap&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;F&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
This is all we need to define a Functor type class that can extend
supported types with a map function. Note that I&apos;ve added an f to
differentiate the function from the built in map. Then I added another
f by mistake, don&apos;t tell anyone, they might not notice!
&lt;/p&gt;

&lt;p&gt;
Before we can use this against an Either we need to implement an
instance of the typeclass. Remember that Functor needs a type of kind
&lt;code&gt;F[_]&lt;/code&gt;. It has one &quot;type hole&quot;. Either has two, which is not going to
work, so let&apos;s start by specialising to Either with only a fixed error
type of String.
&lt;/p&gt;

&lt;p&gt;
First we make a type alias that reduces the Either to one unknown
type, the computation result type &lt;code&gt;A&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Next we provide an implementation of ffmap that does the work of
mapping our pure function over an Either.
&lt;/p&gt;

&lt;p&gt;
Note that this is roughly the same as the pure function. Instead of &lt;code&gt;A
=&amp;gt; B&lt;/code&gt; we are mapping &lt;code&gt;F[A] =&amp;gt; F[B]&lt;/code&gt; where F is the Either.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;StringEither&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]

given &lt;span style=&quot;color: #00bcff;&quot;&gt;Functor&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;StringEither&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt;
  extension [&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](x&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;StringEither&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;ffmap&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;StringEither&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
      x &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
        &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(f(a))
        &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;err&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(err)
      }
    }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Let&apos;s try it out.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e2&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Oops&quot;&lt;/span&gt;)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e3&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e1.ffmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Right(11)&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e4&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e2.ffmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Left(&quot;Oops&quot;)&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
We can now apply pure functions to Eithers with String error
types. Where we want to get to is to be able to apply pure functions
to &lt;code&gt;Either[Error,Numeric[A]]&lt;/code&gt; so we&apos;re not quite there yet.
&lt;/p&gt;

&lt;p&gt;
The first problem is that we can&apos;t handle the Error type that I want
to use in my expression evaluator, we can only handle String. Well we
can just make another instance of Functor for &lt;code&gt;Either[Error,A]&lt;/code&gt;?
&lt;/p&gt;

&lt;p&gt;
Well, yes we could, but how about we make a generic instance of
Functor for &lt;code&gt;all&lt;/code&gt; Eithers?
&lt;/p&gt;

&lt;p&gt;
To do that we need to use type lambdas. These were available in Scala
2 but are greatly simplified in Scala 3.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/new-types/type-lambdas.html&quot;&gt;https://dotty.epfl.ch/docs/reference/new-types/type-lambdas.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Here&apos;s the new instance for Functor with some notable changes.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span class=&quot;linenr&quot;&gt;1: &lt;/span&gt;given eitherFunctor[&lt;span style=&quot;color: #00bcff;&quot;&gt;E&lt;/span&gt;]&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Functor&lt;/span&gt;[[&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;] =&amp;gt;&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;E&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;with&lt;/span&gt;
&lt;span class=&quot;linenr&quot;&gt;2: &lt;/span&gt;  extension [&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;](x&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;E&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;A&lt;/span&gt;])
&lt;span class=&quot;linenr&quot;&gt;3: &lt;/span&gt;      &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;ffmap&lt;/span&gt;(f&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;A&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;E&lt;/span&gt;,&lt;span style=&quot;color: #00bcff;&quot;&gt;B&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
&lt;span class=&quot;linenr&quot;&gt;4: &lt;/span&gt;        x &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
&lt;span class=&quot;linenr&quot;&gt;5: &lt;/span&gt;          &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;a&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(f(a))
&lt;span class=&quot;linenr&quot;&gt;6: &lt;/span&gt;          &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;err&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(err)
&lt;span class=&quot;linenr&quot;&gt;7: &lt;/span&gt;        }
&lt;span class=&quot;linenr&quot;&gt;8: &lt;/span&gt;      }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Line 1 is where the action is. First note that we named the given
instance &lt;code&gt;eitherFunctor&lt;/code&gt;. Our previous instance had no name. You &lt;code&gt;can&lt;/code&gt;
leave the name out, but it&apos;s not recommended, especially for
libraries, since it makes the code easier to work with. See also that
the instance itself takes parameter &lt;code&gt;E&lt;/code&gt; which will represent our error
type.
&lt;/p&gt;

&lt;p&gt;
Next the instance of Functor is for the type &lt;code&gt;[A] =&amp;gt;&amp;gt; Either[E, A]&lt;/code&gt;
which is our type lambda. It means please give me a type that has a
single parameter A but that will be substituted into the &lt;code&gt;Either[E,A]&lt;/code&gt;
in a way that is similar to how parameters are substituted into a
lambda function.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e1&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Right&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e2&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Either&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Left&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e3&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e1.ffmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Right(11)&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;e4&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e2.ffmap(a &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; a + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;) &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Left(1)&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now we can map over any type of Either! As you can see in the first
case the pure function mapped over the A. In the second case the pure
function was not executed and the error value is simply passed along.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org837bdc6&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org837bdc6&quot;&gt;Functor Laws&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org837bdc6&quot;&gt;
&lt;p&gt;
Next time we&apos;ll look at the Functor laws and show that our code obeys them.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgb73242c&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb73242c&quot;&gt;Wrap up&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb73242c&quot;&gt;
&lt;p&gt;
I hope you enjoyed this blog and/or video. Please share, like or
subscribe and help me spread this content to those that may find it
useful.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org00245d4&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org00245d4&quot;&gt;For further info&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org00245d4&quot;&gt;
&lt;p&gt;
Source code
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/evalexample&quot;&gt;https://github.com/justinhj/evalexample&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Read more
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/new-types/type-lambdas.html&quot;&gt;https://dotty.epfl.ch/docs/reference/new-types/type-lambdas.html&lt;/a&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/contextual/extension-methods.html&quot;&gt;https://dotty.epfl.ch/docs/reference/contextual/extension-methods.html&lt;/a&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/contextual/type-classes.html&quot;&gt;https://dotty.epfl.ch/docs/reference/contextual/type-classes.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&amp;copy; 2020 Justin Heyes-Jones. All Rights Reserved.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Wed, 06 Jan 2021 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2021/01/06/handling-errors-functionaly-with-scala-3.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2021/01/06/handling-errors-functionaly-with-scala-3.html</guid>
        
        <category>scala</category>
        
        <category>scala-3</category>
        
        <category>dotty</category>
        
        
      </item>
    
      <item>
        <title>Type classes with Scala 2</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;
&lt;p&gt;
&lt;img src=&quot;/../images/crissy-jarvis-cHhbULJbPwM-unsplash-small.jpg&quot; alt=&quot;A colourful abascus&quot; title=&quot;Abacus&quot; /&gt;
&lt;/p&gt;
&lt;span&gt;Photo by &lt;a href=&quot;https://unsplash.com/@crissyjarvis?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText&quot;&gt;Crissy Jarvis&lt;/a&gt; on &lt;a href=&quot;https://unsplash.com/s/photos/abacus?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText&quot;&gt;Unsplash&lt;/a&gt;&lt;/span&gt;

&lt;div id=&quot;outline-container-orge38ea18&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orge38ea18&quot;&gt;Make your own Numeric type class&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orge38ea18&quot;&gt;
&lt;p&gt;
This is the companion blog for a Functional Justin video which you can
find here &lt;a href=&quot;https://youtu.be/pJFfXhZlR5o&quot;&gt;https://youtu.be/pJFfXhZlR5o&lt;/a&gt;. This is a series of
coffee-break sized videos that each explore a topic in the world of
Scala Functional Programming.
&lt;/p&gt;

&lt;p&gt;
In this video I talk about Type classes and here is the blog version for those that would rather read.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orge66e206&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orge66e206&quot;&gt;What are type classes&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orge66e206&quot;&gt;
&lt;p&gt;
Here are some good references for reading about type classes in Scala (they can of course be implemented in other functional programming languages).
&lt;/p&gt;

&lt;p&gt;
Sam Halliday has a great introduction to data types and type classes in his book Functional Programming for Mortals.
&lt;a href=&quot;https://leanpub.com/fpmortals/read#leanpub-auto-data-and-functionality&quot;&gt;https://leanpub.com/fpmortals/read#leanpub-auto-data-and-functionality&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
This idea of separating data from functions can also be found in the Cats functional programming library, with the library itself being organised into distinct sections for data types and type classes.
&lt;a href=&quot;https://typelevel.org/cats/typeclasses.html&quot;&gt;https://typelevel.org/cats/typeclasses.html&lt;/a&gt;
&lt;a href=&quot;https://typelevel.org/cats/datatypes&quot;&gt;https://typelevel.org/cats/datatypes&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
My former colleague and functional programming advocate Francis Toth also has a nice blog on this topic.
&lt;a href=&quot;https://contramap.dev/2020/04/09/typeclasses.html&quot;&gt;https://contramap.dev/2020/04/09/typeclasses.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
In my own words, type classes are not explicitly part of the Scala
language, but are rather a pattern of implementation that enable you
to define behaviours which can then be implemented for data
types. Data types are values like strings and numbers, collections
like lists and sets and &quot;higher kinded types&quot; like IO, ZIO and so on.
&lt;/p&gt;

&lt;p&gt;
Type classes do not have to be implemented a certain way, but in Cats,
Scalaz and other libraries you will find them implemented just as they
are here, but additional layers of complexity to manage things like
stack safety and take advantage of tools to generate boilerplate code.
&lt;/p&gt;

&lt;p&gt;
In general type classes consist of:
&lt;/p&gt;

&lt;ul class=&quot;org-ul&quot;&gt;
&lt;li&gt;A trait that has one, or sometimes more, type parameters.&lt;/li&gt;
&lt;li&gt;It contains one or more abstract methods. These define behaviours that must be implemented for each &lt;code&gt;instance&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Also you will find generalized methods that are built using the abstract ones.&lt;/li&gt;
&lt;li&gt;Typically a type class contains no data&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org6576dab&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org6576dab&quot;&gt;Numeric&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org6576dab&quot;&gt;
&lt;p&gt;
In the video I implemented the Numeric type class. What is Numeric? It
is a type class you&apos;ll find in the Scala standard library and is used
to build a generic representation of numbers.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://www.scala-lang.org/api/current/scala/math/Numeric.html&quot;&gt;https://www.scala-lang.org/api/current/scala/math/Numeric.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
What I develop here is just enough that we can use it for the
expression evaluator in the first video (which only requires add and
multiply operations).
&lt;/p&gt;

&lt;p&gt;
You can find the complete code here
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/evalexample/blob/master/src/main/scala/Scala2Numeric.scala&quot;&gt;https://github.com/justinhj/evalexample/blob/master/src/main/scala/Scala2Numeric.scala&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Let&apos;s look at the pieces one by one&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;trait&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;] {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;Add&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;, b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;Mul&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;, b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;square&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; mul(a, a)
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here we define the trait which decribes the core of our type class;
what it can do, and what you need to implement if you want your data
type to be an instance of this typeclass.
&lt;/p&gt;

&lt;p&gt;
Add and Mul are abstract, whilst the square function is derived or
generalized and does not need to be implemented when making new
supported instances.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org059d026&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org059d026&quot;&gt;Instances&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org059d026&quot;&gt;
&lt;p&gt;
Once you have the interface for your type class you can define instances for various data types. Here we define the instance for &lt;code&gt;Long&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;numericLong&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Long&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Long&lt;/span&gt;] {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Long&lt;/span&gt;, b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Long&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Long&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a + b
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mul&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Long&lt;/span&gt;, b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Long&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Long&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a * b
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that this is implicit to make it easier to use our instances with
other types, taking advantage of the fact that users can import the
definititions and then use them in their code.
&lt;/p&gt;

&lt;p&gt;
Here&apos;s an example function that is written using the Numeric type
class as a parameter. This function displays what we call &lt;code&gt;ad-hoc
polymorphism&lt;/code&gt;, in that this function does not know all of the
instances that exist for the input type &lt;code&gt;T&lt;/code&gt;, nor does it need to. All
it knows is that to do its work it needs an instance of &lt;code&gt;Numeric[T]&lt;/code&gt;
so that it can access the &lt;code&gt;add&lt;/code&gt; method.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;sumList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;](ts&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;])(&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; numeric&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  ts.reduce((a, b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; numeric.&lt;span style=&quot;color: #00bcff;&quot;&gt;Add&lt;/span&gt;(a,b))
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now we can sum a list of any &lt;code&gt;T&lt;/code&gt; where T has a Numeric instance. Here we use the Int instance (not shown).
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;l1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;List&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;3&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;4&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;sum&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; sumList(l1)

println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;sum of int list is &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$sum&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;sum of int list is 10&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org645a66c&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org645a66c&quot;&gt;Improving the ergonomics&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org645a66c&quot;&gt;
&lt;p&gt;
So that&apos;s all you need to build type classes but we can take a couple
of steps to make things more ergonomic. For one we can ditch the
implicit parameter and instead make use of
[[&lt;a href=&quot;https://docs.scala-lang.org/tutorials/FAQ/context-bounds.html&quot;&gt;https://docs.scala-lang.org/tutorials/FAQ/context-bounds.html&lt;/a&gt;]context
bounds]]. This makes things clearer for the caller of the function.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;sumList&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;](ts&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;List&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;])&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;numeric&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; implicitly[&lt;span style=&quot;color: #00bcff;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;]]
  ts.reduce((a, b) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; numeric.add(a,b))
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that we have to &lt;code&gt;summon&lt;/code&gt; the implicit Numeric instance using
&lt;code&gt;implicitly&lt;/code&gt;. This is a function in the standard library which takes
advantage of the way context bounds work: the context bound &lt;code&gt;Numeric&lt;/code&gt;
specifies that there is an implicit Numeric instance in scope, but
there is no named parameter as before. The implicitly function lets
us access that implicit in a succinct way.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;implicitly&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;](&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; e&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; e
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
So using context bounds helps a little with the use of type classes,
the next step is to use implicit conversions so that we take the
functions in our type class and make them look like ordinary methods
on the data type.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ops&lt;/span&gt; {

  &lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;NumericOps&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;](a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)(&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; numeric&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;]) {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; numeric.add(a, b)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mul&lt;/span&gt;(b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; numeric.mul(a, b)

    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;+&lt;/span&gt;(b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; add(b)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;*&lt;/span&gt;(b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;T&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; mul(b)
  }

}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now if we import ops we can take advantage of the implicit conversion from type T to type NumericOps[T] to give us syntax like below.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;s1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;abcd&quot;&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;s2&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;efgh&quot;&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;product&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; s1 * s2
println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;product &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$product&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;product aeafagahbebfbgbhcecfcgchdedfdgdh&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
So you can see that by implementing a somewhat goofy instance of
Numeric for string (given below) we now have the ability to use the
multiplication operator on it as if it was a regular number.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;stringNumeric&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Numeric&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;] {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;add&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;, b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; a + b

    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;mul&lt;/span&gt;(a&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;, b&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;for&lt;/span&gt; (
      as &lt;span style=&quot;color: #b6a0ff;&quot;&gt;&amp;lt;-&lt;/span&gt; a;
      bs &lt;span style=&quot;color: #b6a0ff;&quot;&gt;&amp;lt;-&lt;/span&gt; b;
      s &lt;span style=&quot;color: #b6a0ff;&quot;&gt;&amp;lt;-&lt;/span&gt; as.toString ++ bs.toString) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;yield&lt;/span&gt; s
  }
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that while this implentation of string arithmetic is not very
rigorous and just for fun, there&apos;s nothing to stop you from
implementing Numeric for data types that do have well defined
arithmetic operations such as Roman Numerals.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org40f4c54&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org40f4c54&quot;&gt;Coherence&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org40f4c54&quot;&gt;
&lt;p&gt;
Type class coherence is an important concept I&apos;ll leave you with. This
is a guideline in place to keep programs easy to reason about. It&apos;s a
good practice to keep common instances together with your type classes
so that users can easily find them, and don&apos;t duplicate the work. It&apos;s
also important that you don&apos;t try to make multiple instances and let
the users select one depending on their needs. The reason for that is
the behaviour of your program can change profoundly when you do this,
and that&apos;s terrible. It means you can&apos;t take advantage of &lt;code&gt;local
reasoning&lt;/code&gt;, one of the benefits of functional programming. You would
need to be very careful with imports to make sure you are using the
instance you think you are.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgc682686&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgc682686&quot;&gt;Final words&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgc682686&quot;&gt;
&lt;p&gt;
If you&apos;re coming from Java or similar OOP language you may recognise
some of this as the adapter pattern (except with Scala
implicits). Type class traits also have similarities to Go interfaces,
although the type class pattern goes a bit beyond them in scope.
&lt;/p&gt;

&lt;p&gt;
I would be amiss not to mention Haskell here, which has type classes
implemented as a first-class language construct, and for some people
the over-use of type classes in Scala is somewhat of an
anti-pattern. We will see in future videos that the pattern will be
greatly simplified in Scala 3 however.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgc07e8a4&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgc07e8a4&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgc07e8a4&quot;&gt;
&lt;p&gt;
Typelevel Cats functional programming library documentation
&lt;a href=&quot;https://typelevel.org/cats/&quot;&gt;https://typelevel.org/cats/&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Functional Programming for Mortals
&lt;a href=&quot;https://leanpub.com/fpmortals&quot;&gt;https://leanpub.com/fpmortals&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&amp;copy; 2020 Justin Heyes-Jones. All Rights Reserved.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Sun, 06 Dec 2020 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2020/12/06/type-classes-scala-2.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2020/12/06/type-classes-scala-2.html</guid>
        
        <category>scala</category>
        
        <category>functional-programming</category>
        
        
      </item>
    
      <item>
        <title>Scala 3 Context Functions</title>
        <description>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../../_orgcss/site.css&quot; /&gt;
&lt;div id=&quot;outline-container-orgf6c3f62&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgf6c3f62&quot;&gt;Some Scala 3 Things: Context functions, Enums and significant whitespace&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgf6c3f62&quot;&gt;
&lt;p&gt;
&lt;code&gt;Updated: for Scala 3.0.0-M3 `as` keyword was removed&lt;/code&gt;
&lt;/p&gt;

&lt;p&gt;
This is the companion blog for my first Functional Justin video which you can find here &lt;a href=&quot;https://youtu.be/J01u_Dmrx5U&quot;&gt;https://youtu.be/J01u_Dmrx5U&lt;/a&gt;. I spend around 15 minutes adding some Scala 3 (formerly Dotty) features to an Scala 2 program.
&lt;/p&gt;

&lt;p&gt;
The program itself builds a simple Algebraic Data Type (ADT) to represent a simple arithmetic expressions. We can then build expressions in this &lt;code&gt;algebra&lt;/code&gt; and evaluate it using an eval function using pattern matching&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;sealed&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;trait&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(value&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(left&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, right&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Mul&lt;/span&gt;(left&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, right&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;class&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(identifier&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Now given an expression like &lt;code&gt;Mul(Var(&quot;z&quot;), Add(Val(30), Mul(Var(&quot;x&quot;), Var(&quot;y&quot;))))&lt;/code&gt; I&apos;d like to be able to recursively traverse it and calculate a final Int value at the end.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;Val&lt;/code&gt; represents an Int value, whilst &lt;code&gt;Add&lt;/code&gt; and &lt;code&gt;Mul&lt;/code&gt; take care of addition and multiplication. You could go ahead and add more functions. &lt;code&gt;Var&lt;/code&gt; is interesting because it takes an a string identifier (i.e., a variable name) and will look it up in an environment. The environment is represented a Scala map of String to Int.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;String&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
For the eval function we just use a pattern match to dispatch to functions that handle each particular operation. These handler functions and eval are &lt;code&gt;mutally recursive&lt;/code&gt;, and note that every function has to have the &lt;code&gt;Env&lt;/code&gt; passed to it as an implicit parameter, yet only &lt;code&gt;Var&lt;/code&gt; needs it. This will be important later.
&lt;/p&gt;

&lt;p&gt;
Here&apos;s the eval function and handlers.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;eval&lt;/span&gt;(exp&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)(&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; env &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
  exp &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;id&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleVar(id)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; value
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleAdd(l,r)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleMul(l,r)
  }
}

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleAdd&lt;/span&gt;(l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)(&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; env &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) + eval(r)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleMul&lt;/span&gt;(l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)(&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; env &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) * eval(r)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;(s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)(&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; env&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; env.getOrElse(s, &lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Note that we could have inlined these functions in eval, but it a larger example it&apos;s important to break things out to keep things managable.
&lt;/p&gt;

&lt;p&gt;
That is all the implementation we need, and all that remains is to create an expression, create an environment (declared implicit so Scala knows to include it as an implicit when eval is called) and print the result of evaluating the expression.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;exp1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;30&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Mul&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt;))))

&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;17&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;)
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;eval1&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(exp1)

println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Eval exp gives &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$eval1&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
You can compile and run the code to see this working. The code is here. &lt;a href=&quot;https://github.com/justinhj/evalexample/blob/master/src/main/scala/Scala2Eval.scala&quot;&gt;https://github.com/justinhj/evalexample/blob/master/src/main/scala/Scala2Eval.scala&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgb5b329b&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgb5b329b&quot;&gt;Fun with Enum&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgb5b329b&quot;&gt;
&lt;p&gt;
Scala enums have been improved greatly. For one they are very simple to create and use just as in other languages.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;StatusCode&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt;
   &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;OK&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;TimedOut&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Error&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here we&apos;ve defined three enums that have ordinal values 0 to 2. You can access the ordinal value with the &lt;code&gt;.ordinal&lt;/code&gt; method, convert ordinal values to Enums using &lt;code&gt;.fromOrdinal&lt;/code&gt; and convert Strings to enums (assuming they match) with &lt;code&gt;.valueOf&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Ordinal value of StatusCode.Error is &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;${StatusCode.Error.ordinal}&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;StatusCode from ordinal 1 is &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;${StatusCode.fromOrdinal(1)}&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;StatusCode from string OK is &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;${StatusCode.valueOf(&quot;OK&quot;)}&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)

&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Ordinal value of StatusCode.Error is 2&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;StatusCode from ordinal 1 is TimedOut&lt;/span&gt;
&lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;StatusCode from string OK is OK&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
You can also add your own parameters and definitions to enums. The underlying ordinal values are still there. For example you could encode Http Status codes as follows.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;HttpStatusCode&lt;/span&gt;(code&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;OK&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;HttpStatusCode&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;200&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;NotModified&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;HttpStatusCode&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;304&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Forbidden&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;HttpStatusCode&lt;/span&gt;(&lt;span style=&quot;color: #00bcff;&quot;&gt;404&lt;/span&gt;)

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;isSuccess&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; code &amp;gt;= &lt;span style=&quot;color: #00bcff;&quot;&gt;200&lt;/span&gt; &amp;amp;&amp;amp; code &amp;lt; &lt;span style=&quot;color: #00bcff;&quot;&gt;300&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Scala 3 team also took the opportunity to make Enums &lt;code&gt;a more concise notation for ADTs and GADTs&lt;/code&gt;. For our purposes that means we can simply the definition of &lt;code&gt;Exp&lt;/code&gt; as follows.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;Exp&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, &lt;span style=&quot;color: #00d3d0;&quot;&gt;right&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;identifier&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;
}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
In fact you can further simplify to the following (you could also remove the braces).
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;enum &lt;span style=&quot;color: #00bcff;&quot;&gt;Exp&lt;/span&gt; {
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, &lt;span style=&quot;color: #00d3d0;&quot;&gt;right&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;identifier&lt;/span&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orgf9c19ca&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orgf9c19ca&quot;&gt;Explicit implicits&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orgf9c19ca&quot;&gt;
&lt;p&gt;
A focus of the Scala 3 team is to help beginners access the language and in particular simplifying implicits. There are many subtle changes here but two obvious ones are that you now have different keywords for implicit parameters and creating implicit instances. In our code this means that when we supply the implicit symbol table to eval we now use the new &lt;code&gt;given&lt;/code&gt; syntax instead of &lt;code&gt;implicit&lt;/code&gt;.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #f78fe7;&quot;&gt;implicit&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;17&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;2&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
becomes&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;given envMap&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Map&lt;/span&gt;(&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;x&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;7&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;y&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;6&lt;/span&gt;, &lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;z&quot;&lt;/span&gt; -&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;22&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Similarly, the method parameters now no longer use the implicit keyword and instead you prefix the parameter name with &lt;code&gt;using&lt;/code&gt;.
&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
def eval(exp: Exp)(implicit env : Env): Int
&lt;/pre&gt;

&lt;p&gt;
becomes&amp;#x2026;
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;eval&lt;/span&gt;(exp&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)(using env &lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Env&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
You don&apos;t have to change your Scala 2 code at this point, it is still compatible, but for new code and in the long term you should gradually eliminate implicit.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org08f0809&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org08f0809&quot;&gt;Context Functions&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org08f0809&quot;&gt;
&lt;p&gt;
Last and not at all least are context functions. This gives us one more opportunity to remove boiler plate from the eval code. When you create a regular function value it has a type like &lt;code&gt;Function1[A,B]&lt;/code&gt;. In other words it is a function that takes a value A and returns vale of type B. Context Functions are a new function value type (this is synthesized by the compiler so you won&apos;t see it your code), with an input and an output type. The difference is that the input is understood to be provided implicitly.
&lt;/p&gt;

&lt;p&gt;
Let&apos;s make this more concrete. Assume you have a function that needs an &lt;code&gt;ExecutionContext&lt;/code&gt;. We can make a Context Function type that will take an implicit execution context and return some paramaterized type T.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Executable&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ExecutionContext&lt;/span&gt; ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
How would that be used in a real program? Let&apos;s say you have some deeply nested function (f4 in the code below) and it is only down at that level you need the implicit execution context. Without implicit parameters you&apos;d add the ExecutionContext parameter to every single function call all the way down and then have to take care to pass it along. With Scala 2 implicits you still have to declare the parameter but you can make it implicit and avoid the burden of manually passing it along.
&lt;/p&gt;

&lt;p&gt;
With Scala 3 you can define the function to be of type &lt;code&gt;Executable[T]&lt;/code&gt; and then we don&apos;t need to even name the implicit parameter, we just know that it will be included automatically all the way down. Here is a complete example.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;import&lt;/span&gt; scala.concurrent.{&lt;span style=&quot;color: #00bcff;&quot;&gt;Future&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;ExecutionContext&lt;/span&gt;, &lt;span style=&quot;color: #00bcff;&quot;&gt;Await&lt;/span&gt;}
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;import&lt;/span&gt; scala.concurrent.duration.&lt;span style=&quot;color: #b6a0ff;&quot;&gt;_&lt;/span&gt;
&lt;span style=&quot;color: #b6a0ff;&quot;&gt;import&lt;/span&gt; scala.language.postfixOps

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Executable&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;extends&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;App&lt;/span&gt; {

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Executable&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;ExecutionContext&lt;/span&gt; ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;T&lt;/span&gt;

  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;f1&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Executable&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Future&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; f2(n + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;f2&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Executable&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Future&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; f3(n + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;f3&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Executable&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Future&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; f4(n + &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt;)
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;f4&lt;/span&gt;(n&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Int&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Executable&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Future&lt;/span&gt;[&lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;]] &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;ex&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; summon[&lt;span style=&quot;color: #00bcff;&quot;&gt;ExecutionContext&lt;/span&gt;]
    &lt;span style=&quot;color: #00bcff;&quot;&gt;Future&lt;/span&gt; {
      println(s&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;Hi from the future! n is &lt;/span&gt;&lt;span style=&quot;color: #00d3d0;&quot;&gt;$n&lt;/span&gt;&lt;span style=&quot;color: #79a8ff;&quot;&gt;&quot;&lt;/span&gt;)
      n
    }
  }

  {
    given ec&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;ExecutionContext&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; scala.concurrent.&lt;span style=&quot;color: #00bcff;&quot;&gt;ExecutionContext&lt;/span&gt;.global
    &lt;span style=&quot;color: #00bcff;&quot;&gt;Await&lt;/span&gt;.result(f1(&lt;span style=&quot;color: #00bcff;&quot;&gt;10&lt;/span&gt;), &lt;span style=&quot;color: #00bcff;&quot;&gt;1&lt;/span&gt; second)
    &lt;span style=&quot;color: #a8a8a8;&quot;&gt;// &lt;/span&gt;&lt;span style=&quot;color: #a8a8a8;&quot;&gt;Hi from the future! n is 13&lt;/span&gt;
  }

}
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Context functions reduce boilerplate when dealing with implicit parameters in deeply nested code. We can apply this technique to our eval function so that the symbol table itself is the implicit piece of context.
&lt;/p&gt;

&lt;div class=&quot;org-src-container&quot;&gt;
&lt;pre class=&quot;src src-scala&quot;&gt;&lt;span style=&quot;color: #b6a0ff;&quot;&gt;type&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt; ?=&amp;gt; &lt;span style=&quot;color: #00bcff;&quot;&gt;Int&lt;/span&gt;

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;eval&lt;/span&gt;(exp&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  exp &lt;span style=&quot;color: #b6a0ff;&quot;&gt;match&lt;/span&gt; {
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Var&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;id&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleVar(id)
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Val&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;value&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; value
    &lt;span style=&quot;color: #b6a0ff;&quot;&gt;case&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Add&lt;/span&gt;(&lt;span style=&quot;color: #00d3d0;&quot;&gt;l&lt;/span&gt;,&lt;span style=&quot;color: #00d3d0;&quot;&gt;r&lt;/span&gt;) &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&amp;gt;&lt;/span&gt; handleAdd(l,r)
  }

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleAdd&lt;/span&gt;(l&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;, r&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;Exp&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; eval(l) + eval(r)

&lt;span style=&quot;color: #b6a0ff;&quot;&gt;def&lt;/span&gt; &lt;span style=&quot;color: #feacd0;&quot;&gt;handleVar&lt;/span&gt;(s&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;String&lt;/span&gt;)&lt;span style=&quot;color: #b6a0ff;&quot;&gt;:&lt;/span&gt; &lt;span style=&quot;color: #6ae4b9;&quot;&gt;WithEnv&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt;
  &lt;span style=&quot;color: #b6a0ff;&quot;&gt;val&lt;/span&gt; &lt;span style=&quot;color: #00d3d0;&quot;&gt;env&lt;/span&gt; &lt;span style=&quot;color: #b6a0ff;&quot;&gt;=&lt;/span&gt; summon[&lt;span style=&quot;color: #00bcff;&quot;&gt;Env&lt;/span&gt;]
  env.getOrElse(s, &lt;span style=&quot;color: #00bcff;&quot;&gt;0&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
You can take a look at the final Scala 3 version of the code here.
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/justinhj/evalexample/blob/master/src/main/scala/Scala3Eval.scala&quot;&gt;https://github.com/justinhj/evalexample/blob/master/src/main/scala/Scala3Eval.scala&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-org7baa236&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;org7baa236&quot;&gt;Final notes&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-org7baa236&quot;&gt;
&lt;p&gt;
Of all the new features in Scala 3, I found Context Functions of most interest because of Martin Odersky&apos;s blog from 2016 &lt;a href=&quot;https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html&quot;&gt;https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html&lt;/a&gt; where this intriguing quote appears near the end. (Context functions were initially known as implicit functions).
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
There are many interesting connections with category theory to explore here. On the one hand, implicit functions are used for tasks that are sometimes covered with monads such as the reader monad. There’s an argument to be made that implicits have better composability than monads and why that is.
&lt;/p&gt;

&lt;p&gt;
On the other hand, it turns out that implicit functions can also be given a co-monadic interpretation, and the interplay between monads and comonads is very interesting in its own right.
&lt;/p&gt;

&lt;p&gt;
But these discussions will have to wait for another time, as this blog post is already too long.
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Somewhat of a Fermat&apos;s last theorem moment there, and I am also interested in how we can represent concepts, that are currently implemented in libraries which model category theory, using vanilla Scala 3 or alternative representations.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;outline-container-orga7482f9&quot; class=&quot;outline-2&quot;&gt;
&lt;h2 id=&quot;orga7482f9&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;outline-text-2&quot; id=&quot;text-orga7482f9&quot;&gt;
&lt;p&gt;
&lt;a href=&quot;https://en.wikiquote.org/wiki/Pierre_de_Fermat&quot;&gt;https://en.wikiquote.org/wiki/Pierre_de_Fermat&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/enums/enums.html&quot;&gt;https://dotty.epfl.ch/docs/reference/enums/enums.html&lt;/a&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/enums/adts.html&quot;&gt;https://dotty.epfl.ch/docs/reference/enums/adts.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;http://dotty.epfl.ch/docs/reference/other-new-features/indentation.html&quot;&gt;http://dotty.epfl.ch/docs/reference/other-new-features/indentation.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/contextual/givens.html&quot;&gt;https://dotty.epfl.ch/docs/reference/contextual/givens.html&lt;/a&gt; &lt;a href=&quot;https://dotty.epfl.ch/docs/reference/contextual/using-clauses.html&quot;&gt;https://dotty.epfl.ch/docs/reference/contextual/using-clauses.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://dotty.epfl.ch/docs/reference/contextual/context-functions.html&quot;&gt;https://dotty.epfl.ch/docs/reference/contextual/context-functions.html&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Foundations and Applications of Implicit Function Types
&lt;a href=&quot;https://infoscience.epfl.ch/record/229878/files/simplicitly_1.pdf&quot;&gt;https://infoscience.epfl.ch/record/229878/files/simplicitly_1.pdf&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;http://recurse.se/2019/09/implicit-functions-in-scala-3/&quot;&gt;http://recurse.se/2019/09/implicit-functions-in-scala-3/&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
&amp;copy; 2020 Justin Heyes-Jones. All Rights Reserved.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
        <pubDate>Wed, 18 Nov 2020 00:00:00 +0000</pubDate>
        <link>http://justinhj.github.io/2020/11/18/scala-3-context-functions.html</link>
        <guid isPermaLink="true">http://justinhj.github.io/2020/11/18/scala-3-context-functions.html</guid>
        
        <category>scala</category>
        
        <category>scala-3</category>
        
        <category>dotty</category>
        
        
      </item>
    
  </channel>
</rss>
