{"@attributes":{"version":"2.0"},"channel":{"title":"Functional[Justin]","description":"Principal Software Engineer. Streaming data at scale. Generative AI. Functional Programming. Neovim. Emacs.","link":"http:\/\/justinhj.github.io\/","pubDate":"Sun, 15 Nov 2026 04:47:44 +0000","lastBuildDate":"Sun, 15 Nov 2026 04:47:44 +0000","generator":"Jekyll v3.10.0","item":[{"title":"Refreshing your Neovim config for 0.12.0","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n\n<div id=\"outline-container-org12a1d94\" class=\"outline-2\">\n<h2 id=\"org12a1d94\">Introduction<\/h2>\n<div class=\"outline-text-2\" id=\"text-org12a1d94\">\n<p>\nNeovim version 0.12.1 was just released and you can check the release news here:\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/neovim\/neovim\/blob\/v0.12.1\/runtime\/doc\/news.txt\">Neovim v0.12.1 release news<\/a>\n<\/p>\n\n<p>\nThis 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.\n<\/p>\n\n<p>\nRather 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't even using such as luasnip (hrsh7th\/nvim-cmp won't work without a snippets plugin whether you want one or not).\n<\/p>\n\n<p>\nI considered two options for the refresh:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Gradually fix it a bit at a time.<\/li>\n<li>Kill it with fire and start again.<\/li>\n<\/ol>\n\n<p>\nGiven the mess my old config had gotten to I decided the latter would be much more manageable.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orge55627f\" class=\"outline-2\">\n<h2 id=\"orge55627f\">Running two configs on the same machine<\/h2>\n<div class=\"outline-text-2\" id=\"text-orge55627f\">\n<p>\nIt'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 <code>NVIM_APPNAME<\/code> environment variable. Normally Neovim expects the various working folders, including the configuration, to be in the nvim folder.\n<\/p>\n\n<p>\nBy using the <code>NVIM_APPNAME<\/code> environment variable you can set it to something different, I chose nvim-next. This let's you build an entirely new config and leave your old one intact.\n<\/p>\n\n<p>\nI started by manually creating the new folders (MacOS example).\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-bash\">mkdir -p ~\/.config\/nvim-next\nmkdir -p ~\/.local\/share\/nvim-next\nmkdir -p ~\/.local\/state\/nvim-next\nmkdir -p ~\/.cache\/nvim-next\n<\/pre>\n<\/div>\n\n<p>\nNow it's possible to run with a fresh config without worrying about messing up the old one.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-bash\"><span style=\"color: #00d3d0;\">NVIM_APPNAME<\/span>=nvim-next nvim\n<\/pre>\n<\/div>\n\n<p>\nDuring development of the new config I used this command to open them both up together.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-bash\"><span style=\"color: #00d3d0;\">NVIM_APPNAME<\/span>=nvim-next nvim -O ~\/.config\/nvim-next\/init.lua ~\/.config\/nvim\/init.lua\n<\/pre>\n<\/div>\n\n<p>\nFinally, you may want to include the environment variable in your shell config to use it as your \"real\" config more easily.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-bash\"><span style=\"color: #f78fe7;\">export<\/span> <span style=\"color: #00d3d0;\">NVIM_APPNAME<\/span>=nvim-next\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n\n<div id=\"outline-container-org0367c42\" class=\"outline-2\">\n<h2 id=\"org0367c42\">Replicating the config<\/h2>\n<div class=\"outline-text-2\" id=\"text-org0367c42\">\n<p>\nI 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\">vim.g.mapleader = <span style=\"color: #79a8ff;\">\",\"<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Prevents showing extra messages when using completion<\/span>\nvim.opt.shortmess:append(<span style=\"color: #79a8ff;\">\"c\"<\/span>)\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Sets the height of the command line area at the bottom<\/span>\nvim.opt.cmdheight = 2\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Displays the line number for the current line<\/span>\nvim.opt.number = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Displays line numbers relative to the current cursor position<\/span>\nvim.opt.relativenumber = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Time in milliseconds to wait for a mapped sequence to complete<\/span>\nvim.opt.timeoutlen = 500\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Time in milliseconds of inactivity before calling CursorHold or writing to swap<\/span>\nvim.opt.updatetime = 4000\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Ignores case when searching patterns<\/span>\nvim.opt.ignorecase = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Automatically switches to case-sensitive search if a capital letter is used<\/span>\nvim.opt.smartcase = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Enables 24-bit RGB colors in the terminal<\/span>\nvim.opt.termguicolors = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Configures the behavior of the insert mode completion menu<\/span>\nvim.opt.completeopt = <span style=\"color: #79a8ff;\">\"menu,menuone,noselect,popup\"<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Number of spaces that a &lt;Tab&gt; character represents<\/span>\nvim.opt.tabstop = 2\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Number of spaces to use for each step of automatic indentation<\/span>\nvim.opt.shiftwidth = 2\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Number of spaces that a &lt;Tab&gt; counts for during editing operations<\/span>\nvim.opt.softtabstop = 2\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Converts tabs into spaces when typing<\/span>\nvim.opt.expandtab = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Automatically inserts an extra level of indentation in some cases<\/span>\nvim.opt.smartindent = <span style=\"color: #00bcff;\">true<\/span>\n<span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Makes &lt;Tab&gt; insert 'shiftwidth' number of spaces at the start of a line<\/span>\nvim.opt.smarttab = <span style=\"color: #00bcff;\">true<\/span>\n<\/pre>\n<\/div>\n\n<p>\nAfter that I stepped through the init.lua entirely and made a list of things to keep and things to lose. Let's cover them by category.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgd0cd587\" class=\"outline-2\">\n<h2 id=\"orgd0cd587\">vim.pack, Neovim's new built-in plugin manager<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgd0cd587\">\n<p>\nPreviously I used <a href=\"https:\/\/github.com\/folke\/lazy.nvim\">folke\/lazy.nvim<\/a> 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\">{\n  <span style=\"color: #79a8ff;\">'shaunsingh\/nord.nvim'<\/span>,\n  lazy = <span style=\"color: #00bcff;\">false<\/span>,\n  priority = 1000,\n  <span style=\"color: #feacd0;\">config<\/span> = <span style=\"color: #b6a0ff;\">function<\/span>()\n    vim.cmd <span style=\"color: #79a8ff;\">\"colorscheme nord\"<\/span>\n  <span style=\"color: #b6a0ff;\">end<\/span>\n},\n<\/pre>\n<\/div>\n\n<p>\nvim.pack'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.\n<\/p>\n\n<p>\nIf 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. \n<\/p>\n\n<p>\nIn my use case I found the start up time is 80ms and plenty fast enough for me, so I don't miss the lazy loading.\n<\/p>\n\n<p>\nTo 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.\n<\/p>\n\n<p>\nFor example the configuration above becomes:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\">vim.pack.add({\n  { src = <span style=\"color: #79a8ff;\">\"https:\/\/github.com\/shaunsingh\/nord.nvim\"<\/span> },\n})\n\nvim.cmd(<span style=\"color: #79a8ff;\">'colorscheme nord'<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nNote 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\"><span style=\"color: #b6a0ff;\">local<\/span> <span style=\"color: #feacd0;\">gh<\/span> = <span style=\"color: #b6a0ff;\">function<\/span>(<span style=\"color: #00d3d0;\">x<\/span>) <span style=\"color: #b6a0ff;\">return<\/span> <span style=\"color: #79a8ff;\">'https:\/\/github.com\/'<\/span> .. x <span style=\"color: #b6a0ff;\">end<\/span>\n<span style=\"color: #b6a0ff;\">local<\/span> <span style=\"color: #feacd0;\">cb<\/span> = <span style=\"color: #b6a0ff;\">function<\/span>(<span style=\"color: #00d3d0;\">x<\/span>) <span style=\"color: #b6a0ff;\">return<\/span> <span style=\"color: #79a8ff;\">'https:\/\/codeberg.org\/'<\/span> .. x <span style=\"color: #b6a0ff;\">end<\/span>\n\nvim.pack.add({ gh(<span style=\"color: #79a8ff;\">'user\/plugin1'<\/span>), cb(<span style=\"color: #79a8ff;\">'user\/plugin2'<\/span>) })\n<\/pre>\n<\/div>\n\n<p>\nvim.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.\n<\/p>\n\n<p>\nAlso 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. \n<\/p>\n\n<p>\nOne 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org4665a53\" class=\"outline-2\">\n<h2 id=\"org4665a53\">Treesitter<\/h2>\n<div class=\"outline-text-2\" id=\"text-org4665a53\">\n<p>\nI 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:\n<\/p>\n\n<p>\nInstall the tree-sitter-cli, which is required by newer versions of treesitter-nvim.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-bash\">brew install tree-sitter-cli\n<\/pre>\n<\/div>\n\n<p>\nEnsure to switch to the main branch of treesitter-nvim (main is more up to date than master).\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\">vim.pack.add({\n  { src = <span style=\"color: #79a8ff;\">\"https:\/\/github.com\/nvim-treesitter\/nvim-treesitter\"<\/span>, \n    version = <span style=\"color: #79a8ff;\">'main'<\/span> },\n})\n<\/pre>\n<\/div>\n\n<p>\nAfter that I was able to TSUpdate and TSInstall whatever I needed without any issues providing perfect syntax highlighting.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgb35f839\" class=\"outline-2\">\n<h2 id=\"orgb35f839\">LSP and completion<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb35f839\">\n<p>\nAs mentioned, the bulk of my config complexity was coming from completion and LSP configuration. This complexity is greatly reduced by the following changes:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Remove nvim-cmp and LuaSnip<\/li>\n<li>Use native completion<\/li>\n<li>Modular lsp configuration<\/li>\n<\/ol>\n\n<p>\nSince 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\">vim.opt.completeopt = <span style=\"color: #79a8ff;\">\"menu,menuone,noselect,popup\"<\/span> <span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Ensures the menu appears even for a single match and uses the native popup window.<\/span>\nvim.o.autocomplete = <span style=\"color: #00bcff;\">true<\/span> <span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Enables the overall completion feature.<\/span>\n\nvim.api.nvim_create_autocmd(<span style=\"color: #79a8ff;\">\"LspAttach\"<\/span>, {\n  group = vim.api.nvim_create_augroup(<span style=\"color: #79a8ff;\">\"lsp_completion\"<\/span>, { clear = <span style=\"color: #00bcff;\">true<\/span> }),\n  <span style=\"color: #feacd0;\">callback<\/span> = <span style=\"color: #b6a0ff;\">function<\/span>(<span style=\"color: #00d3d0;\">args<\/span>)\n    <span style=\"color: #b6a0ff;\">local<\/span> <span style=\"color: #00d3d0;\">client_id<\/span> = args.data.client_id\n    <span style=\"color: #b6a0ff;\">if<\/span> <span style=\"color: #b6a0ff;\">not<\/span> client_id <span style=\"color: #b6a0ff;\">then<\/span>\n      <span style=\"color: #b6a0ff;\">return<\/span>\n    <span style=\"color: #b6a0ff;\">end<\/span>\n\n    <span style=\"color: #b6a0ff;\">local<\/span> <span style=\"color: #00d3d0;\">client<\/span> = vim.lsp.get_client_by_id(client_id)\n    <span style=\"color: #b6a0ff;\">if<\/span> client <span style=\"color: #b6a0ff;\">and<\/span> client:supports_method(<span style=\"color: #79a8ff;\">\"textDocument\/completion\"<\/span>) <span style=\"color: #b6a0ff;\">then<\/span>\n      <span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Enable native LSP completion for this client + buffer<\/span>\n      vim.lsp.completion.enable(<span style=\"color: #00bcff;\">true<\/span>, client_id, args.buf, {\n        autotrigger = <span style=\"color: #00bcff;\">true<\/span>,   <span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">auto-show menu as you type (recommended)<\/span>\n        <span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">You can also set { autotrigger = false } and trigger manually with &lt;C-x&gt;&lt;C-o&gt;<\/span>\n      })\n    <span style=\"color: #b6a0ff;\">end<\/span>\n  <span style=\"color: #b6a0ff;\">end<\/span>,\n})\n<\/pre>\n<\/div>\n\n<p>\nFinally, 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\">vim.lsp.enable(<span style=\"color: #79a8ff;\">'pylsp'<\/span>) <span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">Python<\/span>\n<\/pre>\n<\/div>\n\n<p>\nLSP 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\"><span style=\"color: #b6a0ff;\">return<\/span> {\n  cmd = { <span style=\"color: #79a8ff;\">'pylsp'<\/span> },\n  filetypes = { <span style=\"color: #79a8ff;\">'python'<\/span> },\n  settings = {\n    pylsp = {\n      plugins = {\n        mccabe = { enabled = <span style=\"color: #00bcff;\">false<\/span> },\n        pycodestyle = { enabled = <span style=\"color: #00bcff;\">false<\/span> },\n        flake8 = {\n          enabled = <span style=\"color: #00bcff;\">true<\/span>,\n          ignore = { <span style=\"color: #79a8ff;\">\"E501\"<\/span>, <span style=\"color: #79a8ff;\">\"E302\"<\/span>, <span style=\"color: #79a8ff;\">\"W\"<\/span> },\n          maxLineLength = 120,\n        },\n      },\n    },\n  },\n}\n<\/pre>\n<\/div>\n\n<p>\nThis kind of convention over configuration appeals to me and helps keeps things organized.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orga3c3afd\" class=\"outline-2\">\n<h2 id=\"orga3c3afd\">New User interface (ui2) and the status line<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga3c3afd\">\n<p>\nui2 is a \"is a redesign of the core messages and commandline UI, which will replace the legacy message grid in the TUI.\". In particular it removes \"Press Enter\" interruptions, and it highlights the command line as you type. Nice.\n<\/p>\n\n<p>\nAs a maintainer of a status line plugin, <a href=\"https:\/\/github.com\/justinhj\/battery.nvim\">battery.nvim<\/a> I was curious if anything had broken the statusline. Everything seemed to work without any changes. \n<\/p>\n\n<p>\nui2 is opt-in and you can do so as follows:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-lua\"><span style=\"color: #a8a8a8;\">-- <\/span><span style=\"color: #a8a8a8;\">New UI opt-in<\/span>\n<span style=\"color: #f78fe7;\">require<\/span>(<span style=\"color: #79a8ff;\">'vim._core.ui2'<\/span>).enable({})\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org28e3aee\" class=\"outline-2\">\n<h2 id=\"org28e3aee\">The best of the rest<\/h2>\n<div class=\"outline-text-2\" id=\"text-org28e3aee\">\n<p>\nI've kept the most minimal set of plugins for my config. In particular I still have:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>mason, mason-lspconfig &#x2013; lsp server managment<\/li>\n<li>nvim-treesitter &#x2013; tools for treesitter<\/li>\n<li>shaunsingh\/nord.nvim &#x2013; my favourite colourscheme<\/li>\n<li>mrjones2014\/legendary.nvim &#x2013; archived but still great key map manager<\/li>\n<li>ibhagwan\/fzf-lua &#x2013; fast finder for files and text within files<\/li>\n<li>nvim-lualine\/lualine.nvim &#x2013; best statusline<\/li>\n<li>justinhj\/battery.nvim &#x2013; Let me plug my own plugin<\/li>\n<li>nvim-lua\/plenary.nvim &#x2013; Useful libraries<\/li>\n<li>folke\/which-key.nvim &#x2013; Keymap display<\/li>\n<\/ol>\n\n<p>\nSome I may miss\n<\/p>\n\n<ol class=\"org-ol\">\n<li>tpope\/vim-fugitive &#x2013; Nice Git commands, but I mostly use Git at the command line<\/li>\n<li>karb94\/neoscroll.nvim &#x2013; smooth scrolling<\/li>\n<\/ol>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org23ff122\" class=\"outline-2\">\n<h2 id=\"org23ff122\">vim.net.request<\/h2>\n<div class=\"outline-text-2\" id=\"text-org23ff122\">\n<p>\nI 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org4f02f78\" class=\"outline-2\">\n<h2 id=\"org4f02f78\">Wrapping up<\/h2>\n<div class=\"outline-text-2\" id=\"text-org4f02f78\">\n<p>\nThere are a couple of options once you're happy with the new config. One option is to keep the old config around forever. Another would be to delete it completely.\n<\/p>\n\n<p>\nFor 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. \n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org6a4f83d\" class=\"outline-2\">\n<h2 id=\"org6a4f83d\">Conclusion<\/h2>\n<div class=\"outline-text-2\" id=\"text-org6a4f83d\">\n<p>\n0.12.x is one of the biggest updates for a while in Neovim and it'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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org00f72ee\" class=\"outline-2\">\n<h2 id=\"org00f72ee\">Thanks<\/h2>\n<div class=\"outline-text-2\" id=\"text-org00f72ee\">\n<p>\nThank you to <code>GrandLate7367<\/code>, <code>TheLeoP_<\/code> and  <code>mushfiq_814<\/code> on Reddit's <code>r\/neovim<\/code> for pointing out some issues with the original post.\n<\/p>\n\n<p>\n&copy;2026 Justin Heyes-Jones. All Rights Reserved\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Mon, 06 Apr 2026 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2026\/04\/06\/refreshing-your-neovim-config-for-0-12-0.html","guid":"http:\/\/justinhj.github.io\/2026\/04\/06\/refreshing-your-neovim-config-for-0-12-0.html","category":["neovim","vim","command-line"]},{"title":"Visualizing K-Way Merge&#58 An Interactive Guide to Database Sorting","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n<script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.0\/MathJax.js?config=TeX-AMS_HTML\"><\/script>\n<p>\n<img src=\"\/..\/images\/aleksandr-galichkin-AUae3_x_lDU-unsplash.jpg\" alt=\"aerial view of three empty tennis courts\" title=\"\" \/>\n<\/p>\n<span>\nPhoto by <a href=\"https:\/\/unsplash.com\/@axga?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Aleksandr Galichkin<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/aerial-view-of-three-empty-tennis-courts-AUae3_x_lDU?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash<\/a>\n<\/span>\n\n<p>\nIn this post, inspired by a <a href=\"https:\/\/www.youtube.com\/embed\/agjVihO6IPM?si=gBBtRn744A5A2Wqr\">video<\/a> by Tigerbeetle engineers Tobias Ziegler (@toziegler) and Alex Kladov (@matklad), I'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. \n<\/p>\n\n<p>\nThe title image isn't just a pretty picture of tennis courts; it's the inspiration for the most efficient external sorting algorithm: The Tournament Tree.\n<\/p>\n\n<div id=\"outline-container-orga70713b\" class=\"outline-2\">\n<h2 id=\"orga70713b\">External sort and k-way merge<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga70713b\">\n<p>\nWhilst 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. \n<\/p>\n\n<p>\nAs an extreme example take the 1960 USA Census for example. The Census Bureau'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.\n<\/p>\n\n<p>\nInstead 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. \n<\/p>\n\n<p>\nThe k-way merge part comes from k (the number of runs being handled at once, in this case the number of tapes, let'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.\n<\/p>\n\n<iframe width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/2YnydcjlLPg?si=IKNFMKHE5TMEels4\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org7b156e7\" class=\"outline-2\">\n<h2 id=\"org7b156e7\">External sort in modern databases<\/h2>\n<div class=\"outline-text-2\" id=\"text-org7b156e7\">\n<p>\nModern databases use essentially the same logic. An LSM tree (see next section) flushes \"SSTables\" (sorted runs) to disk (which are modern \"tapes\") 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.\n<\/p>\n\n<p>\nExternal sort is used for various purposes:\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-left\">Databases<\/td>\n<td class=\"org-left\">Purpose<\/td>\n<td class=\"org-left\">Algorithm<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">LSM-Tree Databases (RocksDB, Cassandra, ScyllaDB, LevelDB)<\/td>\n<td class=\"org-left\">Compaction<\/td>\n<td class=\"org-left\">min-heap<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">Search Engines (Apache Lucene \/ Elasticsearch \/ Solr)<\/td>\n<td class=\"org-left\">Segment merging<\/td>\n<td class=\"org-left\">min-heap<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">Analytical &amp; Columnar Databases (ClickHouse, DuckDB)<\/td>\n<td class=\"org-left\">Part Merging: Maintaining column blocks sort order<\/td>\n<td class=\"org-left\">Linear scan\/Vectorized merge<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">Relational Databases (PostgreSQL)<\/td>\n<td class=\"org-left\">Queries that exceed work<sub>mem<\/sub>\/Merging joins<\/td>\n<td class=\"org-left\">Tree of Losers\/Polyphase<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org712f4b8\" class=\"outline-2\">\n<h2 id=\"org712f4b8\">LSM trees<\/h2>\n<div class=\"outline-text-2\" id=\"text-org712f4b8\">\n<p>\nLSM-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't go into much detail on them in this post, it'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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgbeb8019\" class=\"outline-2\">\n<h2 id=\"orgbeb8019\">Tigerbeetle<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgbeb8019\">\n<p>\nLike DuckDB and others, Tigerbeetle's storage engine is also using LSM-Trees. Let's dig into that a little:\n<\/p>\n\n<img src=\"..\/..\/..\/images\/tbwriting.png\" \n     alt=\"Tigerbeetle's write path\" \n     style=\"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);\">\n\n<p>\nIn 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). \n<\/p>\n\n<p>\nThe 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. \n<\/p>\n\n<p>\nTo better explain the mechanism play with the following toy Tigerbeetle database: \n<\/p>\n\n<div style=\"text-align: center; margin: 20px 0;\">\n    <a href=\"https:\/\/heyes-jones.com\/tigerbeetlelsm.html\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"text-decoration: none;\">\n        <img src=\"..\/..\/..\/images\/tb1.png\" \n             alt=\"Tigerbeetle LSM Visualization\" \n             title=\"Click to launch interactive simulation\"\n             style=\"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);\">\n        <p style=\"margin-top: 8px; color: #666; font-size: 0.9em;\">\n            \ud83d\udc46 <em>Click to try the interactive simulation<\/em>\n        <\/p>\n    <\/a>\n<\/div>\n\n<p>\nApart 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org063d6f2\" class=\"outline-2\">\n<h2 id=\"org063d6f2\">K-Way merges<\/h2>\n<div class=\"outline-text-2\" id=\"text-org063d6f2\">\n<p>\nThe 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.\n<\/p>\n\n<p>\nImplementing 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.\n<\/p>\n\n<p>\nContrary 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org3e83ba1\" class=\"outline-2\">\n<h2 id=\"org3e83ba1\">Linear scan<\/h2>\n<div class=\"outline-text-2\" id=\"text-org3e83ba1\">\n<p>\nAs always, let'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:\n<\/p>\n\n<p>\nAlgorithm.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Run through all k current candidates tracking the smallest one found.<\/li>\n<li>Output the smallest element.<\/li>\n<li>Replace the smallest element with the next element <code>from the run it came from<\/code>.<\/li>\n<\/ol>\n\n<p>\nThat last point is crucial. Why take the next element from that particular run? It'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't see yet from the \"winner's\" run. \n<\/p>\n\n<p>\nMake sure to understand that point as all the algorithms below will do the same.\n<\/p>\n\n<p>\nAs mentioned above, you can explore each algorithm interactively, just click on the image below. Each one has the same controls:\n<\/p>\n\n<ul class=\"org-ul\">\n<li><b>Step<\/b>. Go to the next step of the algorithm, updating the step description and animation.<\/li>\n<li><b>Play<\/b>. To unleash the animation and run through the algorithm until you stop it or the runs are all empty.<\/li>\n<li><b>Seed<\/b>. Change the seed to try different data sets.<\/li>\n<li><b>Speed<\/b> slider. Change the speed of the animation.<\/li>\n<li><b>Reset<\/b>. Restart the simulation.<\/li>\n<\/ul>\n\n<div style=\"text-align: center; margin: 20px 0;\">\n    <a href=\"https:\/\/heyes-jones.com\/externalsort\/linearscan.html\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"text-decoration: none;\">\n        <img src=\"..\/..\/..\/images\/linear-scan-thumbnail.png\" \n             alt=\"K-Way Merge Tree of Winners Visualization\" \n             title=\"Click to launch interactive simulation\"\n             style=\"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);\">\n        <p style=\"margin-top: 8px; color: #666; font-size: 0.9em;\">\n            \ud83d\udc46 <em>Click to try the interactive simulation<\/em>\n        <\/p>\n    <\/a>\n<\/div>\n\n<p>\nAnalysis.\n<\/p>\n\n<p>\nSince we must do k comparisons per output, with n total data items in all the runs the complexity is: \\(O(kn)\\)\n<\/p>\n\n<p>\nWhilst 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. \n<\/p>\n\n<p>\nIn 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org3c1a975\" class=\"outline-2\">\n<h2 id=\"org3c1a975\">Going faster with Tree Selection<\/h2>\n<div class=\"outline-text-2\" id=\"text-org3c1a975\">\n<p>\nAs 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.\n<\/p>\n\n<p>\nAlthough 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. \n<\/p>\n\n<p>\nIn Knuth (Art of Computer Programming vol3: Searching and Sorting) we find the discussion on selection sort which helps here&#x2026;\n<\/p>\n\n<p>\nQuadratic 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.\n<\/p>\n\n<p>\n<code>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't be confused by finding the largest element in this section.<\/code>\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-right\">8<\/td>\n<td class=\"org-right\">4<\/td>\n<td class=\"org-right\">3<\/td>\n<td class=\"org-right\">7<\/td>\n<td class=\"org-right\">5<\/td>\n<td class=\"org-right\">2<\/td>\n<td class=\"org-right\">9<\/td>\n<td class=\"org-right\">1<\/td>\n<td class=\"org-right\">6<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-right\">8<\/td>\n<td class=\"org-right\">4<\/td>\n<td class=\"org-right\">3<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-right\">7<\/td>\n<td class=\"org-right\">5<\/td>\n<td class=\"org-right\">2<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-right\">9<\/td>\n<td class=\"org-right\">1<\/td>\n<td class=\"org-right\">6<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nOnce you have the three groups find the largest in each.\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-left\"><code>8<\/code><\/td>\n<td class=\"org-right\">4<\/td>\n<td class=\"org-right\">3<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><code>7<\/code><\/td>\n<td class=\"org-right\">5<\/td>\n<td class=\"org-right\">2<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><code>9<\/code><\/td>\n<td class=\"org-right\">1<\/td>\n<td class=\"org-right\">6<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nThe largest element is now the largest of the three \"winners\", 9.\n<\/p>\n\n<p>\nTo find the second largest, it could be either of the two remaining winners or one of the others in 9's group. (Note that I replace removed elements with infinity so they can be ignored in subsequent steps.)\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-left\"><code>8<\/code><\/td>\n<td class=\"org-right\">4<\/td>\n<td class=\"org-right\">3<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><code>7<\/code><\/td>\n<td class=\"org-right\">5<\/td>\n<td class=\"org-right\">2<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">\\(\\infty\\)<\/td>\n<td class=\"org-right\">1<\/td>\n<td class=\"org-right\"><code>6<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nWe find it is 8. So the next winner is the larger of 7, 6 or the others in 8's group.\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-right\" \/>\n\n<col  class=\"org-right\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-left\">\\(\\infty\\)<\/td>\n<td class=\"org-right\"><code>4<\/code><\/td>\n<td class=\"org-right\">3<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><code>7<\/code><\/td>\n<td class=\"org-right\">5<\/td>\n<td class=\"org-right\">2<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">\\(\\infty\\)<\/td>\n<td class=\"org-right\">1<\/td>\n<td class=\"org-right\"><code>6<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nProceeding this way the sort needs n sqrt n comparisons, much better than the original n<sup>2<\/sup>.\n<\/p>\n\n<p>\nFriend 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.\n<\/p>\n\n<p>\nThis 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't have to repeat them.\n<\/p>\n<\/div>\n\n<div id=\"outline-container-orgc32f994\" class=\"outline-3\">\n<h3 id=\"orgc32f994\">min heap<\/h3>\n<div class=\"outline-text-3\" id=\"text-orgc32f994\">\n<p>\nAs we saw above, modern databases make use of the min-heap for k-way merge. As a binary tree structure it'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.\n<\/p>\n\n<p>\nIn order to use the min-heap for k-way merge we do the following:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Populate a fixed size min-heap with the first (smallest) elements from the k runs.<\/li>\n<li>Pop the top item from the heap (the smallest) and replace it with the next from the same run.<\/li>\n<li>Sift the heap down to make the heap valid again.<\/li>\n<li>Repeat until the sort is complete.<\/li>\n<\/ol>\n\n<p>\nOnce again, you can step through the algorithm using the interactive visualization below.\n<\/p>\n\n<div style=\"text-align: center; margin: 20px 0;\">\n    <a href=\"https:\/\/heyes-jones.com\/externalsort\/minheapmerge.html\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"text-decoration: none;\">\n        <img src=\"..\/..\/..\/images\/min-heap-merge-thumbnail.png\" \n             alt=\"K-Way Merge Tree of Losers Visualization\" \n             title=\"Click to launch interactive simulation\"\n             style=\"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);\">\n        <p style=\"margin-top: 8px; color: #666; font-size: 0.9em;\">\n            \ud83d\udc46 <em>Click to try the interactive simulation<\/em>\n        <\/p>\n    <\/a>\n<\/div>\n\n<p>\nAnalysis.\n<\/p>\n\n<p>\nWith a min-heap the push and pop operations are both \\(O(\\log_2 k)\\) giving a runtime complexity of \\(O(n \\log k)\\).\n<\/p>\n\n<pre class=\"example\" id=\"orgdbf335b\">\n                  a\n                  |\n      +-----------+-----------+\n      |                       |\n      b                       c\n      |                       |\n+-----+-----+           +-----+-----+\n|           |           |           |\nd           e           f           g\n<\/pre>\n\n<p>\nmin-heaps are represented as a flat array. For example the tree above would be stored in memory like this:\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n<\/colgroup>\n<tbody>\n<tr>\n<td class=\"org-left\">a<\/td>\n<td class=\"org-left\">b<\/td>\n<td class=\"org-left\">c<\/td>\n<td class=\"org-left\">d<\/td>\n<td class=\"org-left\">e<\/td>\n<td class=\"org-left\">f<\/td>\n<td class=\"org-left\">g<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nThis 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.\n<\/p>\n\n<p>\nIn addition our use case allows us to do the push and pop in one move.\n<\/p>\n\n<p>\nDuring the sift down process after adding the new winner you need to:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Compare Left Child vs. Right Child (to find the smaller one).<\/li>\n<li>Compare the Smaller Child vs. The Current Node (to see if you swap).<\/li>\n<\/ol>\n\n<p>\nThis costs \\(2 \\cdot \\log_2 k\\) comparisons per element.\n<\/p>\n\n<p>\nLet's see how we can improve.\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org222126e\" class=\"outline-2\">\n<h2 id=\"org222126e\">Tournament Trees<\/h2>\n<div class=\"outline-text-2\" id=\"text-org222126e\">\n<p>\nIn 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.\n<\/p>\n\n<pre class=\"example\" id=\"org9d0cd52\">\n                  Chris (Champion)\n                      |\n          +-----------+-----------+\n          |                       |\n        Chris                    Pat\n          |                       |\n    +-----+-----+           +-----+-----+\n    |           |           |           |\n   Kim        Chris        Pat        Robin\n    |           |           |           |\n +--+--+     +--+--+     +--+--+     +--+--+\n |     |     |     |     |     |     |     |\nKim  Sandy Chris  Lou   Pat   Ray   Dale Robin\n<\/pre>\n\n<p>\nThe 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.\n<\/p>\n\n<p>\nThe best player then, is Chris. But what if Chris had not shown up that day? Is Pat the best player? \n<\/p>\n\n<p>\nWell all we know is that Pat beat all the opponents on her side of the tree, but we don't in fact know if she would have beaten the same opponents on Chris'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.\n<\/p>\n\n<p>\n<img src=\"\/..\/images\/pure-julia-E4fNq7wYE2w-unsplash.jpg\" alt=\"book image of a page from alice in wonderland\" title=\"\" \/>\n<\/p>\n<span>\nPhoto by <a href=\"https:\/\/unsplash.com\/@purejulia?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">pure julia<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/white-book-page-with-man-and-woman-print-E4fNq7wYE2w?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash<\/a>\n<\/span>\n\n<p>\nIt 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.\n<\/p>\n\n<p>\nRev. Charles Lutwidge Dodgson, better known by his pen name, Lewis Carroll, author of Alice'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.\n<\/p>\n\n<p>\n\u201cAt 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.\u201d - Charles Dodgson\n<\/p>\n\n<p>\nDodgson 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. \n<\/p>\n\n<p>\nIf you want to read more about this I found an excellent blog post which includes an implementation of Dodgson's idea in the R language, with the missing specifications figured out.\n<\/p>\n\n<p>\n<a href=\"https:\/\/freerangestats.info\/blog\/2020\/02\/01\/tennis-carroll\">Lewis Carroll's proposed rules for Tennis Tournaments<\/a>\n<\/p>\n\n<p>\nWhilst 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'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.\n<\/p>\n\n<p>\nFor 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.\n<\/p>\n\n<p>\nIn the tournament above, Lou should play Kim and Pat should play the winner of that game. Notice that \"only two additional matches are required to find the second-best player, because of the structure we have remembered from the earlier games.\"\n<\/p>\n\n<p>\nTree selection, then, proceeds by removing the winner of the tournament from our \"Tree of Winners\", then replaying the tournament without that player, and each replay requires \\(\\log_2 k\\) comparisons.\n<\/p>\n\n<p>\nTo make this more concrete as a sort let'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.\n<\/p>\n\n<p>\nStep 1 we remove 1 and output it as the first element.\n<\/p>\n\n<pre class=\"example\" id=\"org8555b4b\">\nSort output: 1\n                    1 (Champion)\n                        |\n            +-----------+-----------+\n            |                       |\n            1                       3\n            |                       |\n      +-----+-----+           +-----+-----+\n      |           |           |           |\n      2           1           3           7\n      |           |           |           |\n   +--+--+     +--+--+     +--+--+     +--+--+\n   |     |     |     |     |     |     |     |\n   2     6     1     4     3     5     8     7\n<\/pre>\n\n<p>\nIn step 2 we remove 1 from the tournament in preparation to replay without them.\n<\/p>\n\n<pre class=\"example\" id=\"org2086dae\">\nSort output: 1,2\n                        2 (Champion)\n                        |\n            +-----------+-----------+\n            |                       |\n            2                       3\n            |                       |\n      +-----+-----+           +-----+-----+\n      |           |           |           |\n      2           4           3           7\n      |           |           |           |\n   +--+--+     +--+--+     +--+--+     +--+--+\n   |     |     |     |     |     |     |     |\n   2     6     X     4     3     5     8     7\n<\/pre>\n\n<p>\nWe 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.\n<\/p>\n\n<p>\nNow we remove 2. Replaying from the bottom gives the tree below and we output the 3.\n<\/p>\n\n<pre class=\"example\" id=\"orgae2d0ba\">\nSort output: 1,2,3\n                        3 (Champion)\n                        |\n            +-----------+-----------+\n            |                       |\n            4                       3\n            |                       |\n      +-----+-----+           +-----+-----+\n      |           |           |           |\n      6           4           3           7\n      |           |           |           |\n   +--+--+     +--+--+     +--+--+     +--+--+\n   |     |     |     |     |     |     |     |\n   x     6     X     4     3     5     8     7\n<\/pre>\n\n<p>\nIt'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!\n<\/p>\n\n<p>\nCheck out this interactive visualization to fully understand the algorithm.\n<\/p>\n\n<div style=\"text-align: center; margin: 20px 0;\">\n    <a href=\"https:\/\/heyes-jones.com\/externalsort\/treeofwinners.html\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"text-decoration: none;\">\n        <img src=\"..\/..\/..\/images\/tree-of-winners-thumbnail.png\" \n             alt=\"K-Way Merge Tree of Winners Visualization\" \n             title=\"Click to launch interactive simulation\"\n             style=\"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);\">\n        <p style=\"margin-top: 8px; color: #666; font-size: 0.9em;\">\n            \ud83d\udc46 <em>Click to try the interactive simulation<\/em>\n        <\/p>\n    <\/a>\n<\/div>\n\n<p>\nAnalysis.\n<\/p>\n\n<p>\nAgain 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:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>You traverse from a single leaf at the bottom up to the root of the tree to replace the winner.<\/li>\n<li>At each level you need compare only with the current sibling.<\/li>\n<li>The number of comparisons is cut to \\(\\log_2 k\\), half that of the worse case min-heap.<\/li>\n<li>Hardware Sympathy: Tournament trees have a fixed path from leaf to root. There are no conditional checks to see \"which child is smaller\" before deciding which path to take down; you always move up from the leaf. This can be friendlier to CPU branch prediction.<\/li>\n<\/ol>\n\n<p>\nThere is still some room for improvement thanks to an ingenious idea from the 1950's.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgc7f5290\" class=\"outline-2\">\n<h2 id=\"orgc7f5290\">Tree of Losers<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgc7f5290\">\n<p>\nIn Knuth's Sorting and Searching (specifically Section 5.4.1), Donald Knuth attributes the origin of the \"tree of losers\" (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.\n<\/p>\n\n<p>\nHis 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.\n<\/p>\n\n<p>\nDemuth'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. \n<\/p>\n\n<p>\nThe algorithm looks like this:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Populate the tree of losers in a similar way to the tree of winners, but store the loser in each node.<\/li>\n<li>Remove the winner.<\/li>\n<li>Take the next candidate from the winners run.<\/li>\n<li>Starting from its leaf compare with each loser. If the winner loses in this comparison then swap it, otherwise continue moving up the tree.<\/li>\n<li>When you get to the top, whoever is stored in the winner register gets output.<\/li>\n<li>Repeat until the runs are empty.<\/li>\n<\/ol>\n\n<p>\nInteractive tree of losers:\n<\/p>\n\n<div style=\"text-align: center; margin: 20px 0;\">\n    <a href=\"https:\/\/heyes-jones.com\/externalsort\/treeoflosers.html\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"text-decoration: none;\">\n        <img src=\"..\/..\/..\/images\/tree-of-losers-thumbnail.png\" \n             alt=\"K-Way Merge Tree of Losers Visualization\" \n             title=\"Click to launch interactive simulation\"\n             style=\"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);\">\n        <p style=\"margin-top: 8px; color: #666; font-size: 0.9em;\">\n            \ud83d\udc46 <em>Click to try the interactive simulation<\/em>\n        <\/p>\n    <\/a>\n<\/div>\n\n<p>\nAnalysis.\n<\/p>\n\n<p>\nAsymptotic complexity is \\(O(n \\log_2 k)\\) again.\n<\/p>\n\n<p>\nWe have performance improvements for larger values of k primarily due to efficiency in memory access and branch prediction during the \"replay\" phase.\n<\/p>\n\n<p>\nMemory access:\n<\/p>\n\n<p>\nRemember 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 \"loser\" from memory at each step.\n<\/p>\n\n<p>\nBranch prediction:\n<\/p>\n\n<p>\nWhile replaying the Winner tree we execute the conditional logic  <code>if (came_from_left) compare(new_val, right_child) else compare(new_val, left_child)<\/code> 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org3f9ed7d\" class=\"outline-2\">\n<h2 id=\"org3f9ed7d\">Conclusion<\/h2>\n<div class=\"outline-text-2\" id=\"text-org3f9ed7d\">\n<ul class=\"org-ul\">\n<li>K-Way merge is ubiquitous in database technology.<\/li>\n<li>For small k (merging 4-16 runs) you can often use simple select and consider using SIMD.<\/li>\n<li>Otherwise Tree of Losers is likely to be the best performance.<\/li>\n<\/ul>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n<\/colgroup>\n<thead>\n<tr>\n<th scope=\"col\" class=\"org-left\">Algorithm<\/th>\n<th scope=\"col\" class=\"org-left\">Complexity (per item)<\/th>\n<th scope=\"col\" class=\"org-left\">Comparisons (approx)<\/th>\n<th scope=\"col\" class=\"org-left\">Key Characteristic<\/th>\n<th scope=\"col\" class=\"org-left\">Pros<\/th>\n<th scope=\"col\" class=\"org-left\">Cons<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td class=\"org-left\"><b>Linear Scan<\/b><\/td>\n<td class=\"org-left\">\\(O(k)\\)<\/td>\n<td class=\"org-left\">\\(k\\)<\/td>\n<td class=\"org-left\">Iterates all candidates<\/td>\n<td class=\"org-left\">CPU Prefetch &amp; SIMD friendly for small \\(k\\)<\/td>\n<td class=\"org-left\">Scales poorly as \\(k\\) increases (&gt;16)<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><b>Min-Heap<\/b><\/td>\n<td class=\"org-left\">\\(O(\\log k)\\)<\/td>\n<td class=\"org-left\">\\(2 \\log k\\)<\/td>\n<td class=\"org-left\">Sift-down (swap with smallest child)<\/td>\n<td class=\"org-left\">Standard library; Compact memory layout<\/td>\n<td class=\"org-left\">Conditional branches (left vs right child); Higher comparison count<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><b>Winner Tree<\/b><\/td>\n<td class=\"org-left\">\\(O(\\log k)\\)<\/td>\n<td class=\"org-left\">\\(\\log k\\)<\/td>\n<td class=\"org-left\">Replay path from leaf to root<\/td>\n<td class=\"org-left\">Fewer comparisons than Heap<\/td>\n<td class=\"org-left\">Requires sibling checks at every level (branch mispredictions)<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\"><b>Tree of Losers<\/b><\/td>\n<td class=\"org-left\">\\(O(\\log k)\\)<\/td>\n<td class=\"org-left\">\\(\\log k\\)<\/td>\n<td class=\"org-left\">Compare with parent (loser)<\/td>\n<td class=\"org-left\"><b>Winner stays in register<\/b>; Fixed memory path (always parent)<\/td>\n<td class=\"org-left\">Slightly more complex implementation<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nYou can view the Tigerbeetle current implementation here.\n<a href=\"https:\/\/github.com\/tigerbeetle\/tigerbeetle\/blob\/main\/src\/lsm\/k_way_merge.zig\">Tigerbeetle K-Way merge<\/a>\n<\/p>\n\n<p>\nThanks for reading, please contact me using the email and social links above with any comments and corrections.\n<\/p>\n\n<p>\n\u00a92026 Justin Heyes-Jones. All Rights Reserved\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Mon, 19 Jan 2026 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2026\/01\/19\/visualizing-k-way-merge.html","guid":"http:\/\/justinhj.github.io\/2026\/01\/19\/visualizing-k-way-merge.html","category":["algorithms","databases"]},{"title":"Optimizing training a GPT style Tokenizer with C++","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/chart.js\"><\/script>\n\n<style>\n  .chart-container {\n      position: relative;\n      width: 100%;\n      max-width: 800px;\n      margin-left: auto;\n      margin-right: auto;\n      height: 300px;\n      max-height: 40vh;\n  }\n  @media (min-width: 768px) {\n      .chart-container {\n          height: 400px;\n      }\n  }\n  .chart-btn {\n      padding: 0.5rem 1rem;\n      font-size: 0.875rem;\n      font-weight: 500;\n      border-radius: 0.375rem;\n      transition: background-color 0.2s, color 0.2s;\n      border: 1px solid #e2e8f0;\n      color: #475569;\n  }\n  .chart-btn-active {\n      background-color: #3b82f6;\n      color: white;\n      border-color: #3b82f6;\n  }\n<\/style>\n\n<script>\n    document.addEventListener('DOMContentLoaded', () => {\n        const benchmarkData = {\n            taylorswift: {\n                labels: ['Python', 'C++ (First)', 'C++ (Lexical)'],\n                times: [11.0, 5.5, 0.04], \/\/ Using 0.04 instead of 0.0 for log scale\n            },\n            shakespeare: {\n                labels: ['Python', 'C++ (First)', 'C++ (Lexical)'],\n                times: [77.5, 36.5, 1.50],\n            },\n            bible: {\n                labels: ['Python', 'C++ (First)', 'C++ (Lexical)'],\n                times: [298.5, 107.0, 5.5],\n            },\n            wikitext: {\n                labels: ['Python', 'C++ (First)', 'C++ (Lexical)'],\n                times: [46080.0, 13500.0, 2217.5],\n            }\n        };\n\n        const ctx = document.getElementById('benchmarkChart').getContext('2d');\n        \n        const benchmarkChart = new Chart(ctx, {\n            type: 'bar',\n            data: {\n                labels: [],\n                datasets: [{\n                    label: 'Training Time (seconds)',\n                    data: [],\n                    backgroundColor: [\n                        'rgba(255, 99, 132, 0.2)',\n                        'rgba(54, 162, 235, 0.2)',\n                        'rgba(75, 192, 192, 0.2)'\n                    ],\n                    borderColor: [\n                        'rgba(255, 99, 132, 1)',\n                        'rgba(54, 162, 235, 1)',\n                        'rgba(75, 192, 192, 1)'\n                    ],\n                    borderWidth: 1\n                }]\n            },\n            options: {\n                indexAxis: 'y',\n                responsive: true,\n                maintainAspectRatio: false,\n                scales: {\n                    x: {\n                        beginAtZero: true,\n                        type: 'logarithmic',\n                        title: {\n                            display: true,\n                            text: 'Time in Seconds (Logarithmic Scale)'\n                        },\n                        grid: {\n                          display: false\n                        }\n                    },\n                    y: {\n                        grid: {\n                          display: false\n                        }\n\n                    }\n                },\n                plugins: {\n                    legend: {\n                        display: false\n                    },\n                    tooltip: {\n                        callbacks: {\n                            label: function(context) {\n                                let label = context.dataset.label || '';\n                                if (label) {\n                                    label += ': ';\n                                }\n                                if (context.parsed.x !== null) {\n                                    label += context.parsed.x.toFixed(2) + ' seconds';\n                                }\n                                return label;\n                            }\n                        }\n                    }\n                }\n            },\n            plugins: [],\n        });\n\n        const buttons = document.querySelectorAll('.chart-btn');\n\n        function updateChart(datasetName) {\n            const newData = benchmarkData[datasetName];\n            benchmarkChart.data.labels = newData.labels;\n            benchmarkChart.data.datasets[0].data = newData.times;\n            benchmarkChart.update();\n\n            buttons.forEach(button => {\n                if (button.dataset.corpus === datasetName) {\n                    button.classList.add('chart-btn-active');\n                } else {\n                    button.classList.remove('chart-btn-active');\n                }\n            });\n        }\n\n        buttons.forEach(button => {\n            button.addEventListener('click', () => {\n                updateChart(button.dataset.corpus);\n            });\n        });\n\n        \/\/ Set initial active state\n        updateChart('taylorswift');\n        \n        \/\/ Smooth scrolling for nav links\n        document.querySelectorAll('a[href^=\"#\"]').forEach(anchor => {\n            anchor.addEventListener('click', function (e) {\n                e.preventDefault();\n                document.querySelector(this.getAttribute('href')).scrollIntoView({\n                    behavior: 'smooth'\n                });\n            });\n        });\n    });\n<\/script>\n\n<div id=\"outline-container-org2e0801c\" class=\"outline-2\">\n<h2 id=\"org2e0801c\">Introduction<\/h2>\n<div class=\"outline-text-2\" id=\"text-org2e0801c\">\n<p>\nIn February 2024, renowned AI researcher and educator Andrej Karpathy, published the following video.\u00a0\n<\/p>\n\n<p>\n<a href=\"https:\/\/www.youtube.com\/watch?v=zduSFxRajkE\">https:\/\/www.youtube.com\/watch?v=zduSFxRajkE<\/a>\n<\/p>\n\n<p>\nAn excellent introduction to the fascinating topic of tokenization,\nsomething he considers a necessary evil right now. Maybe the need for\nit will go away but for now it must be well understood by AI engineers\nin order to get good results when building and using large language\nmodels.\n<\/p>\n\n<p>\nAs software engineers in 2025 the advent of large language models, and\ngenerative AI in general, bring about a profound shift in how we\ndesign, develop and implement software systems. As such I have been\ndelving into the details of how they they work, with Tokenization being\na significant side quest.\n<\/p>\n\n<p>\nIn this blog, related video and accompanying C++ project, I will walk\nthrough my exploration of the training aspect of tokenizers and look\nat their performance characteristics and optimization opportunities.\n<\/p>\n\n<p>\nMy main goal was to port the Python to C++ but also I became interested in optimizing the training stage.\n<\/p>\n\n<p>\nTraining 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.\n<\/p>\n\n<p>\nFor 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.\n<\/p>\n\n<p>\nUltimately, I was able to reduce the training time by a factor of 23 (for the large wikitext input) as shown below.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgb8bea08\" class=\"outline-2\">\n<h2 id=\"orgb8bea08\">Optimization results<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb8bea08\">\n<div class=\"text-center mb-12\">\n        <p class=\"mt-2 text-lg text-slate-600\">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.<\/p>\n    <\/div>\n    <div class=\"bg-white p-6 md:p-8 rounded-xl border border-slate-200 shadow-sm\" style=\"padding: 0.5em; background-color: #fcfcfc;\">\n        <div class=\"flex flex-wrap justify-center items-center mb-6 space-x-2 space-y-2\">\n            <button data-corpus=\"taylorswift\" class=\"chart-btn\">Taylor Swift<\/button>\n            <button data-corpus=\"shakespeare\" class=\"chart-btn\">Shakespeare<\/button>\n            <button data-corpus=\"bible\" class=\"chart-btn\">Bible<\/button>\n            <button data-corpus=\"wikitext\" class=\"chart-btn\">Wikitext-103<\/button>\n        <\/div>\n        <div class=\"chart-container\">\n            <canvas id=\"benchmarkChart\"><\/canvas>\n        <\/div>\n         <p class=\"text-center text-xs text-slate-500 mt-4\">Lower is better. Time in seconds.<\/p>\n    <\/div>\n\n<p>\nInput data sets used:\n<\/p>\n<ol class=\"org-ol\">\n<li>taylorswift. Text of the Taylor Swift wikipedia page.<\/li>\n<li>shakespeare. The complete works of Shakespeare.<\/li>\n<li>bible. The old and new testament of the Bible.<\/li>\n<li>wikitext-103. <a href=\"https:\/\/huggingface.co\/datasets\/Salesforce\/wikitext\">https:\/\/huggingface.co\/datasets\/Salesforce\/wikitext<\/a> 100 million tokens of high quality wikipedia articles.<\/li>\n<\/ol>\n\n<p>\nThese are included in the repository apart from wikitext which you can download from hugging face.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org5a48473\" class=\"outline-2\">\n<h2 id=\"org5a48473\">Briefly, Tokenization and BPE<\/h2>\n<div class=\"outline-text-2\" id=\"text-org5a48473\">\n<p>\nI don't want to even try and do a better job of explaining the need\nfor tokenization and the BPE algorithm than Karpathy, so I instead\nrecommend watching his video and, for additional insights, read the\npaper below:\n<\/p>\n\n<p>\n[Neural Machine Translation of Rare Words with Subword Units](<a href=\"https:\/\/arxiv.org\/pdf\/1508.07909\">https:\/\/arxiv.org\/pdf\/1508.07909<\/a>)\n<\/p>\n<\/div>\n\n<div id=\"outline-container-org457d3c1\" class=\"outline-3\">\n<h3 id=\"org457d3c1\">The need for tokenization<\/h3>\n<div class=\"outline-text-3\" id=\"text-org457d3c1\">\n<ul class=\"org-ul\">\n<li>Large language models deal with numbers not words or characters, so we must map input text to numbers.<\/li>\n<li>The model requires a fixed size vocabulary.<\/li>\n<li>Unfortunately, that vocabulary would have to be enormous to fit all words from all languages.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org61241d9\" class=\"outline-3\">\n<h3 id=\"org61241d9\">Sub word unit tokenization<\/h3>\n<div class=\"outline-text-3\" id=\"text-org61241d9\">\n<p>\nThe solution to these issues is sub-word tokenization; splitting words\nup into numbers representing components of words. Once you have that\nyou can handle:\n<\/p>\n\n<ul class=\"org-ul\">\n<li><b>Open-Vocabulary<\/b> Part of the token set is the basic characters of each language so you can represent every word.<\/li>\n<li><b>Rare words<\/b> Because the vocabulary set is open it means any rare word is handled.<\/li>\n<li><b>Translation of Novel Words<\/b> The model can translate and generate words it has not encountered before by composing them from sub-word units.<\/li>\n<\/ul>\n\n<p>\nHere 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.\n<\/p>\n\n<pre class=\"example\" id=\"org1d5d662\">\n      Input Text\n          \u2502\n          \u25bc\n     \"I love NLP\"\n          \u2502\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   Tokenizer       \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n          \u2502\n          \u25bc\n      Tokens\n   [\"i\", \"love\", \"nlp\"]\n          \u2502\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Vocabulary Lookup \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n          \u2502\n          \u25bc\n      Token IDs\n      [25, 2097, 12510]\n          \u2502\n          \u2502         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n          \u2502         \u2502          Embedding Matrix         \u2502\n          \u2502         \u2502 (Size: |V| x d_model)            \u2502\n          \u2502         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n          \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba\u2502 Row 25:   [0.1, -0.4, 0.2, ...]   \u2502  \u2500\u2500\u2500\u25ba  Embedding for \"i\"\n          \u2502         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n          \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba\u2502 Row 2097: [-0.8, 0.5, 0.9, ...]   \u2502  \u2500\u2500\u2500\u25ba  Embedding for \"love\"\n          \u2502         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n          \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba\u2502 Row 12510: [0.3, 0.7, -0.1, ...]  \u2502  \u2500\u2500\u2500\u25ba  Embedding for \"nlp\"\n          \u2502         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n          \u2502         \u2502                ...                \u2502\n          \u2502         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n          \u2502\n          \u25bc\n  Input Embeddings\n(Dense Vectors fed to the model)\n<\/pre>\n\n<p>\nTokenization means taking text and splitting it into sub-word (and whole-word or even multi-word) units. An input text like <code>\"My cat, Blivarian, is making a mess.\"<\/code> may be tokenized into something like this:\n<\/p>\n\n<p>\nYou can explore this tokenization here:\n<a href=\"https:\/\/platform.openai.com\/tokenizer\">https:\/\/platform.openai.com\/tokenizer<\/a>\n<\/p>\n\n<p class=\"text-4xl flex\">\n  <span style=\"background-color: #d1c4e9;\">My <\/span>\n  <span style=\"background-color: #c8e6c9;\">cat<\/span>\n  <span style=\"background-color: #f0f4c3;\">, <\/span>\n  <span style=\"background-color: #ffcdd2;\">Bl<\/span>\n  <span style=\"background-color: #b3e5fc;\">iv<\/span>\n  <span style=\"background-color: #d1c4e9;\">arian<\/span>\n  <span style=\"background-color: #f0f4c3;\">, <\/span>\n  <span style=\"background-color: #c8e6c9;\"> is<\/span>\n  <span style=\"background-color: #ffcdd2;\"> making<\/span>\n  <span style=\"background-color: #b3e5fc;\"> a<\/span>\n  <span style=\"background-color: #d1c4e9;\"> mess<\/span>\n  <span style=\"background-color: #c8e6c9;\">.<\/span>\n<\/p>\n\n<p>\n[5444, 9059, 11, 3130, 569, 21203, 11, 382, 4137, 261, 13017, 13]\n<\/p>\n\n<p>\nNotice that the commas have the same token value when appearing in\ndifferent places. Also that common words like cat and mess have their\nown tokens.\n<\/p>\n\n<p>\nI deliberately made up a name for the made up Cat that is not a real\nword \"Blivarian\". You can see that it is split up into 3 sub\nwords. Without tokenization this would instead have been stored with a\nspecial \"Out of vocabulary\" token, that means it carries no semantic\nmeaning. When dealing with sub word tokens however, the LLM has the\nopportunity to build up meaning for those components that may help\nwith overall model quality.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org5b03015\" class=\"outline-3\">\n<h3 id=\"org5b03015\">Byte Pair Encoding - BPE<\/h3>\n<div class=\"outline-text-3\" id=\"text-org5b03015\">\n<\/div>\n<div id=\"outline-container-org6a0c0da\" class=\"outline-4\">\n<h4 id=\"org6a0c0da\">Why BPE?<\/h4>\n<div class=\"outline-text-4\" id=\"text-org6a0c0da\">\n<p>\nFrom above we understand that we should split words into sub-word\ncomponents to handle the vast space of human vocabulary in the finite\nspace of the LLMs vocabulary.\n<\/p>\n\n<p>\nHow to do that is the next question. Why not, for example, just have a\nvocabulary consisting of the punctuation and alphabetic characters of\nevery language?\n<\/p>\n\n<p>\nIt won't work well because in the LLM training it will build up an\nembedding vector for each token, the unit of vocabulary. This vector\nis an array of numbers that represents a direction in multidimensional\nspace. To us those numbers mean nothing, but in LLM training those\nnumbers, when used in conjunction with the rest of the models weights,\ncan be used to learn and represent all kinds of meaning.\n<\/p>\n\n<p>\nModels like Transformers have a finite context window. When sequences\nare excessively long, it becomes much harder for the model to capture\nlong-range dependencies and relationships between words that are far\napart. The model has to work harder to understand the overall context.\n<\/p>\n\n<p>\nInstead 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:\n<\/p>\n\n<p>\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Huffman_coding\">https:\/\/en.wikipedia.org\/wiki\/Huffman_coding<\/a>\n<\/p>\n\n<p>\nIt represents more frequently occurring substrings with less bits, giving us a more efficient data size.\n<\/p>\n\n<p>\nSimilarly, BPE, is data-driven algorithm that creates a vocabulary of meaningful and frequently occurring subword units.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgcab669d\" class=\"outline-4\">\n<h4 id=\"orgcab669d\">BPE algorithm<\/h4>\n<div class=\"outline-text-4\" id=\"text-orgcab669d\">\n<p>\nFirst you need to train across a large corpus of realistic text. For\nstate of the art (SOTA) LLMs this is likely in the trillions of\ncharacters of data.\n<\/p>\n\n<p>\nThe algorithm itself is very simple, it works as follows:\n<\/p>\n\n<p>\nStart with 256 tokens (0 to 255), our basic character set.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>First turn the text into its underlying numeric representation (typically just the bytes of a UTF-8 input).<\/li>\n<li>Count all the pairs of bytes.\u00a0<\/li>\n<li>Pick the most frequently occurring pair and generate the next new token (257, 258&#x2026;).<\/li>\n<li>Replace that pair wherever it occurs with the new token.<\/li>\n<\/ol>\n\n<p>\nRepeat until you have your full vocabulary. You can then save the\nmerge pairs and these are then used by end users to encode their text\nbefore sending to the model.\n<\/p>\n\n<p>\nThey can also be used to reconstruct the original text in the decoding\nprocess when the response comes from the model.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org60512a5\" class=\"outline-4\">\n<h4 id=\"org60512a5\">Conflict Resolution<\/h4>\n<div class=\"outline-text-4\" id=\"text-org60512a5\">\n<p>\nAn important decision in tokenization is how to handle pairs with the same frequency. In this post I'll consider two methods:\n<\/p>\n\n<ul class=\"org-ul\">\n<li>First in corpus wins.\u00a0<\/li>\n<li>Lexicographical ordering.<\/li>\n<\/ul>\n\n<p>\nWith any tokenization algorithm design we need to consider efficiency\nof implementation alongside methods that give the best results. Some\nof these concerns will be highlighted below.\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org12ceb67\" class=\"outline-2\">\n<h2 id=\"org12ceb67\">minbpe-cc an exercise in optimization<\/h2>\n<div class=\"outline-text-2\" id=\"text-org12ceb67\">\n<p>\nWith these algorithmic decisions in mind, I was ready to dive into the\nC++ implementation and see how they performed in practice. This led to\nmy project, minbpe-cc. I find the best way to learn a topic is to get\nmy hands dirty, and as such I decided to reimplement Karpathy's Python\ncode in C++.\n<\/p>\n\n<p>\nI also wanted to focus on optimization of the training stage, for no\nother reason than curiosity.\n<\/p>\n\n<p>\nWhy C++?\n<\/p>\n\n<ul class=\"org-ul\">\n<li>It's a low level language with generally low to zero cost abstractions.<\/li>\n<li>I've recently been catching up with modern C++ and wanted to try out some of the new features (C++23 required).<\/li>\n<\/ul>\n\n<p>\nThe final code here fully implements all the facets of Karpathy's minbpe including encoding, decoding and training. I'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.\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/minbpe-cc\">https:\/\/github.com\/justinhj\/minbpe-cc<\/a>\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org75441f7\" class=\"outline-2\">\n<h2 id=\"org75441f7\">Implementation tales<\/h2>\n<div class=\"outline-text-2\" id=\"text-org75441f7\">\n<\/div>\n<div id=\"outline-container-orgd71570e\" class=\"outline-3\">\n<h3 id=\"orgd71570e\">Speed bumps<\/h3>\n<div class=\"outline-text-3\" id=\"text-orgd71570e\">\n<p>\nConverting from Python to C++ is fairly straightforward although I hit some speed bumps on the way:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>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.<\/li>\n<li>Polymorphism. I didn't really like Karpathy'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.<\/li>\n<li>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.<\/li>\n<\/ol>\n<\/div>\n<\/div>\n<div id=\"outline-container-orgfb58706\" class=\"outline-3\">\n<h3 id=\"orgfb58706\">Regex compatibility<\/h3>\n<div class=\"outline-text-3\" id=\"text-orgfb58706\">\n<p>\nFirstly, what are regexes needed for?\u00a0\n<\/p>\n\n<p>\nIn the GPT series of tokenizers, OpenAI realized that it is beneficial to\ntry and keep parts of text together, as such rather than run BPE on\nthe whole input text, they first divide it up into sections by the\nfollowing regular expressions:\n<\/p>\n\n<ul class=\"org-ul\">\n<li>GPT2 <code>\"'(?:[sdmt]|ll|ve|re)| ?\\\\p{L}+| ?\\\\p{N}+| ?[^\\\\s\\\\p{L}\\\\p{N}]+|\\\\s+(?!\\\\S)|\\\\s+\"<\/code><\/li>\n<li>GPT4 <code>\"'(?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+\"<\/code><\/li>\n<\/ul>\n\n<p>\nThese expressions are designed to preserve various aspects of English text rather than allow them to be split up during the merge process.\n<\/p>\n\n<p>\nWhilst 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.\u00a0\n<\/p>\n\n<p>\nThese expressions need support for unicode matchers and also negative lookahead.\n<\/p>\n\n<p>\nI compared several libraries:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>RE2 from Google.<\/li>\n<li>std::regex in the C++ standard library.<\/li>\n<li>Boost::regex<\/li>\n<li>Re-Flex<\/li>\n<\/ol>\n\n<p>\nNone of these met the requirements.\u00a0\n<\/p>\n\n<p>\nIn the end I found the Perl compatible PRE2 library worked the best.\n<\/p>\n\n<p>\nThe biggest footgun was that the Boost::regex library was asserting\nbecause Boost was not linking properly with the ICU\n(internationalization) library. I suspect this could be made to work\nbut I gave up.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org268ef34\" class=\"outline-3\">\n<h3 id=\"org268ef34\">Optimization mantras<\/h3>\n<div class=\"outline-text-3\" id=\"text-org268ef34\">\n<p>\nIn System'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.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Don\u2019t do it.<\/li>\n<li>Do it, but don\u2019t do it again.<\/li>\n<li>Do it less.<\/li>\n<li>Do it later.<\/li>\n<li>Do it when they\u2019re not looking.<\/li>\n<li>Do it concurrently.<\/li>\n<li>Do it more cheaply.<\/li>\n<\/ol>\n\n<p>\nWe can refer to these during the post.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgdf21769\" class=\"outline-3\">\n<h3 id=\"orgdf21769\">Data structures<\/h3>\n<div class=\"outline-text-3\" id=\"text-orgdf21769\">\n<p>\nThe 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.\u00a0\n<\/p>\n<\/div>\n\n<div id=\"outline-container-orge5842ea\" class=\"outline-4\">\n<h4 id=\"orge5842ea\">Data<\/h4>\n<div class=\"outline-text-4\" id=\"text-orge5842ea\">\n<ul class=\"org-ul\">\n<li>Body text. We will store this as a vector (array) of numbers representing the input text for training.<\/li>\n<li>Pair frequencies. We need to keep track of all the pairs in the body text and their frequencies.\u00a0<\/li>\n<\/ul>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgee29ac0\" class=\"outline-4\">\n<h4 id=\"orgee29ac0\">Access patterns<\/h4>\n<div class=\"outline-text-4\" id=\"text-orgee29ac0\">\n<ul class=\"org-ul\">\n<li>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.<\/li>\n<li>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.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgcfe6a9b\" class=\"outline-4\">\n<h4 id=\"orgcfe6a9b\">Implementation<\/h4>\n<div class=\"outline-text-4\" id=\"text-orgcfe6a9b\">\n<\/div>\n<div id=\"outline-container-org6edd3b9\" class=\"outline-5\">\n<h5 id=\"org6edd3b9\">Body text<\/h5>\n<div class=\"outline-text-5\" id=\"text-org6edd3b9\">\n<p>\nBecause the body text required sequential access and the ability to quickly remove elements I used a singly linked list, or <code>forward_list<\/code>. This has the desirable properties of sequential access and O(1) deletions.\n<\/p>\n\n<p>\n<code>forward_list<\/code> has the lowest memory overhead of all std C++ containers (a single pointer to the next element.\n<\/p>\n\n<p>\nOther valid options considered:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Keep in a vector but use tombstones for removed items. This has the<\/li>\n<\/ol>\n<p>\n\u00a0 \u00a0advantage of eliminating the memory moves for each replacement, and\n\u00a0 \u00a0it doesn't have the problem forward list has with giving us a way\n\u00a0 \u00a0to know the position in the input text (see later). This is quite a\n\u00a0 \u00a0tricky implementation but perfectly feasible.\n<\/p>\n<ol class=\"org-ol\">\n<li>Keep in a vector and do the memory moves. Requires a lot of memory<\/li>\n<\/ol>\n<p>\n\u00a0 \u00a0bandwidth and cpu for the copying but it is simple.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org7c71903\" class=\"outline-5\">\n<h5 id=\"org7c71903\">Pair frequencies<\/h5>\n<div class=\"outline-text-5\" id=\"text-org7c71903\">\n<p>\nUltimately 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:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-c++\"><span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">PairCount<\/span> {\n<span style=\"color: #b6a0ff;\">public<\/span>:\n&#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Virtual destructor to ensure proper cleanup of derived classes.<\/span>\n&#160; &#160; <span style=\"color: #b6a0ff;\">virtual<\/span> ~PairCount() = <span style=\"color: #b6a0ff;\">default<\/span>;\n\n&#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Gets the total number of unique pairs stored.<\/span>\n&#160; &#160; <span style=\"color: #b6a0ff;\">virtual<\/span> size_t get_count() = 0;\n\n&#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Retrieves the count for a specific pair.<\/span>\n&#160; &#160; <span style=\"color: #b6a0ff;\">virtual<\/span> <span style=\"color: #6ae4b9;\">optional<\/span>&lt;<span style=\"color: #6ae4b9;\">int<\/span>&gt; get_pair(<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt; <span style=\"color: #00d3d0;\">mp<\/span>) = 0;\n\n&#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Creates a new pair or modifies the frequency of an existing one.<\/span>\n&#160; &#160; <span style=\"color: #b6a0ff;\">virtual<\/span> <span style=\"color: #6ae4b9;\">bool<\/span> create_or_modify_pair(<span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #00d3d0;\">a<\/span>, <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #00d3d0;\">b<\/span>, <span style=\"color: #6ae4b9;\">int<\/span> <span style=\"color: #00d3d0;\">freq<\/span>) = 0;\n\n&#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Gets the pair with the highest count.<\/span>\n&#160; &#160; <span style=\"color: #b6a0ff;\">virtual<\/span> <span style=\"color: #6ae4b9;\">optional<\/span>&lt;<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt;&gt; get_top_pair_count() = 0;\n\n&#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Retrieves all pairs and their counts.<\/span>\n&#160; &#160; <span style=\"color: #b6a0ff;\">virtual<\/span> <span style=\"color: #00bcff;\">std<\/span>::<span style=\"color: #6ae4b9;\">vector<\/span>&lt;<span style=\"color: #00bcff;\">std<\/span>::<span style=\"color: #6ae4b9;\">vector<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&gt; get_all() = 0;\n};\n<\/pre>\n<\/div>\n\n<p>\nNote that the class has a template parameter, as the Tokenizer can be recompiled with different underlying numeric types for the tokens.\n<\/p>\n<\/div>\n\n<ul class=\"org-ul\">\n<li><a id=\"org007443d\"><\/a>Conflict resolution strategy: First seen in input<br \/>\n<div class=\"outline-text-6\" id=\"text-org007443d\">\n<p>\nImagine a sequence as follows:\n<\/p>\n\n<p>\n1,2,8,9,3,4&#x2026;\n<\/p>\n\n<p>\nAfter counting all the pairs we find that [1,2] and [3,4] have the same frequency.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>[1,2] =&gt; 20\u00a0<\/li>\n<li>[3,4] =&gt; 20<\/li>\n<\/ol>\n\n<p>\nIn this case we pick the one added first, which means the one first seen\nin the input text.\n<\/p>\n\n<blockquote>\n<p>\nIn Python this insertion order comes for free because of Raymond\nHettinger's 2012 redesign of the Python dictionary. Implemented in\nPython 3.6 (released December 23, 2016), introduced compact\ndictionaries with key-sharing and faster performance. A side effect of\nthis redesign was that dictionaries began preserving insertion order\nas an implementation detail. This was later formalized as a language\nguarantee in Python 3.7 (released June 27, 2018), meaning dictionaries\nofficially maintain the order of key-value pairs as they are inserted.\n<\/p>\n<\/blockquote>\n\n<p>\nIn Karpathy's code you can see that he simply relies on this behaviour\nto get the consistent result based on above.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-python\"><span style=\"color: #a8a8a8;\"># <\/span><span style=\"color: #a8a8a8;\">count up the number of times every consecutive pair appears<\/span>\n<span style=\"color: #00d3d0;\">stats<\/span> = get_stats(ids)\n<span style=\"color: #a8a8a8;\"># <\/span><span style=\"color: #a8a8a8;\">find the pair with the highest count<\/span>\n<span style=\"color: #00d3d0;\">pair<\/span> = <span style=\"color: #f78fe7;\">max<\/span>(stats, key=stats.get)\n<\/pre>\n<\/div>\n\n<p>\nAnd from the Python documentation: <a href=\"https:\/\/docs.python.org\/3\/library\/functions.html#max\">https:\/\/docs.python.org\/3\/library\/functions.html#max<\/a>\n<\/p>\n\n<blockquote>\n<p>\nIf multiple items are maximal, the function returns the first one\nencountered. This is consistent with other sort-stability preserving\ntools such as sorted(iterable, key=keyfunc, reverse=True)[0] and\nheapq.nlargest(1, iterable, key=keyfunc).\n<\/p>\n\n<p>\nIn order to implement that we must track the insertion order. Rather\nthan let the user deal with that I built it into the PairCount\nclass. As elements are added, new ones get the current count and the\ncount is incremented.\n<\/p>\n<\/blockquote>\n\n<p>\nPicking a data structure here is tricky because we want to be able to\nquickly store and modify pair frequencies (unordered<sub>map<\/sub>), and a way\nto get the most frequent (priority<sub>queue<\/sub>). Furthermore, we want to\nkeep track of insertion order?\n<\/p>\n\n<p>\nSometimes you need to use multiple data structures to support a use case with conflicting requirements. For this purpose I used the <code>boost::multi_index<\/code>.\n<\/p>\n\n<p>\n<a href=\"https:\/\/www.boost.org\/doc\/libs\/1_88_0\/libs\/multi_index\/doc\/index.html\">https:\/\/www.boost.org\/doc\/libs\/1_88_0\/libs\/multi_index\/doc\/index.html<\/a>\n<\/p>\n\n<p>\nThere's nothing to stop you from using a set and a priority queue and\ntracking them yourself, but multi<sub>index<\/sub> handles that for you based on\nthe declaration of which indexes and access patterns you need.\n<\/p>\n\n<p>\nLet's take a look at the implementation of <code>PairCountInsertOrder<\/code>:\n<\/p>\n\n<p>\nFirst the data; we need to store pair, the count and the insert order.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-c++\"><span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">struct<\/span> <span style=\"color: #6ae4b9;\">PairCountOrder<\/span> {\n&#160; &#160; ::<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt; pair;\n&#160; &#160; <span style=\"color: #6ae4b9;\">int<\/span> count;\n&#160; &#160; size_t insert_order;\n\n&#160; &#160; PairCountOrder(::<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt; <span style=\"color: #00d3d0;\">p<\/span>, <span style=\"color: #6ae4b9;\">int<\/span> <span style=\"color: #00d3d0;\">c<\/span>, <span style=\"color: #6ae4b9;\">size_t<\/span> <span style=\"color: #00d3d0;\">fo<\/span>) : pair(p), count(c), insert_order(fo) {}\n&#160; &#160; PairCountOrder(::<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt; <span style=\"color: #00d3d0;\">p<\/span>, <span style=\"color: #6ae4b9;\">int<\/span> <span style=\"color: #00d3d0;\">c<\/span>) : pair(p), count(c), insert_order(<span style=\"color: #00bcff;\">std<\/span>::<span style=\"color: #00bcff;\">numeric_limits<\/span>&lt;<span style=\"color: #6ae4b9;\">size_t<\/span>&gt;::max()) {}\n};\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Comparison struct for sorting. Sorts by count (descending), then by insertion order (ascending).<\/span>\n<span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">struct<\/span> <span style=\"color: #6ae4b9;\">CompareCountOrder<\/span> {\n&#160; &#160; <span style=\"color: #6ae4b9;\">bool<\/span> <span style=\"color: #b6a0ff;\">operator<\/span>()(<span style=\"color: #b6a0ff;\">const<\/span> <span style=\"color: #6ae4b9;\">PairCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&amp; <span style=\"color: #00d3d0;\">a<\/span>, <span style=\"color: #b6a0ff;\">const<\/span> <span style=\"color: #6ae4b9;\">PairCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&amp; <span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">const<\/span> {\n&#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">if<\/span>(a.count == b.count) {\n&#160; &#160; &#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> a.insert_order &lt; b.insert_order;\n&#160; &#160; &#160; &#160; } <span style=\"color: #b6a0ff;\">else<\/span> {\n&#160; &#160; &#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> a.count &gt; b.count; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">higher count is greater<\/span>\n&#160; &#160; &#160; &#160; }\n&#160; &#160; }\n};\n<\/pre>\n<\/div>\n\n<p>\nNext we define the container itself. We just specify the indexes required and Boost takes care of picking the underlying data structures.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-c++\"><span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">using<\/span> <span style=\"color: #6ae4b9;\">PairCountStore<\/span> = <span style=\"color: #00bcff;\">boost<\/span>::<span style=\"color: #6ae4b9;\">multi_index_container<\/span>&lt;\n&#160; &#160; <span style=\"color: #6ae4b9;\">PairCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;,\n&#160; &#160; <span style=\"color: #6ae4b9;\">indexed_by<\/span>&lt;\n&#160; &#160; &#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Index 0: Hashed unique index on the 'pair' member for fast lookups.<\/span>\n&#160; &#160; &#160; &#160; <span style=\"color: #6ae4b9;\">hashed_unique<\/span>&lt;<span style=\"color: #6ae4b9;\">member<\/span>&lt;<span style=\"color: #6ae4b9;\">PairCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;, <span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt;, &amp;<span style=\"color: #00bcff;\">PairCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;::pair&gt;&gt;,\n&#160; &#160; &#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Index 1: Ordered non-unique index for sorting by count and insertion order.<\/span>\n&#160; &#160; &#160; &#160; <span style=\"color: #6ae4b9;\">ordered_non_unique<\/span>&lt;<span style=\"color: #6ae4b9;\">identity<\/span>&lt;<span style=\"color: #6ae4b9;\">PairCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&gt;, <span style=\"color: #6ae4b9;\">CompareCountOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&gt;\n&#160; &#160; &gt;\n&gt;;\n<\/pre>\n<\/div>\n\n<p>\nIndex 0 explanation:\nIt is hashed so we should get an O(1) lookup type, and unique meaning keys are unique, each pair can occur once only.\nThe rest of the declaration explains how to get the key for this index (use the pair member).\n<\/p>\n\n<p>\nIndex 1 explanation:\u00a0\nThis needs to be an ordered collection so we can extract the highest\nfrequency. It also needs to be non-unique (in its sort criteria),\nbecause we can have multiple elements with the same frequency.\n<\/p>\n\n<p>\nNow in our code we can grab the appropriate index depending on the\ncurrent purpose and when we make modifications to the data the boost\nlibrary will ensure the changes are synchronized across all the\nindexes in the container.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-C++\"><span style=\"color: #b6a0ff;\">auto<\/span>&amp; <span style=\"color: #00d3d0;\">index_by_key<\/span> = pcs.<span style=\"color: #b6a0ff;\">template<\/span> get&lt;0&gt;();\n<span style=\"color: #b6a0ff;\">auto<\/span> <span style=\"color: #00d3d0;\">f<\/span> = index_by_key.find(mp);\n<span style=\"color: #b6a0ff;\">if<\/span>(f != pcs.end()) {\n&#160; &#160; index_by_key.modify(f, [<span style=\"color: #00bcff;\">freq<\/span>](<span style=\"color: #6ae4b9;\">PairCountOrder<\/span>&lt;T&gt;&amp; <span style=\"color: #00d3d0;\">pc<\/span>) { pc.count += freq; });\n&#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> <span style=\"color: #00bcff;\">false<\/span>;\n} <span style=\"color: #b6a0ff;\">else<\/span> {\n&#160; &#160; pcs.insert(PairCountOrder&lt;T&gt;(mp, freq, next_insert++));\n&#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> <span style=\"color: #00bcff;\">true<\/span>;\n}\n<\/pre>\n<\/div>\n<\/div>\n<\/li>\n\n<li><a id=\"org68fb120\"><\/a>Conflict resolution strategy: Lexicographical<br \/>\n<div class=\"outline-text-6\" id=\"text-org68fb120\">\n<p>\nReferred 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:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>[1,2] =&gt; 20\u00a0<\/li>\n<li>[3,4] =&gt; 20<\/li>\n<\/ol>\n\n<p>\nThey have the same frequency so we pick pair 1) as 1 &lt; 3. The second member\nof the pair is used as the tie-breaker, and of course if both members\nare the same then they would be combined to a single entry in the\nPairCount.\n<\/p>\n\n<p>\nAgain a multi<sub>index<\/sub> container is needed here. Let's start with the data:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-c++\"><span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">struct<\/span> <span style=\"color: #6ae4b9;\">PairCountLexical<\/span> {\n&#160; &#160; ::<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt; pair;\n&#160; &#160; <span style=\"color: #6ae4b9;\">int<\/span> count;\n\n&#160; &#160; PairCountLexical(::<span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt; <span style=\"color: #00d3d0;\">p<\/span>, <span style=\"color: #6ae4b9;\">int<\/span> <span style=\"color: #00d3d0;\">c<\/span>) : pair(p), count(c) {}\n};\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Comparison struct for sorting. Sorts by count (descending), then by pair (lexical ascending).<\/span>\n<span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">struct<\/span> <span style=\"color: #6ae4b9;\">CompareLexicalOrder<\/span> {\n&#160; &#160; <span style=\"color: #6ae4b9;\">bool<\/span> <span style=\"color: #b6a0ff;\">operator<\/span>()(<span style=\"color: #b6a0ff;\">const<\/span> <span style=\"color: #6ae4b9;\">PairCountLexical<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&amp; <span style=\"color: #00d3d0;\">a<\/span>, <span style=\"color: #b6a0ff;\">const<\/span> <span style=\"color: #6ae4b9;\">PairCountLexical<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&amp; <span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">const<\/span> {\n&#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">if<\/span>(a.count == b.count) {\n&#160; &#160; &#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">if<\/span> (a.pair.first == b.pair.first) {\n&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> a.pair.second &lt; b.pair.second;\n&#160; &#160; &#160; &#160; &#160; &#160; } <span style=\"color: #b6a0ff;\">else<\/span> {\n&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> a.pair.first &lt; b.pair.first;\n&#160; &#160; &#160; &#160; &#160; &#160; }\n&#160; &#160; &#160; &#160; } <span style=\"color: #b6a0ff;\">else<\/span> {\n&#160; &#160; &#160; &#160; &#160; &#160; <span style=\"color: #b6a0ff;\">return<\/span> a.count &gt; b.count; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">higher count is greater<\/span>\n&#160; &#160; &#160; &#160; }\n&#160; &#160; }\n};\n<\/pre>\n<\/div>\n\n<p>\nAnd the container looks like this:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-c++\"><span style=\"color: #b6a0ff;\">template<\/span>&lt;<span style=\"color: #b6a0ff;\">typename<\/span> <span style=\"color: #6ae4b9;\">T<\/span>&gt;\n<span style=\"color: #b6a0ff;\">using<\/span> <span style=\"color: #6ae4b9;\">PairCountLexicalStore<\/span> = <span style=\"color: #00bcff;\">boost<\/span>::<span style=\"color: #6ae4b9;\">multi_index_container<\/span>&lt;\n&#160; &#160; <span style=\"color: #6ae4b9;\">PairCountLexical<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;,\n&#160; &#160; <span style=\"color: #6ae4b9;\">indexed_by<\/span>&lt;\n&#160; &#160; &#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Index 0: Hashed unique index on the 'pair' member for fast lookups.<\/span>\n&#160; &#160; &#160; &#160; <span style=\"color: #6ae4b9;\">hashed_unique<\/span>&lt;<span style=\"color: #6ae4b9;\">member<\/span>&lt;<span style=\"color: #6ae4b9;\">PairCountLexical<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;, <span style=\"color: #6ae4b9;\">pair<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>,<span style=\"color: #6ae4b9;\">T<\/span>&gt;, &amp;<span style=\"color: #00bcff;\">PairCountLexical<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;::pair&gt;&gt;,\n&#160; &#160; &#160; &#160; <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Index 1: Ordered non-unique index for sorting by count and lexical order.<\/span>\n&#160; &#160; &#160; &#160; <span style=\"color: #6ae4b9;\">ordered_non_unique<\/span>&lt;<span style=\"color: #6ae4b9;\">identity<\/span>&lt;<span style=\"color: #6ae4b9;\">PairCountLexical<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&gt;, <span style=\"color: #6ae4b9;\">CompareLexicalOrder<\/span>&lt;<span style=\"color: #6ae4b9;\">T<\/span>&gt;&gt;\n&#160; &#160; &gt;\n&gt;;\n<\/pre>\n<\/div>\n\n<p>\nIndex 0 explanation:\nSame as above this gives us fast insert, modify and lookup for the pair frequencies.\n<\/p>\n\n<p>\nIndex 1 explanation:\nSame as above except the outcome is different because of the implementation of <code>CompareLexicalOrder<\/code>.\n<\/p>\n<\/div>\n<\/li>\n\n<li><a id=\"orgecc25d2\"><\/a>Optimization of frequency counts<br \/>\n<div class=\"outline-text-6\" id=\"text-orgecc25d2\">\n<p>\nWhen running the code I see that the biggest cost is regenerating the\nfrequency map each step. For example when churning through wikitext (a\n500mb text corpus) it takes the Python code 28 seconds on my Macbook\nto count all the pairs.\n<\/p>\n\n<p>\nLet's work through Brendan Gregg's impactful optimizations:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Don\u2019t do it.<\/li>\n<li>Do it, but don\u2019t do it again.<\/li>\n<li>Do it less.<\/li>\n<li>Do it later.<\/li>\n<li>Do it when they\u2019re not looking.<\/li>\n<li>Do it concurrently.<\/li>\n<li>Do it more cheaply.<\/li>\n<\/ol>\n\n<p>\nDon't do it is not an option, we need those updated counts each step.\u00a0\nDo it but not again is fruitful though.\u00a0\n<\/p>\n\n<p>\nThe key insight here is that we only need to do a full frequency count\none time. Then we can incrementally update the pair frequencies as we\nwalk through doing the merge process. Essentially we are removing and\nadding a number of pairs on each replacement.\n<\/p>\n\n<p>\nI noticed that the authors of the paper mentioned this too:\u00a0\n<\/p>\n\n<p>\n\"In practice, we increase efficiency by indexing all pairs, and updating data structures incrementally.\"\n<\/p>\n\n<p>\nYou can see their incremental update code here:\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/rsennrich\/subword-nmt\/blob\/92d6139d07d30e12735a0af9e7f7f925ebe62c54\/subword_nmt\/learn_bpe.py#L159\">https:\/\/github.com\/rsennrich\/subword-nmt\/blob\/92d6139d07d30e12735a0af9e7f7f925ebe62c54\/subword_nmt\/learn_bpe.py#L159<\/a>\n<\/p>\n\n<p>\nIn addition to this optimization they use a pruning technique that\ndrops frequencies of pairs below some threshold. This makes sense\nbecause the Python max function iterates the whole collection. In my\ncase our data structures do not, so pruning is probably not worth the\nadditional complexity. Worth trying maybe?\n<\/p>\n\n<p>\nIn any case, for my lexicographical conflict strategy I do implement\nthis optimization and it is a huge win on performance as shown in the\ncharts.\n<\/p>\n\n<p>\nCrucially, it is not implemented for the first occurring strategy,\nbecause the current implementation gives now way to easily keep track\nof the first occurence of a pair in the input corpus.\n<\/p>\n<\/div>\n<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org3054bba\" class=\"outline-2\">\n<h2 id=\"org3054bba\">Next steps<\/h2>\n<div class=\"outline-text-2\" id=\"text-org3054bba\">\n<p>\nFor me the project is at a good point to move on to other things but there are some things I would do next otherwise:\n<\/p>\n<ol class=\"org-ol\">\n<li>Port to Zig. Currently I'm using Zig for some other projects and would be interested in the porting experience and how the performance compares.<\/li>\n<li>Work on different data structures for the input text to support incremental frequency counting for the first strategy.<\/li>\n<li>Optimization of the encode and decode steps.<\/li>\n<li>Implement download and conversion of GPT merges like Karpathy does in his gpt4 code.<\/li>\n<li>Look at implementations of other Tokenization algorithms.<\/li>\n<li>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.<\/li>\n<\/ol>\n<\/div>\n<\/div>\n<div id=\"outline-container-orge16fdc5\" class=\"outline-2\">\n<h2 id=\"orge16fdc5\">Conclusion<\/h2>\n<div class=\"outline-text-2\" id=\"text-orge16fdc5\">\n<p>\nI 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.\n<\/p>\n\n<p>\nAs a refresher on modern C++ this was a great project. (I recommend (Tour of C++)[<a href=\"https:\/\/www.amazon.ca\/Tour-C-2nd-Bjarne-Stroustrup\/dp\/0134997832\">https:\/\/www.amazon.ca\/Tour-C-2nd-Bjarne-Stroustrup\/dp\/0134997832<\/a>] and <a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines\">https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines<\/a>.\n<\/p>\n\n<p>\nApart 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.\n<\/p>\n<\/div>\n<\/div>\n<div id=\"outline-container-org9d17545\" class=\"outline-2\">\n<h2 id=\"org9d17545\">References<\/h2>\n<div class=\"outline-text-2\" id=\"text-org9d17545\">\n<p>\nKarpathy's youtube\n<\/p>\n\n<p>\n<a href=\"https:\/\/www.youtube.com\/watch?v=zduSFxRajkE\">https:\/\/www.youtube.com\/watch?v=zduSFxRajkE<\/a>\n<\/p>\n\n<p>\nAnd his Python code\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/karpathy\/minbpe\">https:\/\/github.com\/karpathy\/minbpe<\/a>\n<\/p>\n\n<p>\nIf you want to dive into the code or run the benchmarks yourself, you can find the full project on GitHub.\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/minbpe-cc\">https:\/\/github.com\/justinhj\/minbpe-cc<\/a>\n<\/p>\n\n<p>\nAn early paper on bpe for tokenization is \"Neural Machine Translation of Rare Words with Subword Units\"\n<\/p>\n\n<p>\n<a href=\"https:\/\/arxiv.org\/pdf\/1508.07909\">https:\/\/arxiv.org\/pdf\/1508.07909<\/a>\n<\/p>\n\n<p>\nThe original source code from the paper.\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/rsennrich\/subword-nmt\">https:\/\/github.com\/rsennrich\/subword-nmt<\/a>\n<\/p>\n\n<p>\nThanks for reading!\n<\/p>\n\n<p>\n&copy;2025 Justin Heyes-Jones. All Rights Reserved\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Wed, 30 Jul 2025 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2025\/07\/30\/journey-in-optimizing-a-bpe-tokenizer.html","guid":"http:\/\/justinhj.github.io\/2025\/07\/30\/journey-in-optimizing-a-bpe-tokenizer.html","category":["ai","cpp","c++","python","optimization","performance","llm","tokenizer"]},{"title":"The Magic of Lazy Lists","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n\n<style>\n.img.special {\n  width: 600px;\n  border:2px solid #fff;\n  box-shadow: 6px 6px 2px #ccc;\n  -moz-box-shadow: 6px 6px 2px #ccc;\n  -webkit-box-shadow: 6px 6px 2px #ccc;\n  -khtml-box-shadow: 6px 6px 2px #ccc;\n  margin-bottom: 40px;\n}\n<\/style>\n\n<figure>\n  <img class=\"img special\" src=\"..\/..\/..\/images\/dollar-gill-0V7_N62zZcU-unsplash.jpg\" border=\"0\" alt=\"A mysterious book on a table with a glowing globe\" width=\"600\"\/>\n  <figcaption>\n    Photo by <a href=\"https:\/\/unsplash.com\/@dollargill?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Dollar Gill<\/a> on <a href=\"https:\/\/unsplash.com\/s\/photos\/magic?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash<\/a>\n  <figcaption>\n<\/figure>\n\n<div id=\"outline-container-orgb7894ea\" class=\"outline-2\">\n<h2 id=\"orgb7894ea\">Introduction<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb7894ea\">\n<p>\nAs the <a href=\"https:\/\/docs.scala-lang.org\/scala3\/book\/taste-collections.html\">Scala 3 - book<\/a> points out, Scala has a rich set of collection\nclasses. As well as <code>List<\/code>, of course, it also has a solid implementation of <code>LazyList<\/code>. If you'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.\n<\/p>\n\n<p>\nScala <code>List<\/code> can represent collections of <code>zero or more<\/code>, stored as a linked list, with the details of the underlying data structure abstracted away. \nIn my video <a href=\"https:\/\/youtu.be\/7A2xuRkCZBg\">NonEmptyLists more or less<\/a> I talked about how\nyou can build a variant of <code>List<\/code> that can only be a collection with <code>one or more<\/code> items. \n<\/p>\n\n<p>\nIn this video, I will present the theory and practice of building a <code>LazyList<\/code> type, that adds the additional capability of controlling <code>when elements are evaluated<\/code>.\n<\/p>\n\n<p>\nAll the code written in this post, and the accompanying video <a href=\"https:\/\/youtu.be\/laB15gG5bjY\">The Magic of Lazy Lists<\/a> can be found in my new educational Scala library <a href=\"https:\/\/github.com\/justinhj\/duct\/\">Duct<\/a>. In order to produce this implementation I studied the code of the \nScala standard library (both the current version and history versions which are less sophisticated but also easier to read), as well as other implementations\nsuch 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.\n<\/p>\n\n<iframe width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/laB15gG5bjY\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org283ea86\" class=\"outline-2\">\n<h2 id=\"org283ea86\">Implementing Lazy Thing<\/h2>\n<div class=\"outline-text-2\" id=\"text-org283ea86\">\n<p>\n<code>LazyList<\/code> is easier to understand if you have a good grasp of different evaluation models in Scala, so let's explore that with a custom class called <code>LazyThing<\/code>.\n<\/p>\n\n<p>\nWith 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 \nthe expression <code>{println(\"evaluated\"); 10<\/code> is passed into the <code>LazyThing<\/code> constructor it is evaluated immediately and stored in the class. Later when the user calls the get method \nwe find that we just get the value; nothing is evaluated again.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span>\n   <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">get<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">lt<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>({println(<span style=\"color: #79a8ff;\">\"evaluated\"<\/span>); <span style=\"color: #00bcff;\">10<\/span>})\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">evaluated<\/span>\nlt.get\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res4: Int = 10<\/span>\n<\/pre>\n<\/div>\n\n<p>\nWhen working with a <code>LazyList<\/code> we want to be able to populate it with expressions but without having them evaluated until we are ready (what Haskell refers to\nas 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\ncall it when the user calls get, making it lazy.\n<\/p>\n\n<p>\nNow when we create the class nothing is evaluated until we call get, and then it is evaluated every time. This evaluation mode is called <code>always<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> () <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span>\n   <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">get<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a()\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">lt<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>(() <span style=\"color: #b6a0ff;\">=&gt;<\/span> {println(<span style=\"color: #79a8ff;\">\"evaluated\"<\/span>); <span style=\"color: #00bcff;\">10<\/span>})\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">scala&gt; lt.get<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">evaluated<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res15: Int = 10<\/span>\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">scala&gt; lt.get<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">evaluated<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res16: Int = 10<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThe <code>LazyList<\/code> structure is not about always evaluation though, it is about <code>lazy<\/code> or <code>call by need<\/code> evaluation. We want to be able to remember the result \nof evaluated list elements, and never evaluate them again. This <code>memoization<\/code> is the next step.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> () <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span>\n   <span style=\"color: #b6a0ff;\">var<\/span> <span style=\"color: #d0bc00;\">evaluated<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">false<\/span>\n   <span style=\"color: #b6a0ff;\">var<\/span> <span style=\"color: #d0bc00;\">value<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">_<\/span>\n   <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">get<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">if<\/span> evaluated then value\n     <span style=\"color: #b6a0ff;\">else<\/span>\n         evaluated <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">true<\/span>\n         value <span style=\"color: #b6a0ff;\">=<\/span> a()\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">lt<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>(() <span style=\"color: #b6a0ff;\">=&gt;<\/span> {println(<span style=\"color: #79a8ff;\">\"evaluated\"<\/span>); <span style=\"color: #00bcff;\">10<\/span>})\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">scala&gt; lt.get<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">evaluated<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res17: Any = ()<\/span>\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">scala&gt; lt.get<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res18: Any = 10<\/span>\n<\/pre>\n<\/div>\n\n<p>\nNow 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 \nvalues, but it also means we must be mindful of memory use and hanging on to references to the internal structure of our <code>LazyList<\/code> so as not \nto consume memory that is no longer needed.\n<\/p>\n\n<p>\nTwo final simplifications using Scala features make this much more succinct. The mechanism of passing an argument as a function executed only on first \nreference is implemented within Scala and known as call by name. Rewriting like below uses that mechanism instead.\n<\/p>\n\n<p>\nSecondly, we can replace the manual memoization code that remembers the evaluated value with <code>lazy val<\/code> which does the same thing but, again, is built into the compiler.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #f78fe7;\">lazy<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">get<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">lt<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">LazyThing<\/span>({println(<span style=\"color: #79a8ff;\">\"evaluated\"<\/span>); <span style=\"color: #00bcff;\">10<\/span>})\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">scala&gt; lt.get<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">evaluated<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res24: Int = 10<\/span>\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">scala&gt; lt.get<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res25: Int = 10<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"outline-container-org462128a\" class=\"outline-2\">\n<h2 id=\"org462128a\">Beginning LazyList<\/h2>\n<div class=\"outline-text-2\" id=\"text-org462128a\">\n<p>\nLet's begin by representing the <code>LazyList<\/code> as a <code>sealed trait<\/code>, which will be the object through which users interact with the collection.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">sealed<\/span> <span style=\"color: #b6a0ff;\">trait<\/span> <span style=\"color: #6ae4b9;\">OurLazyList<\/span>[+<span style=\"color: #00bcff;\">A<\/span>]<span style=\"color: #b6a0ff;\">:<\/span>\n   <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">head<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span>\n   <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">tail<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">OurLazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n   <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">isEmpty<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Boolean<\/span>\n<\/pre>\n<\/div>\n\n<p>\nOf note here is the <code>+A<\/code> variance notation. It's important to know about and understand variance when making libraries in Scala, slightly less\nimportant when writing application code. A short explanation of variance is that it is short for \"variance under inheritance\".\n<\/p>\n\n<p>\nLet's say we have a type <code>Loan<\/code> and two other subtypes of Loan, <code>Credit Card<\/code> and <code>Amortized Loan<\/code>. If you have some function that takes Loan \nand prints the outstanding balance, you would expect through normal rules of inheritance to be able to pass in a Credit card or an amortized \nloan 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 \nsubtyping. \n<\/p>\n\n<p>\nWhat variance under inheritance refers to, is what inheritance means when we have some parameterized type such as a collection. If I have a function \nthat 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 \nincludes variance annotations so that you can choose the variance relationship you want as needed. I'll come back to this topic in more detail in a later \nvideo.\n<\/p>\n\n\n\n<p>\n<code>LazyList<\/code> will have a companion object containing all the static methods that will be used to create and manipulate lazy lists. The first thing \nwe need is a representation of empty list. We add that to a new companion object.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">LazyList<\/span><span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">empty<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">Nothing<\/span>]<span style=\"color: #b6a0ff;\">:<\/span>\n      <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">head<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">throw<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">NoSuchElementException<\/span>(<span style=\"color: #79a8ff;\">\"Cannot get head of empty lazy list\"<\/span>)\n      <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">tail<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">throw<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">UnsupportedOperationException<\/span>(<span style=\"color: #79a8ff;\">\"No tail of empty lazy list\"<\/span>)\n      <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">isEmpty<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">true<\/span>\n<\/pre>\n<\/div>\n\n<p>\nLazy list has the type Nothing. Nothing is at the bottom of Scala's type hierarchy meaning it is the subtype of everything. Now it's not a useful type\nin itself, because you can't do anything with it, but it is really useful in this context&#x2026; our empty list is a singleton value shared by all lazy \nlists, we only need one. Why does this work? Because of the variance annotation above. We said that a list of subtypes of <code>A<\/code> would be acceptable as \nlist of <code>A<\/code>. \n<\/p>\n\n<p>\nSo now we are able to create lazy lists with nothing in them using <code>LazyList.empty<\/code>. The next step is to be able to create lists with elements inside. We will call this the <code>cons<\/code> method, \nas it will be used to construct lists one lazy element at a time.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">object LazyList continued:<\/span>\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">cons<\/span>[<span style=\"color: #00bcff;\">A<\/span>](hd<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">A<\/span>, tl<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>]<span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #f78fe7;\">lazy<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">head<\/span> <span style=\"color: #b6a0ff;\">=<\/span> hd\n  <span style=\"color: #f78fe7;\">lazy<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">tail<\/span> <span style=\"color: #b6a0ff;\">=<\/span> tl\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">isEmpty<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">false<\/span>\n<\/pre>\n<\/div>\n\n<p>\nWith this small amount of code we have a functional (no pun intended) lazy list.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">ll<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>.cons({println(<span style=\"color: #79a8ff;\">\"evaluated!\"<\/span>);<span style=\"color: #00bcff;\">10<\/span>}, <span style=\"color: #00bcff;\">LazyList<\/span>.empty)\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">nothing is printed yet!<\/span>\nll.head\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">evaluated!<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res9: Int = 10<\/span>\n\nll.head\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val res10: Int = 10<\/span>\n<\/pre>\n<\/div>\n\n<p>\nHere 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 \nevaluation happen, but subsequently we did not not. Nice.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org06dcc57\" class=\"outline-2\">\n<h2 id=\"org06dcc57\">Pattern matching and the \"cons operator\"<\/h2>\n<div class=\"outline-text-2\" id=\"text-org06dcc57\">\n<p>\nIn Scala you can construct lists using the so-called <code>cons<\/code> operator <code>::<\/code>. For example:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">l<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">1<\/span> :: <span style=\"color: #00bcff;\">2<\/span> :: <span style=\"color: #00bcff;\">3<\/span> :: <span style=\"color: #00bcff;\">List<\/span>.empty\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Creates a List[Int] = List(1, 2, 3)<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThis is convenient so Scala's standard <code>LazyList<\/code> also implements this using the syntax <code>#::<\/code>. Let's do the same for Duct. There are two things to note here:\n<\/p>\n\n<ol class=\"org-ol\">\n<li>To make this work we want #:: to be a right associative function that <code>cons<\/code>'s a new head for the list to the tail which is to the right<\/li>\n<li>The type of the operation should be a cons operation on a list.<\/li>\n<\/ol>\n\n<p>\nTo append <code>1<\/code> to the list <code>val ll = (2,3)<\/code> we need to write <code>1 #:: ll<\/code> and we want the compiler to evaluate this as:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">ll.#::(<span style=\"color: #00bcff;\">1<\/span>)\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">where the type of LL is LazyList[Int]<\/span>\n<\/pre>\n<\/div>\n\n<p>\nNote 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'll see code like the following:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">toDeferrer<\/span>[<span style=\"color: #00bcff;\">A<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Deferrer<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">Deferrer<\/span>[<span style=\"color: #00bcff;\">A<\/span>](() <span style=\"color: #b6a0ff;\">=&gt;<\/span> l)\n\n<span style=\"color: #f78fe7;\">final<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">Deferrer<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #f78fe7;\">private<\/span>[<span style=\"color: #00bcff;\">LazyList<\/span>] (<span style=\"color: #f78fe7;\">private<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">l<\/span><span style=\"color: #b6a0ff;\">:<\/span> () <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">AnyVal<\/span> {\n  <span style=\"color: #b0d6f5;\">\/** Construct a LazyList consisting of a given first element followed by elements<\/span>\n<span style=\"color: #b0d6f5;\">    *  from another LazyList.<\/span>\n<span style=\"color: #b0d6f5;\">    *\/<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">#::<\/span> [<span style=\"color: #00bcff;\">B<\/span> <span style=\"color: #b6a0ff;\">&gt;:<\/span> <span style=\"color: #00bcff;\">A<\/span>](elem<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> newLL(sCons(elem, newLL(l().state)))\n  <span style=\"color: #b0d6f5;\">\/** Construct a LazyList consisting of the concatenation of the given LazyList and<\/span>\n<span style=\"color: #b0d6f5;\">    *  another LazyList.<\/span>\n<span style=\"color: #b0d6f5;\">    *\/<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">#:::<\/span>[<span style=\"color: #00bcff;\">B<\/span> <span style=\"color: #b6a0ff;\">&gt;:<\/span> <span style=\"color: #00bcff;\">A<\/span>](prefix<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">B<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> prefix lazyAppendedAll l()\n}\n<\/pre>\n<\/div>\n\n<p>\n<a href=\"https:\/\/github.com\/scala\/scala\/blob\/39148e4ec34a5c53443dd1b25ceec2308cd097fe\/src\/library\/scala\/collection\/immutable\/LazyList.scala#L1136\">scala.collection.immutable.LazyList.scala<\/a>\n<\/p>\n\n<p>\nWith Scala 3 we can simply implement this as an extension method on the <code>LazyList<\/code> trait. Much nicer.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">extension [<span style=\"color: #00bcff;\">A<\/span>](hd<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">A<\/span>)\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">#::<\/span>(tl<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> \n   <span style=\"color: #00bcff;\">LazyList<\/span>.cons(hd, tl)\n<\/pre>\n<\/div>\n\n<p>\nNow we can create lazy lists more easily as follows:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">ll<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">1<\/span> #:: <span style=\"color: #00bcff;\">2<\/span> #:: <span style=\"color: #00bcff;\">LazyList<\/span>.empty\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">val ll: LazyList[Int] = LazyList$$anon$2@687292c5<\/span>\n<\/pre>\n<\/div>\n\n<p>\nCreating 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's add that functionality next.\n<\/p>\n\n<p>\nIn Scala you implement pattern matching on a particular type by implementing <code>unapply<\/code> on an object with that types name, in our case <code>#::<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">#::<\/span> {\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">unapply<\/span>[<span style=\"color: #00bcff;\">A<\/span>](s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Option<\/span>[(<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>])] <span style=\"color: #b6a0ff;\">=<\/span>\n        <span style=\"color: #b6a0ff;\">if<\/span> !s.isEmpty then <span style=\"color: #00bcff;\">Some<\/span>((s.head, s.tail)) <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">None<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nThe 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.\n<\/p>\n\n<p>\nNow we can write lazy code using pattern matching:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">ourMap<\/span>[<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>](ll<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>], f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  ll <span style=\"color: #b6a0ff;\">match<\/span> {\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00d3d0;\">hd<\/span> <span style=\"color: #6ae4b9;\">#::<\/span> <span style=\"color: #00d3d0;\">tl<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n      <span style=\"color: #00bcff;\">LazyList<\/span>.cons(f(hd), ourMap(tl, f))\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">_<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n      <span style=\"color: #00bcff;\">LazyList<\/span>.empty\n  }\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org026cfab\" class=\"outline-2\">\n<h2 id=\"org026cfab\">Iterating over Lazy List<\/h2>\n<div class=\"outline-text-2\" id=\"text-org026cfab\">\n<p>\nNote 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:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">map<\/span>[<span style=\"color: #00bcff;\">B<\/span>](f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #b6a0ff;\">if<\/span> isEmpty then <span style=\"color: #00bcff;\">LazyList<\/span>.empty\n  <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>.cons(f(head), tail.map(f))\n<\/pre>\n<\/div>\n\n<p>\nAnother useful function is <code>forEach<\/code>, which you can use to execute some action across the lazy list. This function highlights a couple of interesting things.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>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.<\/li>\n<li>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.<\/li>\n<\/ol>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #ff9077;\">@tailrec<\/span>\n<span style=\"color: #f78fe7;\">final<\/span> <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">forEach<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Unit<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Unit<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #b6a0ff;\">if<\/span> !isEmpty then\n    f(head)\n    tail.forEach(f)\n<\/pre>\n<\/div>\n\n<p>\nAnd you can use it as follows. Note that I'm using the <a href=\"https:\/\/github.com\/justinhj\/duct\/blob\/2ebe7e3ea25edf4c668ca6e044959396ae3cb265\/core\/src\/main\/scala\/org\/justinhj\/duct\/datatypes\/LazyList.scala#L123\">LazyList.apply<\/a> method here is a convenience to create a lazy list from a variable argument list.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">list1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">1<\/span>,<span style=\"color: #00bcff;\">2<\/span>,<span style=\"color: #00bcff;\">3<\/span>)\n\nprintln(<span style=\"color: #79a8ff;\">\"forEach list1\"<\/span>)\nlist1.forEach { a <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n  println(a)\n}\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">forEach list1<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">1<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">2<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">3<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org21af617\" class=\"outline-2\">\n<h2 id=\"org21af617\">Filtering<\/h2>\n<div class=\"outline-text-2\" id=\"text-org21af617\">\n<p>\nAnother part of the implementation worth looking at is dropping elements that pass or fail some filter, namely <code>filter<\/code> and <code>dropWhile<\/code>. Let's first think about what the semantics are here in terms of laziness.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Given a lazy list and a filter function we want the user to be able to iterate through them <code>by need<\/code>.<\/li>\n<li>When the user calls head on a lazy list where many elements fail the filter before a good one comes, many elements are evaluated.<\/li>\n<li>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.<\/li>\n<\/ol>\n\n<p>\nWe have to be careful about laziness then. Let's first think about <code>dropWhile<\/code>. This takes lazy list with all the failing elements dropped.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #ff9077;\">@tailrec<\/span>\n<span style=\"color: #f78fe7;\">final<\/span> <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">dropWhile<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Boolean<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n    <span style=\"color: #b6a0ff;\">if<\/span> isEmpty then <span style=\"color: #00bcff;\">LazyList<\/span>.empty\n    <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #b6a0ff;\">if<\/span> f(head) then tail.dropWhile(f)\n    <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #b6a0ff;\">this<\/span>\n<\/pre>\n<\/div>\n\n<p>\nNow since we want this to work on many elements potentially, it is important to be tail recursive. With <code>dropWhile<\/code> we can take list such as <code>LazyList(1,2,3,4,5)<\/code> and drop all elements less than 3. What we get back is LazyList beginning with 3.\n<\/p>\n\n<p>\nTake a moment to think about which elements have been evaluated at this point.\n<\/p>\n\n<p>\nWhether you reason about it by looking at the code or thinking about it semantically, the answer is that the 3 is evaluated and the <code>4,5<\/code> elements are in a lazy tail. <code>dropWhile<\/code> then will evaluate elements <code>up to and including the first one that should not be dropped<\/code>.\n<\/p>\n\n<p>\nOnce you implement <code>dropWhile<\/code> it can be used to implement <code>filter<\/code> with the requirements we came up with above.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">filter<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Boolean<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n    <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">dropped<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">this<\/span>.dropWhile(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> !f(a))\n    <span style=\"color: #b6a0ff;\">if<\/span> dropped.isEmpty then <span style=\"color: #00bcff;\">LazyList<\/span>.empty\n    <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>.cons(dropped.head, dropped.tail.filter(f))    \n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org2f8dc3f\" class=\"outline-2\">\n<h2 id=\"org2f8dc3f\">Infinite lists<\/h2>\n<div class=\"outline-text-2\" id=\"text-org2f8dc3f\">\n<p>\nQuite 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 \nnot 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.\n<\/p>\n\n<p>\nAs you've seen so far, I hope, the mechanisms of lazy evaluation make working with infinite lists possible and don't require a lot of work. Let's look at how what we've done so far scales effortlessly from small lists to infinite ones.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">repeat<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> a #:: repeat(a)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">from<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> n #:: from(n+<span style=\"color: #00bcff;\">1<\/span>)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">iterate<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span>)(next<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> a #:: iterate(next(a))(next)\n<\/pre>\n<\/div>\n\n<p>\nNote how these functions build on what we did so far, and give us ways to declaratively create infinite lists.\n<\/p>\n\n<p>\n<code>repeat<\/code> provides a lazy list with a head of type <code>A<\/code>. 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.\n<\/p>\n\n<p>\n<code>from<\/code> 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!\n<\/p>\n\n<p>\n<code>iterate<\/code> is a generalisation of this allowing you to take some function that creates a new A from the previous one, forever.\n<\/p>\n\n<p>\nOf course, we don't want to actually evaluate infinite lists because we don't have time for that, so you would use <a href=\"https:\/\/github.com\/justinhj\/duct\/blob\/2ebe7e3ea25edf4c668ca6e044959396ae3cb265\/core\/src\/main\/scala\/org\/justinhj\/duct\/datatypes\/LazyList.scala#L57\">take<\/a> 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't know how many of a thing you need and it may be expensive to generate them, so <code>call by need<\/code> evaluation is what we want.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orga762366\" class=\"outline-2\">\n<h2 id=\"orga762366\">Fusion of operations<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga762366\">\n<p>\nImagine the following code.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">lotsOfThings<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">List<\/span>.fill(<span style=\"color: #00bcff;\">1<\/span>)(<span style=\"color: #00bcff;\">10000000<\/span>)\nlotsOfThings.map(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> expensiveCalculation(a)).filter(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a &lt; <span style=\"color: #00bcff;\">10<\/span>).map(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> expensiveCalculation2(a)).take(<span style=\"color: #00bcff;\">10<\/span>).sum\n<\/pre>\n<\/div>\n\n<p>\nWith a strictly evaluated list what happens here?\n<\/p>\n\n<ol class=\"org-ol\">\n<li><code>map<\/code> will iterate over the large list, doing expensiveCalculation 10m times and making a new list of 10m elements.<\/li>\n<li><code>filter<\/code> will walk that new list and create a new list with up to 10m elements that pass the filter.<\/li>\n<li><code>map<\/code> will take those elements and create a new list after calling expensiveCalculation2 on each element<\/li>\n<li><code>take<\/code> will drop all elements after the 10th one<\/li>\n<li><code>sum<\/code> iterates over the elements<\/li>\n<\/ol>\n\n<p>\nWhilst 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 <code>potentially<\/code> much more efficient way of working.\n<\/p>\n\n<p>\nThe same code as a lazy list would work this way.\n<\/p>\n\n<ol class=\"org-ol\">\n<li value=\"1\"><code>map<\/code> takes the large list and returns a lazy list where, when evaluated, head will have expensiveCalculation applied to it. This is O(1).<\/li>\n<li value=\"2\"><code>filter<\/code> will internally call <code>dropWhile<\/code>. Let's pretend the filter is true because a &lt; 10 and we return a new lazy list with the filter but paused at the first element.<\/li>\n<li value=\"3\"><code>map<\/code> will take that list and again, return a new lazy list that is unevaluated and ready to run expensiveCalculation2 if anyone asks.<\/li>\n<\/ol>\n\n<p>\nObservation&#x2026; we are turning our list of values into a <code>list of delayed computations<\/code>. This takes up more memory than a list of values because each step is wrapped in a Function object.\n<\/p>\n\n<ol class=\"org-ol\">\n<li value=\"4\"><code>take<\/code> 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.<\/li>\n<li value=\"5\"><code>sum<\/code> okay now we're going to do a bit more work. sum calls <code>foldLeft<\/code> (see below), which by definition must evaluate all the items and combine them to a single result<\/li>\n<\/ol>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #ff9077;\">@tailrec<\/span>\n<span style=\"color: #f78fe7;\">final<\/span> <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">foldLeft<\/span>[<span style=\"color: #00bcff;\">B<\/span>](z<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span>)(f<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">B<\/span>, <span style=\"color: #00bcff;\">A<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n    <span style=\"color: #b6a0ff;\">if<\/span> isEmpty then z\n    <span style=\"color: #b6a0ff;\">else<\/span> tail.foldLeft(f(z, head))(f)\n<\/pre>\n<\/div>\n\n<ol class=\"org-ol\">\n<li value=\"6\">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 <code>only as often as needed<\/code> to evaluate the 10 elements.<\/li>\n<\/ol>\n\n<p>\nThis is all rather hard to conceptualize, so here's a picture that may help. The call stack shown in the middle of the <code>foldLeft<\/code> shows that the lazy list we evaluate consists of a stack of function calls that are waiting to happen.\n<\/p>\n\n<img class=\"img\" src=\"..\/..\/..\/images\/nestedlazylist.png\" border=\"0\" style=\"padding: 30px;\" alt=\"A callstack snapshot\" width=\"600\"\/>\n\n<p>\nFusion 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.\n<\/p>\n\n<p>\nThis gives us some insight on when to use a lazy list (or equivalent structures such as streams, iterators), rather than concrete immutable containers.\n<\/p>\n\n<p>\nUse lazy lists when you need to execute an expensive sequence of operations and you don't expect to consume the majority of the collection.\n<\/p>\n\n<p>\nYou need to use some discretion here. If you can't guarantee that the whole list won't be executed, it'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).\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgf4d244e\" class=\"outline-2\">\n<h2 id=\"orgf4d244e\">Laziness for convenience<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgf4d244e\">\n<p>\nSome algorithms require you to provide a list of things but you don't know how many things you need in advance. Here's an example that appears in the paper <a href=\"https:\/\/www.staff.city.ac.uk\/~ross\/papers\/Applicative.html\">Applicative Programming with Effects<\/a> that transposes a matrix.\n<\/p>\n\n<p>\nYou can see this code also in my post about the paper at <a href=\".\/2020\/04\/04\/whats-ap.html\">What's Ap?<\/a>, although the coverage there is more about how this operation can be written in \"the applicative style\".\n<\/p>\n\n<p>\nFirst, let's represent a 2-dimensional matrix as a lazy list of lazy lists.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">matrix<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>(\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">11<\/span>, <span style=\"color: #00bcff;\">12<\/span>, <span style=\"color: #00bcff;\">13<\/span>, <span style=\"color: #00bcff;\">14<\/span>, <span style=\"color: #00bcff;\">15<\/span>),\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">21<\/span>, <span style=\"color: #00bcff;\">22<\/span>, <span style=\"color: #00bcff;\">23<\/span>, <span style=\"color: #00bcff;\">24<\/span>, <span style=\"color: #00bcff;\">25<\/span>),\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">31<\/span>, <span style=\"color: #00bcff;\">32<\/span>, <span style=\"color: #00bcff;\">33<\/span>, <span style=\"color: #00bcff;\">34<\/span>, <span style=\"color: #00bcff;\">35<\/span>)\n)\n<\/pre>\n<\/div>\n\n<p>\nThe idea of transposing a matrix is you \"rotate\" 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.\n<\/p>\n\n<p>\nRotated by hand and represented in code, this 3 by 5 matrix should be transposed to the following.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">matrix<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">LazyList<\/span>(\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">11<\/span>, <span style=\"color: #00bcff;\">21<\/span>, <span style=\"color: #00bcff;\">31<\/span>),\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">12<\/span>, <span style=\"color: #00bcff;\">22<\/span>, <span style=\"color: #00bcff;\">32<\/span>),\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">13<\/span>, <span style=\"color: #00bcff;\">23<\/span>, <span style=\"color: #00bcff;\">33<\/span>),\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">14<\/span>, <span style=\"color: #00bcff;\">24<\/span>, <span style=\"color: #00bcff;\">34<\/span>),\n  <span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #00bcff;\">15<\/span>, <span style=\"color: #00bcff;\">25<\/span>, <span style=\"color: #00bcff;\">35<\/span>)\n)\n<\/pre>\n<\/div>\n\n<p>\nIn order to implement this a nicely functional, declarative way, we first need a helper function <code>zipWith<\/code> that takes two empty lists and lets us combine them with a function.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">zipWith<\/span>[<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>, <span style=\"color: #00bcff;\">C<\/span>](as<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>], bs<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">B<\/span>])\n  (f<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">C<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">C<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> as.zip(bs).map { <span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">a<\/span>, <span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> f(a, b) }\n<\/pre>\n<\/div>\n\n<p>\nAn 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 \nzip together two lists, one of which is infinite and the other is bounded. That's the technique used here.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">transpose<\/span>[<span style=\"color: #00bcff;\">A<\/span>](\n    matrix<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>]])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">LazyList<\/span>[<span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #b6a0ff;\">if<\/span> matrix.isEmpty then <span style=\"color: #00bcff;\">LazyList<\/span>.repeat(<span style=\"color: #00bcff;\">LazyList<\/span>.empty) then\n  <span style=\"color: #b6a0ff;\">else<\/span> zipWith(matrix.head, transpose(matrix.tail))(<span style=\"color: #b6a0ff;\">_<\/span> #:: <span style=\"color: #b6a0ff;\">_<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nIs it easy to understand? No, it takes a bit of thinking about to understand what is going on (as an exercise I'd suggest adding some println to see how it works). What's more \ninteresting 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 \nmake any mistakes. Even though matrix transpose is simple, functional programming <code>scales up<\/code> to bigger more complex programs, whereas the imperative version is more \nof a one-off implementation.\n<\/p>\n\n<p>\nThe \"trick\" in the code above is in the <code>LazyList.repeat<\/code>. 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 \nhere is an infinite number, and let the zip figure out when to stop?\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org946c355\" class=\"outline-2\">\n<h2 id=\"org946c355\">Folding left and right<\/h2>\n<div class=\"outline-text-2\" id=\"text-org946c355\">\n<p>\nThere are a couple of interesting things to say about folding lazy lists. Firstly let's look at stack safety.\n<\/p>\n\n<p>\nAs we saw earlier the amount of memory used by a lazy list can be\nhigher than with a regular list since with fusion between operations\nwe can end up with a stack of function objects before it is\nevaluated. For that reason and just in general we may want to operate\non large lists, it's important to consider which operations are stack\nsafe and which are not.\n<\/p>\n\n<p>\nFor a stack safe function I present <code>foldLeft<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #ff9077;\">@tailrec<\/span>\n<span style=\"color: #f78fe7;\">final<\/span> <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">foldLeft<\/span>[<span style=\"color: #00bcff;\">B<\/span>](z<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span>)(f<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">B<\/span>, <span style=\"color: #00bcff;\">A<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #b6a0ff;\">if<\/span> isEmpty then z\n  <span style=\"color: #b6a0ff;\">else<\/span> tail.foldLeft(f(z, head))(f)\n<\/pre>\n<\/div>\n\n<p>\nThis is a so-called aggregate function that takes a collection, in this case, iterates over it and produces some aggregate value. The supplied function\nfrom the user is applied to each element along with some accumulating value. In the case of this implementation, the foldLeft recursive call is in <code>tail position<\/code> \nwhich 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">incN<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>, inc<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #00bcff;\">LazyList<\/span>.cons(n, incN(n + inc, inc))\n\nprintln(\n  incN(<span style=\"color: #00bcff;\">1<\/span>, <span style=\"color: #00bcff;\">1<\/span>).take(<span style=\"color: #00bcff;\">10000000<\/span>).foldLeft(<span style=\"color: #00bcff;\">BigInt<\/span>(<span style=\"color: #00bcff;\">0<\/span>)) { <span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">acc<\/span>, <span style=\"color: #00d3d0;\">a<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> acc + a }\n)\n<\/pre>\n<\/div>\n\n<p>\nThis function adds up 10m integers and as such takes up a lot of stack space and crashes. Except it doesn't! Why? Because of the tail call optimization.\n<\/p>\n\n<p>\nNow 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.\n<\/p>\n\n<p>\nMake 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<sub>OPTS<\/sub> for IDE's and so on).\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-bash\"><span style=\"color: #00d3d0;\">SBT_OPTS<\/span>=<span style=\"color: #79a8ff;\">\"-XX:+UseG1GC -Xmx4G\"<\/span> sbt\n<\/pre>\n<\/div>\n\n<p>\nSo foldLeft is stack safe, how about foldRight?\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">foldRight<\/span>[<span style=\"color: #00bcff;\">B<\/span>](z<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)(f<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #b6a0ff;\">if<\/span> isEmpty then z\n  <span style=\"color: #b6a0ff;\">else<\/span> f(head, tail.foldRight(z)(f))\n<\/pre>\n<\/div>\n\n<p>\nNote that the problem here is that the recursive call is not a tail\ncall position, in this case, the user function <code>f<\/code> is. That means we\ncan't use the tailrec annotation and it will not be tail call\noptimized.\n<\/p>\n\n<p>\nCan we infer from this situation that <code>foldRight<\/code> is useless? No actually. It has a property that foldLeft does not, that of being able to <code>terminate early<\/code>. Just like with fusion of operations, \nthe early termination of <code>foldRight<\/code> can be used to save us work, and make code more efficient.\n<\/p>\n\n<p>\nHow does that work? The \"trick\" here is that the second argument of the user function, the accumulator, is a call by-name value. It's lazy! That means we don't have to evaluate it.\n<\/p>\n\n<p>\nThis example code uses <code>foldRight<\/code> to find \"tuna\" in a list of fish. \n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">hasTuna<\/span>(ll<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">LazyList<\/span>[<span style=\"color: #00bcff;\">String<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Boolean<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  ll.foldRight(<span style=\"color: #00bcff;\">false<\/span>){\n    (next, z) <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n      println(next)\n      <span style=\"color: #b6a0ff;\">if<\/span> next == <span style=\"color: #79a8ff;\">\"tuna\"<\/span> then\n        <span style=\"color: #00bcff;\">true<\/span>\n      <span style=\"color: #b6a0ff;\">else<\/span>\n        z\n  }\n\nhasTuna(<span style=\"color: #00bcff;\">LazyList<\/span>(<span style=\"color: #79a8ff;\">\"salmon\"<\/span>, <span style=\"color: #79a8ff;\">\"shark\"<\/span>, <span style=\"color: #79a8ff;\">\"tuna\"<\/span>, <span style=\"color: #79a8ff;\">\"moray\"<\/span>, <span style=\"color: #79a8ff;\">\"goldfish\"<\/span>, <span style=\"color: #79a8ff;\">\"eel\"<\/span>))\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">prints:<\/span>\n<span style=\"color: #a8a8a8;\">\/\/   <\/span><span style=\"color: #a8a8a8;\">salmon<\/span>\n<span style=\"color: #a8a8a8;\">\/\/   <\/span><span style=\"color: #a8a8a8;\">shark<\/span>\n<span style=\"color: #a8a8a8;\">\/\/   <\/span><span style=\"color: #a8a8a8;\">tuna<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThis is simply not possible with foldLeft, nor is it possible if you don't use a call by-name argument for the accumulator in foldRight. If you're not sure why it is not possible for \nfoldLeft, try putting some println statements into things that you foldLeft and foldRight and see the order in which things are done.\n<\/p>\n\n<p>\nBy the way, if you try this with the standard library you'll find it does not work the same way. The signature of foldRight is as follows:\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">foldRight<\/span>[<span style=\"color: #00bcff;\">B<\/span>](z<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span>)(op<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span>\n<\/pre>\n<\/div>\n\n<p>\nWithout 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\ndiscussion on this, for example. \n<\/p>\n\n<p>\n<a href=\"https:\/\/stackoverflow.com\/questions\/7830471\/foldright-on-infinite-lazy-structure\">https:\/\/stackoverflow.com\/questions\/7830471\/foldright-on-infinite-lazy-structure<\/a>\n<a href=\"http:\/\/voidmainargs.blogspot.com\/2011\/08\/folding-stream-with-scala.html\">http:\/\/voidmainargs.blogspot.com\/2011\/08\/folding-stream-with-scala.html<\/a>\n<\/p>\n\n<p>\nAs noted in the second example the following code will work with a lazy aware foldRight only.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #00bcff;\">LazyList<\/span>.repeat(<span style=\"color: #00bcff;\">true<\/span>).foldRight(<span style=\"color: #00bcff;\">false<\/span>){<span style=\"color: #b6a0ff;\">_<\/span> || <span style=\"color: #b6a0ff;\">_<\/span>}\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orge975925\" class=\"outline-2\">\n<h2 id=\"orge975925\">Last words<\/h2>\n<div class=\"outline-text-2\" id=\"text-orge975925\">\n<p>\nMaybe 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 \nwith 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 \nlazy lists in some depth will hopefully help your way of thinking in your day to day Scala code!\n<\/p>\n\n<p>\nThanks 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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org9f10093\" class=\"outline-2\">\n<h2 id=\"org9f10093\">References<\/h2>\n<div class=\"outline-text-2\" id=\"text-org9f10093\">\n<p>\nFunctional Programming in Scala (aka the red book) - has a great chapter on lazy lists\n<a href=\"https:\/\/www.manning.com\/books\/functional-programming-in-scala\">Functional Programming in Scala - Manning Press<\/a>\n<\/p>\n\n<p>\nLazyList Scala standard library 2.13 - modern day production ready code\n<a href=\"https:\/\/www.scala-lang.org\/api\/2.13.x\/scala\/collection\/immutable\/LazyList.html\">https:\/\/www.scala-lang.org\/api\/2.13.x\/scala\/collection\/immutable\/LazyList.html<\/a>\n<\/p>\n\n<p>\nStream from Scala standard library 2.7 - older and simpler version which I found easier to understand\n<a href=\"https:\/\/github.com\/scala\/scala\/blob\/v2.7.7\/src\/library\/scala\/Stream.scala\">https:\/\/github.com\/scala\/scala\/blob\/v2.7.7\/src\/library\/scala\/Stream.scala<\/a>\n<\/p>\n\n<p>\nScalaz Ephemeral Stream - did some things I liked too\n<a href=\"https:\/\/github.com\/scalaz\/scalaz\/blob\/ea81ca782a634d4cd93c56529c082567a207c9f6\/core\/src\/main\/scala\/scalaz\/EphemeralStream.scala\">https:\/\/github.com\/scalaz\/scalaz\/blob\/ea81ca782a634d4cd93c56529c082567a207c9f6\/core\/src\/main\/scala\/scalaz\/EphemeralStream.scala<\/a>\n<\/p>\n\n<p>\nAll of the code for the Lazy List class can be found in the Duct library here\n<a href=\"https:\/\/github.com\/justinhj\/duct\/blob\/video17\/core\/src\/main\/scala\/org\/justinhj\/duct\/datatypes\/LazyList.scala\">https:\/\/github.com\/justinhj\/duct\/blob\/video17\/core\/src\/main\/scala\/org\/justinhj\/duct\/datatypes\/LazyList.scala<\/a>\nIf 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.\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Sat, 05 Nov 2022 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2022\/11\/05\/magic-of-lazy-lists.html","guid":"http:\/\/justinhj.github.io\/2022\/11\/05\/magic-of-lazy-lists.html","category":["pure-functional-programming","cats","scala","applicative","monads","comonads","kleisli","zio","popular"]},{"title":"Monad Transformers - the prelude to ZPure","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n\n<div style=\"padding: 30px;\">\n  <img class=\"img\" src=\"..\/..\/..\/images\/monadtransformers.png\" border=\"1\" alt=\"Diagram of monad transformers with the ZPure type\" width=\"600\"\/>\n<\/div>\n\n<div id=\"outline-container-orga6db714\" class=\"outline-2\">\n<h2 id=\"orga6db714\">Readers and Writers and Transformers<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga6db714\">\n<p>\nBTW you can check out the video here instead: \n<a href=\"https:\/\/youtu.be\/tEnZZlOn-jI\">Functional Justin - Another Angle on Monad Transformers<\/a>\n<\/p>\n\n<p>\nThere are twenty pages here or over an hour of videos, so let me help you decide if it's worth your time.\n<\/p>\n<\/div>\n\n<div id=\"outline-container-org9365b75\" class=\"outline-3\">\n<h3 id=\"org9365b75\">Who are you?<\/h3>\n<div class=\"outline-text-3\" id=\"text-org9365b75\">\n<p>\nYou are a Scala programmer or interested in Scala and may have some Haskell or interest in pure functional programming.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org027dc19\" class=\"outline-3\">\n<h3 id=\"org027dc19\">What do I cover?<\/h3>\n<div class=\"outline-text-3\" id=\"text-org027dc19\">\n<ul class=\"org-ul\">\n<li>Introduction to Monad transformers<\/li>\n<li>Implement the WriterT monad in Scala 3 from scratch and used in a program<\/li>\n<li>Implement the ReaderT monad in Scala 3, also from scratch, and use it<\/li>\n<li>Why not both? Stack the Reader and Writer monads on top of each other<\/li>\n<li>Effect rotation and ZIO Prelude's ZPure, another approach to combining effects<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org5369a1f\" class=\"outline-2\">\n<h2 id=\"org5369a1f\">Evaluating expressions<\/h2>\n<div class=\"outline-text-2\" id=\"text-org5369a1f\">\n<p>\nIn previous blogs and videos, I've described a program that evaluates\narithmetic expressions as this is a nice testbed for various\nfunctional effects. So far I've demonstrated how by using different\ndata types and type classes one can make the same program behave\ndifferently.\n<\/p>\n\n<p>\nThis is important for a couple of reasons. It means that you can\ncompose interesting programs from smaller, well-understood components,\nand because we can understand and change the behaviour of our program\nby using different types.\n<\/p>\n\n<p>\nAs a starting point, lets begin with a version of the program that has\nerror handling using the Either data type and Numeric which is a\ngeneric implementation of numbers.\n<\/p>\n\n<p>\nIf you didn't catch up on earlier posts let's recap. An example run of\nthe program requires an environment (symbol table) provided using the\nScala 3 implicit mechanism (using the given keyword). I call eval on a\nsample expression tree which yields either a Right or a Left result\nsince I'm using Either as the result effect type.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">  given envMap<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span> -&gt; <span style=\"color: #00bcff;\">7<\/span>, <span style=\"color: #79a8ff;\">\"y\"<\/span> -&gt; <span style=\"color: #00bcff;\">6<\/span>, <span style=\"color: #79a8ff;\">\"z\"<\/span> -&gt; <span style=\"color: #00bcff;\">22<\/span>)\n\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">exp1<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Mul<\/span>(<span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"z\"<\/span>), <span style=\"color: #00bcff;\">Add<\/span>(<span style=\"color: #00bcff;\">Val<\/span>(<span style=\"color: #00bcff;\">10<\/span>), <span style=\"color: #00bcff;\">Sub<\/span>(<span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span>), <span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"y\"<\/span>))))\n\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">eval1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> eval(exp1)\n\n  println(s<span style=\"color: #79a8ff;\">\"Eval exp gives <\/span><span style=\"color: #00d3d0;\">$eval1<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">[info] running Scala3EvalEither <\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Eval exp gives Right(242)<\/span>\n\n<\/pre>\n<\/div>\n\n<p>\nI represent the errors as a Scala 3 enum which is a nice way to create\nADT's (algebraic data types), similar to how you would do it in Rust.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">EvalError<\/span> {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">InvalidSymboName<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">SymbolNotFound<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">DivisionByZero<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nThe next things to look at are an ADT to represent the program steps a return type.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">\nenum <span style=\"color: #00bcff;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]<span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">left<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>], <span style=\"color: #00d3d0;\">right<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Sub<\/span>(<span style=\"color: #00d3d0;\">left<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>], <span style=\"color: #00d3d0;\">right<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Mul<\/span>(<span style=\"color: #00d3d0;\">left<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>], <span style=\"color: #00d3d0;\">right<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Div<\/span>(<span style=\"color: #00d3d0;\">left<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>], <span style=\"color: #00d3d0;\">right<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">identifier<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n\n<span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n\n<span style=\"color: #b6a0ff;\">import<\/span> <span style=\"color: #00bcff;\">Exp<\/span>.<span style=\"color: #b6a0ff;\">_<\/span>\n\n<span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>] ?=&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nThe <code>Env<\/code> type is a simple map for strings to values that we will use\nas a symbol table so that variables can be looked up at runtime. The\n<code>?-&gt;<\/code> syntax indicates that the return type is a context function. An\nearlier blog discusses that, but in short, it allows us to thread our\nEnv symbol table through the computation easily.\n<\/p>\n\n<p>\nHere is the main body of the code.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">eval<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](exp<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  exp <span style=\"color: #b6a0ff;\">match<\/span>\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">id<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleVar(id)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Right<\/span>(value)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleAdd(l,r)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Sub<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleSub(l,r)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Div<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleDiv(l,r)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Mul<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleMul(l,r)\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleAdd<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] , r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] )<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> eval(l) + eval(r)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleSub<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] , r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] )<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> eval(l) - eval(r)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleMul<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] , r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] )<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> eval(l) * eval(r)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleDiv<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] , r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] )<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> eval(l) \/ eval(r)\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>[<span style=\"color: #00bcff;\">A<\/span>](s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  summonEnv.get(s) <span style=\"color: #b6a0ff;\">match<\/span> {\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Some<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Right<\/span>(value)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #00bcff;\">EvalError<\/span>.<span style=\"color: #00bcff;\">SymbolNotFound<\/span>)\n  }\n<\/pre>\n<\/div>\n\n<p>\nThose arithmetic operators you see are operating not on integers,\ndoubles or some other concrete type, but are working on a type A that\nhas a Numeric instance. You may wonder then how that <code>+<\/code> operator\nknows what to do? The answer is that I implemented an instance of\nNumeric for the type <code>Numeric[Either[EvalError,A]]<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Implement Numeric for EvalResult<\/span>\ngiven evalResultNumeric[<span style=\"color: #00bcff;\">A<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>]<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">with<\/span> {\n\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>], fb<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n    fa.map2(fb)((a,b) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + b)\n  }\n  <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">... and so on<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nWhilst this is a lot of overhead for a simple program, as your\nprograms scale in complexity, this level of abstraction lets you\ncontrol effects as well as swap them in and out as your requirements\nchange without having to rewrite the core logic.\n<\/p>\n\n<p>\nAs an example, let's introduce a Monad Transformer and show how to\nintegrate it with the program above.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org1d9e441\" class=\"outline-2\">\n<h2 id=\"org1d9e441\">WriterT<\/h2>\n<div class=\"outline-text-2\" id=\"text-org1d9e441\">\n<p>\nLet's say we want to take an existing effectful program and add a new\neffect to it. The effect I will demonstrate is logging. There is a\ndata type called Writer which represents a value and a log. \n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #00bcff;\">Writer<\/span>[<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>](run<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>))\n<\/pre>\n<\/div>\n\n<p>\nThis is not very interesting on its own but if you make a program from\nWriters, sequencing them together using the Monad's flatMap operation\nfor example, then the end result consists of a final value and a log\nfor <code>each step of the program<\/code>.\n<\/p>\n\n<p>\nBut since I already committed to using Either, if I change the type to\nWriter then I would lose the ability to handle errors. Instead what I\nwant is to keep the Either effect and <code>wrap<\/code> it with the capability of\nthe Writer monad.\n<\/p>\n\n<p>\nMonad transformers are the answer. Now the trouble with monads is that\nthey don't compose manually together. As I covered in a previous blog,\napplicatives do. You can take any two applicative effects such as\nEither and List and compose them with simple functions. \n<\/p>\n\n<p>\nWith Monads the composition of any particular monad has to be\nhand-crafted, so if I want to stack a Reader on top of an Either,\nwhich I do, then I need to implement a ReaderT (reader transformer).\n<\/p>\n\n<p>\nIt only needs to be implemented once and for all and can then be applied\nto any other Monad (not just for Either). The idea is to make an\nimplementation of Reader that wraps another Monadic data type.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>](<span style=\"color: #f78fe7;\">private<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">wrapped<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[(<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>)])\n<\/pre>\n<\/div>\n\n<p>\nHere you can see the definition of the WriterT data type. The\ndifference between WriterT and Writer is that the WriterT wraps an\nexisting monad. Note that there is no need to constrain the\nhigher-kinded type F to be a Monad, but later on when we use it in\nvarious ways it is possible to constrain F to be a Functor,\nApplicative or Monad depending on the use-case. Choosing the type\nbounds that constrain what the wrapped type must support based on the\nindividual functions needs gives you more flexibility.\n<\/p>\n\n<p>\nFor example, if you have a data type that has a map operation but no\nmeaningful way to make a flatMap, you can still use the Monad\ntransformer as long as you only use Functor level methods.\n<\/p>\n<\/div>\n\n<div id=\"outline-container-org24d8b6c\" class=\"outline-3\">\n<h3 id=\"org24d8b6c\">Lifting<\/h3>\n<div class=\"outline-text-3\" id=\"text-org24d8b6c\">\n<p>\nTo use WriterT there needs to be a mechanism to take your inner data\ntype (Either in this case) and make an instance of WriterT.  That can\nbe done like this in my implementation by using the WriterT\nconstructor. For example let's say we have an Either instance we can\ntransform it to a WriterT like this.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>,<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">10<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">w1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">WriterT<\/span>(e1.map(n <span style=\"color: #b6a0ff;\">=&gt;<\/span> (<span style=\"color: #00bcff;\">List<\/span>.empty[<span style=\"color: #00bcff;\">String<\/span>], n)))\n<\/pre>\n<\/div>\n\n<p>\nIt's not straightforward because the WriterT wrapped type must be\n<code>F[(W,A)]<\/code> and we had an F[A]. That is why I need to use the map\noperation to take any value the Either may have and combine it with an\nempty log. Here we assume the log is a list of strings and Scala is\nable to infer that too.\n<\/p>\n\n<p>\nSince this needed often the lift method is often added which takes\ncare of creating an empty log message and mapping it for us.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">WriterT<\/span><span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">lift<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">W<\/span>, <span style=\"color: #00bcff;\">A<\/span>](fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>])(using m<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monoid<\/span>[<span style=\"color: #00bcff;\">W<\/span>], <span style=\"color: #00bcff;\">F<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Functor<\/span>[<span style=\"color: #00bcff;\">F<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[<span style=\"color: #00bcff;\">F<\/span>,<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n    <span style=\"color: #00bcff;\">WriterT<\/span>(<span style=\"color: #00bcff;\">F<\/span>.map(fa)(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> (m.zero, a)))\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">... <\/span>\n\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>,<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">10<\/span>)\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">w1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[[<span style=\"color: #00bcff;\">A<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>,<span style=\"color: #00bcff;\">A<\/span>],<span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>],<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> \n    <span style=\"color: #00bcff;\">WriterT<\/span>.lift(e1)\n<\/pre>\n<\/div>\n\n<p>\nCouple of interesting things to note about the lift method type\nsignature. For one you can see that the log must be a Monoid. A Monoid\nis a type that must have two useful operations that make it useful for\nlogs: It must be able to produce an empty element of whatever type it\nis specialized for, and it must be able to join that type together.\n<\/p>\n\n<p>\nThis gives the user the flexibility to use any data type for the log\nand not have to worry about providing an empty log or an append\nfunction. The example here is a monoid since it is a list of\nstrings. Obviously we can produce an empty list, and the append\nfunction is also trivial, so if you look at my Monoid instance for\nlists you can see the implementation is trivial.\n<\/p>\n\n<p>\nAnother interesting thing is the Functor type constraint. As I\nmentioned above, although we call them Monad transformers, they can be\nused with Functors, Applicatives and Monads. Since the lift function\nonly needs map, it needs only the Functor type constraint.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org3132388\" class=\"outline-3\">\n<h3 id=\"org3132388\">Evaluating expressions with a log<\/h3>\n<div class=\"outline-text-3\" id=\"text-org3132388\">\n<p>\nNow I'll walk through the changes needed to convert the expression\nevaluator from having the return type Either, to being one of\nWriterT[Either]\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Without log<\/span>\n<span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>] ?=&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">With log<\/span>\n<span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>] ?=&gt; <span style=\"color: #00bcff;\">WriterT<\/span>[[<span style=\"color: #00bcff;\">A1<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A1<\/span>], <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>], <span style=\"color: #00bcff;\">A<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nThe next step is to make small changes to my programs implementation\nto manage this new type. As you can see, the simplest change, handling\na basic numeric value, just involves lifting our original Either and\nadding a log entry.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span class=\"linenr\">1: <\/span><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">eval<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](exp<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n<span class=\"linenr\">2: <\/span>  exp <span style=\"color: #b6a0ff;\">match<\/span>\n<span class=\"linenr\">3: <\/span>    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">id<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleVar(id)\n<span class=\"linenr\">4: <\/span>    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">WriterT<\/span>.lift[[<span style=\"color: #00bcff;\">A1<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A1<\/span>], <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>], <span style=\"color: #00bcff;\">A<\/span>](<span style=\"color: #00bcff;\">Right<\/span>(value)).tell(<span style=\"color: #00bcff;\">List<\/span>(s<span style=\"color: #79a8ff;\">\"Val <\/span><span style=\"color: #00d3d0;\">$value<\/span><span style=\"color: #79a8ff;\">\"<\/span>))\n<span class=\"linenr\">5: <\/span>    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleAdd(l,r)\n<span class=\"linenr\">6: <\/span>    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Sub<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleSub(l,r)\n<span class=\"linenr\">7: <\/span>    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Div<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleDiv(l,r)\n<span class=\"linenr\">8: <\/span>    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Mul<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleMul(l,r)\n<\/pre>\n<\/div>\n\n<p>\nYou can see in line 4 the code is a matter of lifting the value\nwrapped in an Either. The type annotation is needed and creates some\nnoise.  I use the tell function to add a log entry for this step.\n<\/p>\n\n<p>\n<code>tell<\/code> is a method on the WriterT data type itself, and it takes\nadvantage of the log types monoid to combine this new log entry with\nany prior ones. \n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">tell<\/span>(l1<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">W<\/span>)(using m<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monoid<\/span>[<span style=\"color: #00bcff;\">W<\/span>], f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Functor<\/span>[<span style=\"color: #00bcff;\">F<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[<span style=\"color: #00bcff;\">F<\/span>,<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #00bcff;\">WriterT<\/span>(wrapped.map{\n    (l2,a) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n      (m.combine(l2, l1), a)\n  })\n<\/pre>\n<\/div>\n\n<p>\nBy this technique at the end of a computation we\nshould see a log of entries.\n<\/p>\n\n<p>\nFor example, the expression <code>Val(10)<\/code> would be logged as <code>\"Val\n10\"<\/code>. Having a step-by-step log of your application has various uses\nincluding the following.\n<\/p>\n\n<ol class=\"org-ol\">\n<li>Debugging. View the state of your computation in detail<\/li>\n<li>Auditing and statistics. Analyze the log of your computation for business information.<\/li>\n<li>Restore a failed computation. You can log at each step enough information to resume an expensive computation that may have been interrupted.<\/li>\n<\/ol>\n\n<p>\nThese kinds of benefits come with traditional logging, but building it\ninto your application in a pure and type rich way can amplify the\nbenefits.\n<\/p>\n\n<p>\nLet's take a look at the symbol table lookup part of the program.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>[<span style=\"color: #00bcff;\">A<\/span>](s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  summonEnv.get(s) <span style=\"color: #b6a0ff;\">match<\/span> {\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Some<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> {\n      <span style=\"color: #00bcff;\">WriterT<\/span>.lift[[<span style=\"color: #00bcff;\">A1<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>,<span style=\"color: #00bcff;\">A1<\/span>],<span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>],<span style=\"color: #00bcff;\">A<\/span>](<span style=\"color: #00bcff;\">Right<\/span>(value)).tell(<span style=\"color: #00bcff;\">List<\/span>(s<span style=\"color: #79a8ff;\">\"Var <\/span><span style=\"color: #00d3d0;\">$s<\/span><span style=\"color: #79a8ff;\"> (<\/span><span style=\"color: #00d3d0;\">$value<\/span><span style=\"color: #79a8ff;\">)\"<\/span>))\n    }\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">WriterT<\/span>.lift(<span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #00bcff;\">EvalError<\/span>.<span style=\"color: #00bcff;\">SymbolNotFound<\/span>))\n  }\n<\/pre>\n<\/div>\n\n<p>\nAgain the change is virtually mechanical. We lifted our old code and\nadded the tell call to add some logging information. When we view\nvariable lookups in the log you will see something like <code>Var(\"x\")<\/code>\nwritten as <code>Var x (7)<\/code> where 7 is its value in the symbol table.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org44604ed\" class=\"outline-3\">\n<h3 id=\"org44604ed\">Extending numeric<\/h3>\n<div class=\"outline-text-3\" id=\"text-org44604ed\">\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleAdd<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] , r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] )<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> eval(l) + eval(r)\n<\/pre>\n<\/div>\n\n<p>\nThe remainder of the program involves expressions like this one. We\nuse the <code>+<\/code> operator to add two other expressions together. How that\nworks is a combination of operator overloading, extension methods and\nimplementing an implicit implementation of Numeric for our new WriterT\nreturn type.\n<\/p>\n\n<p>\nHere I'm defining an implicit instance of Numeric that handles things\nare Writers around Eithers. In previous posts, this is where I first\nimplemented addition for different types of number, and then added the\nability to handle errors in a type safe and functional manner.\n<\/p>\n\n<p>\nI'm just extending that technique to handle a more complicated type.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">given evalResultWNumeric[<span style=\"color: #00bcff;\">A<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>]<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">WriterT<\/span>[[<span style=\"color: #00bcff;\">A1<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A1<\/span>], <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>], <span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">with<\/span>\n  <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">... implementations<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThe implementation of Add assuming a Monadic instance is available is as follows.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">M<\/span> <span style=\"color: #b6a0ff;\">=<\/span> writerTMonad[[<span style=\"color: #00bcff;\">A1<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>,<span style=\"color: #00bcff;\">A1<\/span>], <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>]]\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>], fb<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n    <span style=\"color: #00bcff;\">M<\/span>.flatMap(fa) {\n      a <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">M<\/span>.map(fb){\n        b <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n          a + b\n      }\n    } <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  }\n<\/pre>\n<\/div>\n\n<p>\nWhich does the job but it doesn't include any logging. We can add that too.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>], fb<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n    <span style=\"color: #00bcff;\">M<\/span>.flatMap(fa) {\n      a <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">M<\/span>.flatMap(fb){\n        b <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n          <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">result<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a + b \n          <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">w1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">WriterT<\/span>.lift(<span style=\"color: #00bcff;\">Right<\/span>(result))\n          w1.tell(<span style=\"color: #00bcff;\">List<\/span>(s<span style=\"color: #79a8ff;\">\"Added <\/span><span style=\"color: #00d3d0;\">$a<\/span><span style=\"color: #79a8ff;\"> and <\/span><span style=\"color: #00d3d0;\">$b<\/span><span style=\"color: #79a8ff;\"> giving <\/span><span style=\"color: #00d3d0;\">$result<\/span><span style=\"color: #79a8ff;\">\"<\/span>))\n      }\n    }\n  }\n<\/pre>\n<\/div>\n\n<p>\nNote that by nesting the flatMaps we have access to a,b and the result\nof the computation so we can put all of that into the tell call,\nresulting in a log like <code>Added 22 and 23 giving 45<\/code>.\n<\/p>\n\n<p>\nThere's nothing really wrong with this implementation, but it's\nimportant to always think about the principle of least power. Did I\nreally need a Monad here? Well in fact there is a great function for\napplying a computation across two different effects and that is\n<code>map2<\/code>. It also requires only Applicative, so I can use that instead.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">App<\/span> <span style=\"color: #b6a0ff;\">=<\/span> writerTApplicative[[<span style=\"color: #00bcff;\">A1<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>,<span style=\"color: #00bcff;\">A1<\/span>], <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>]]\n\n <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>], fb<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n   <span style=\"color: #00bcff;\">App<\/span>.map2(fa)(fb) {\n     <span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">a<\/span>,<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + b\n   }\n }\n<\/pre>\n<\/div>\n\n<p>\nThis simplifies the code greatly but notice that I am no longer\nlogging anything. Unfortunately, I no longer have access to the result\nof the computation. One clean solution I found here was to write a\nhelper method that is like a logging version of map2. Like map2 it\ntakes a function of two arguments to map the effect values, but it\ntakes a second function that takes the two values and their result and\nlets you build a log entry from them.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mapTell2<\/span>[<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>,<span style=\"color: #00bcff;\">C<\/span>,<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">W<\/span>](fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[<span style=\"color: #00bcff;\">F<\/span>,<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">A<\/span>],fb<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[<span style=\"color: #00bcff;\">F<\/span>,<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">B<\/span>],fabc<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">C<\/span>,fabcw<span style=\"color: #b6a0ff;\">:<\/span> (<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>,<span style=\"color: #00bcff;\">C<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">W<\/span>)\n                           (using m<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monoid<\/span>[<span style=\"color: #00bcff;\">W<\/span>], f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monad<\/span>[<span style=\"color: #00bcff;\">F<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[<span style=\"color: #00bcff;\">F<\/span>,<span style=\"color: #00bcff;\">W<\/span>,<span style=\"color: #00bcff;\">C<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n   <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">r<\/span> <span style=\"color: #b6a0ff;\">=<\/span> fa.unwrap().map2(fb.unwrap()){\n     <span style=\"color: #b6a0ff;\">case<\/span> ((<span style=\"color: #00d3d0;\">al<\/span>,<span style=\"color: #00d3d0;\">a<\/span>),(<span style=\"color: #00d3d0;\">bl<\/span>,<span style=\"color: #00d3d0;\">b<\/span>)) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n       <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">c<\/span> <span style=\"color: #b6a0ff;\">=<\/span> fabc(a,b)\n       <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">w<\/span> <span style=\"color: #b6a0ff;\">=<\/span> fabcw(a,b,c)\n       <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">prev<\/span> <span style=\"color: #b6a0ff;\">=<\/span> m.combine(al,bl)\n       (m.combine(prev,w),c)\n   }\n   <span style=\"color: #00bcff;\">WriterT<\/span>(r)\n }\n<\/pre>\n<\/div>\n\n<p>\nWhile this looks like a handful what it is really doing is\nstraightforward. Like map2 the input is two effects. First I unwrap\nthem which gives us the inner effect, and running map2 on those gives\nthe log and the value of each effect.\n<\/p>\n\n<p>\nOnce I've run the user function fabc on those values, I have the\nresult value c and I can use that to build a log with the fabcw\nfunction. Finally, we need to combine the prior logs with the new log\nand return the result.\n<\/p>\n\n<p>\nHere's the function in action.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">sub<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>], b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResultW<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n     mapTell2(a,b,(a, b) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a \/ b,(a,b,c) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">List<\/span>(s<span style=\"color: #79a8ff;\">\"<\/span><span style=\"color: #00d3d0;\">$c<\/span><span style=\"color: #79a8ff;\">: subtracted <\/span><span style=\"color: #00d3d0;\">$a<\/span><span style=\"color: #79a8ff;\"> from <\/span><span style=\"color: #00d3d0;\">$b<\/span><span style=\"color: #79a8ff;\">\"<\/span>))\n}\n<\/pre>\n<\/div>\n\n<p>\nBy moving all that complexity into a helper function, each operator is now quite simple.\n<\/p>\n\n<pre class=\"example\">\n[info] running Scala3EvalEitherTWriter \nWriterT(Right((List(Var y (6), Var x (7), Val 10, Var z (22)),45)))\nVar y (6)\nVar x (7)\nVal 10\nVar z (22)\nexp01 WriterT(Left(DivisionByZero))\n<\/pre>\n\n<p>\nIn summary, you can use WriterT to convert any effectful program into\none with step-by-step logging.\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org697c96c\" class=\"outline-2\">\n<h2 id=\"org697c96c\">ReaderT<\/h2>\n<div class=\"outline-text-2\" id=\"text-org697c96c\">\n<p>\nAnother useful data type with a Monad instance is the Reader. As the\nname may imply, this is the conceptual opposite of Writer. i.e.,\ninstead of a computation writing its progress to a log, the Reader\nprovides an environment of some type that the application can read\nfrom as it progresses.\n<\/p>\n\n<p>\nIn the program so far I've been using Scala 3 context functions to\npass around the symbol table. There are reasons you may want to do\nthat with a Reader instead. Perhaps you want to take advantage of the\ncompositionality and lawfulness of Reader. Perhaps you want the\ncontext function reserved for some other purpose. Of course you may be\nusing Scala 2 and not have access to the context function feature at\nall.\n<\/p>\n\n<p>\nIn one of my videos, I show the process of replacing context functions\nwith the ReaderT monad transformer. Let's walk through the process\nhere.\n<\/p>\n\n<p>\nFirst of all let's look at the data type. Like the WriterT, the\nReaderT wraps another higher kinded type F. As you can see, there is a\nsecond type parameter R, which is the type of the read-only\nenvironment. Also, you can see from the signature is that what the\nReaderT contains is a function from R to the F[A]. How that is used\nwill become clear.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">ReaderT<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">R<\/span>,<span style=\"color: #00bcff;\">A<\/span>](run<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">R<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>])\n<\/pre>\n<\/div>\n\n<p>\nJust like with WriterT we also would benefit from a lift function that\nlets us take any instance of F and wrap it. Here I'm saying if you\nhave some effect <code>F[A]<\/code> I will give you a ReaderT that wraps it. You\ncan run it with some environment and it will yield that <code>F[A]<\/code> again.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">ReaderT<\/span><span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">lift<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">R<\/span>,<span style=\"color: #00bcff;\">A<\/span>](fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">ReaderT<\/span>[<span style=\"color: #00bcff;\">F<\/span>,<span style=\"color: #00bcff;\">R<\/span>,<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">ReaderT<\/span>(<span style=\"color: #b6a0ff;\">_<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> fa)\n<\/pre>\n<\/div>\n\n<p>\nWhen rewriting the program above we can now look up variables from the\nsymbol table. We are returning a function that when given an\nenvironment can search it for the required symbol. \n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>[<span style=\"color: #00bcff;\">A<\/span>](s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">RResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n   <span style=\"color: #00bcff;\">ReaderT<\/span>((env<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n     env.get(s) <span style=\"color: #b6a0ff;\">match<\/span> {\n       <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Some<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Right<\/span>(value)\n       <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #00bcff;\">EvalError<\/span>.<span style=\"color: #00bcff;\">SymbolNotFound<\/span>)\n     })\n<\/pre>\n<\/div>\n\n<p>\nLiteral values are also simple, just lift the Either from before.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">ReaderT<\/span>.lift(<span style=\"color: #00bcff;\">Right<\/span>(value))\n<\/pre>\n<\/div>\n\n<p>\nThe arithmetic operations don't change at all since ReaderT has an\napplicative instance we can just go ahead and use map2.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(fa<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>], fb<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n    fa.map2(fb)((a,b) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + b)\n  }\n<\/pre>\n<\/div>\n\n<p>\nHere is what needs to be done to run the code. The main difference is\nthat we build a chain of Reader effects then execute them by passing\nan environment to the run method.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">env1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span> -&gt; <span style=\"color: #00bcff;\">1<\/span>, <span style=\"color: #79a8ff;\">\"y\"<\/span> -&gt; <span style=\"color: #00bcff;\">10<\/span>, <span style=\"color: #79a8ff;\">\"z\"<\/span> -&gt; <span style=\"color: #00bcff;\">100<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">exp1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Add<\/span>(<span style=\"color: #00bcff;\">Mul<\/span>(<span style=\"color: #00bcff;\">Val<\/span>(<span style=\"color: #00bcff;\">10<\/span>), <span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"y\"<\/span>)),<span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"z\"<\/span>))\nprintln(eval(exp1).run(env1)) \n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Right(100))<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgae19976\" class=\"outline-2\">\n<h2 id=\"orgae19976\">WriterT and ReaderT<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgae19976\">\n<div style=\"padding: 30px;\">\n  <img class=\"img\" src=\"..\/..\/..\/images\/monadtransformer.png\" border=\"1\" alt=\"Diagram of monad transformers\" width=\"600\"\/>\n<\/div>\n\n<p>\nOne thing I find wonderful about functional programming is its\ncompositionality. I've shown that you can stack WriterT and ReaderT on\ntop of any effect to imbue that effect with more capabilities.\n<\/p>\n\n<p>\nNow given that WriterT can wrap a monadic effect to give that effect\nlogging, and further that ReaderT itself is a monad, it follows that\nyou can wrap WriterT around ReaderT to give some effect the powers of\nboth! This would work the other way around, and of course, you could\nalso make an EitherT monad transformer, giving even more\npossibilities.\n<\/p>\n\n<p>\nThe next step is to change the programs return type to be&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #00bcff;\">WriterT<\/span>[\n  [<span style=\"color: #00bcff;\">RA<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">ReaderT<\/span>[[<span style=\"color: #00bcff;\">EA<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">EA<\/span>], <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>],<span style=\"color: #00bcff;\">RA<\/span>],\n  <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>],\n  <span style=\"color: #00bcff;\">A<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nNext to modify the program to handle the new effect types.\n<\/p>\n\n<p>\nThe implementation to get a value is easy enough. Starting from the\ninside out the value is put into an Either, lifted into ReaderT and\nlifted once more into WriterT.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">WriterT<\/span>.lift(\n     <span style=\"color: #00bcff;\">ReaderT<\/span>.lift(\n       <span style=\"color: #00bcff;\">Right<\/span>(value))).tell(<span style=\"color: #00bcff;\">List<\/span>(s<span style=\"color: #79a8ff;\">\"Literal value <\/span><span style=\"color: #00d3d0;\">$value<\/span><span style=\"color: #79a8ff;\">\"<\/span>))\n<\/pre>\n<\/div>\n\n<p>\nHandling variable lookup we take care of the lookup first then wrap\nthat into a writer.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>[<span style=\"color: #00bcff;\">A<\/span>](s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WriterT<\/span>[[<span style=\"color: #00bcff;\">RA<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">ReaderT<\/span>[[<span style=\"color: #00bcff;\">EA<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">EA<\/span>], <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>],<span style=\"color: #00bcff;\">RA<\/span>],<span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>],<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #00bcff;\">WriterT<\/span>(<span style=\"color: #00bcff;\">ReaderT<\/span>((env<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n    env.get(s) <span style=\"color: #b6a0ff;\">match<\/span> {\n      <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Some<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">List<\/span>(s<span style=\"color: #79a8ff;\">\"Looked up var <\/span><span style=\"color: #00d3d0;\">$s<\/span><span style=\"color: #79a8ff;\"> (<\/span><span style=\"color: #00d3d0;\">$value<\/span><span style=\"color: #79a8ff;\">)\"<\/span>),value)\n      <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #00bcff;\">EvalError<\/span>.<span style=\"color: #00bcff;\">SymbolNotFound<\/span>)\n  }))\n<\/pre>\n<\/div>\n\n<p>\nI'll skip the rest of the program since the theme is the same; wrap\nthe reader code with the writer code and you're done. Let's take a\nlook at how to run the program.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">envMap<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span> -&gt; <span style=\"color: #00bcff;\">7<\/span>, <span style=\"color: #79a8ff;\">\"y\"<\/span> -&gt; <span style=\"color: #00bcff;\">6<\/span>, <span style=\"color: #79a8ff;\">\"z\"<\/span> -&gt; <span style=\"color: #00bcff;\">22<\/span>)\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">eval1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> eval(exp1).unwrap().run(envMap)\n\neval1.foreach {\n  (log, value) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n    println(s<span style=\"color: #79a8ff;\">\"Result is <\/span><span style=\"color: #00d3d0;\">$value\\n<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n    log.foreach {\n      println(<span style=\"color: #b6a0ff;\">_<\/span>)\n    }\n}\n<\/pre>\n<\/div>\n\n<p>\nHere you can see that our program has to be run sort of inside\nout. <code>eval(exp1)<\/code> gives us a <code>WriterT<\/code>. By calling <code>unwrwap<\/code> I get the\n<code>ReaderT<\/code> inside it, which I can then run by passing the environment.\n<\/p>\n\n<p>\nThe response is either an error or a tuple of our log and result,\nwhich we can then iterate over to print it out.\n<\/p>\n\n<pre class=\"example\">\nResult is 990\n\nLooked up var z (22)\nLiteral value 10\nLiteral value 2\nDivided 10 by 2 (5)\nLiteral value 2\nSubtracted 2 from 5 (3)\nLooked up var x (7)\nLooked up var y (6)\nMultiplied 7 by 6 (42)\nAdded 3 to 42 (45)\nMultiplied 22 by 45 (990)\n\n<\/pre>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org7a383cf\" class=\"outline-2\">\n<h2 id=\"org7a383cf\">Monad Transformers - some takeaways<\/h2>\n<div class=\"outline-text-2\" id=\"text-org7a383cf\">\n<p>\nYou can see that monad transformers offer some expressive power since\nthey allow us to manually combine different effect types to get the\nbenefit of them all at once. \n<\/p>\n\n<p>\nThis comes at significant cost though. All this nesting creates\nadditional JVM objects that take up heap space and may cause extra\nwork for the garbage collector. \n<\/p>\n\n<p>\nFor the programmer, the ergonomics are not great. You have to remember\nthe level of nesting you're at at each point of your program and make\nsure to do the right amount of lifting.\n<\/p>\n\n<p>\nJust look at this single simple expression. So much space is taken up\nby the type signature, all the simplicity and elegance is lost.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleAdd<\/span>[<span style=\"color: #00bcff;\">A<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] , r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>[<span style=\"color: #00bcff;\">A<\/span>] )<span style=\"color: #b6a0ff;\">:<\/span> \n  <span style=\"color: #00bcff;\">WriterT<\/span>[[<span style=\"color: #00bcff;\">RA<\/span>] =&gt;&gt; \n    <span style=\"color: #00bcff;\">ReaderT<\/span>[[<span style=\"color: #00bcff;\">EA<\/span>] =&gt;&gt; \n      <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">EA<\/span>], \n      <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>],<span style=\"color: #00bcff;\">RA<\/span>],\n    <span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>],\n    <span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> eval(l) + eval(r)\n<\/pre>\n<\/div>\n\n<p>\nNow there ways to help out the Scala compiler and reduce the amount of\nboilerplate, namely \"kinda curried type parameters\" which is a\ntechnique used heavily in Scalaz and Zio.\n<\/p>\n\n<p>\n<a href=\"https:\/\/tpolecat.github.io\/2015\/07\/30\/infer.html\">https:\/\/tpolecat.github.io\/2015\/07\/30\/infer.html<\/a>\n<\/p>\n\n<p>\nThinking that the poor type inference is maybe my fault I've also\nwritten this code using Scalaz and Cats and you can see that each\nimplementation has its pros and cons. (BTW in these libraries ReaderT\nis called Kleisli)\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/ZPurePlay\/blob\/master\/src\/main\/scala\/EvalScalaz.scala\">Reader Writer example in Scalaz<\/a>\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/ZPurePlay\/blob\/master\/src\/main\/scala\/EvalCats.scala\">Reader Writer example in Typelevel Cats<\/a>\n<\/p>\n\n<p>\nBoth implementations had the same problem as I did when not writing\nout the types in full. Scalaz had the same trouble inferring that my\ntype was applicative so I had to summon the instance explicitly.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">rwApply<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Apply<\/span>[<span style=\"color: #00bcff;\">WriterT<\/span>[<span style=\"color: #00bcff;\">List<\/span>[<span style=\"color: #00bcff;\">String<\/span>],<span style=\"color: #00bcff;\">Kleisli<\/span>[<span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">Error<\/span>,?],<span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>],?],?]]\nrwApply.apply2(x,y) {\n       <span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">a<\/span>,<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + b\n}\n<\/pre>\n<\/div>\n\n<p>\nCats was able to handle it resulting in less code and needed less type\nannotations in general.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">x.map2(y) {\n  <span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">a<\/span>,<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + b\n}\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org0f5756a\" class=\"outline-2\">\n<h2 id=\"org0f5756a\">Effect rotation with Zio Prelude's ZPure<\/h2>\n<div class=\"outline-text-2\" id=\"text-org0f5756a\">\n<p>\n<a href=\"https:\/\/github.com\/zio\/zio-prelude\">Zio Prelude<\/a> is a new library that acts as a sort of add on library to\n<a href=\"https:\/\/github.com\/zio\/zio\">ZIO<\/a> (a zero-dependency Scala library for asynchronous and concurrent\nprogramming) which provides an alternative approach to functional\nabstractions in Scala.\n<\/p>\n\n<p>\nFor the purposes of this blog I'm interested in particular\nexperimental data type within the library called <code>ZPure<\/code>. ZPure has 6\ntype parameters and supports the operations of monads, applicatives\nand functors, albeit the names are changed and some of the\nabstractions too.\n<\/p>\n\n<p>\nFrom Prelude's own source code \"<code>ZPure<\/code> can be used to model a variety\nof effects including context, state, failure, and logging.\", let's see\nhow it compares to monad transformers to implement the program above.\n<\/p>\n\n<p>\nZPure has six type parameters, which may seem like a lot, but bear in\nmind that every time you combine monads you get more type parameters,\nbut they are stacked vertically not horizontally. With ZPure you start\nwith all the different effect types one might need but you don't need\nto keep adding more and more, and you don't suffer from creating\nmultiple objects per layer of effect.\n<\/p>\n\n<div style=\"padding: 30px;\">\n  <img class=\"img\" src=\"..\/..\/..\/images\/zpure.png\" border=\"1\" alt=\"ZPure type parameters\" width=\"600\"\/>\n<\/div>\n\n<p>\nIn the diagram the parameters are.\n<\/p>\n\n<ul class=\"org-ul\">\n<li><code>W<\/code> Logging. The type of logs that this effect produces, analogous to Writer<\/li>\n<li><code>S<\/code> State. There are two S's because the type encodes an input and output state type<\/li>\n<li><code>R<\/code> Reader. The type of the read-only environment<\/li>\n<li><code>E<\/code> Error. The type of the error channel<\/li>\n<li><code>A<\/code> Value. The type of the happy path computed value<\/li>\n<\/ul>\n\n<p>\nJust as before all I need to do is change my programs effect type and\nmodify the implementation accordingly. The code for this section can\nbe found <a href=\"https:\/\/github.com\/justinhj\/ZPurePlay\/blob\/master\/src\/main\/scala\/EvalZpure.scala\">here<\/a>.\n<\/p>\n\n<p>\nAlthough Prelude supports Scala 3 now I rewrote my program in Scala 2\nin order to do the Scalaz and Cats versions, so the following is also\npre Scala 3 friendly code. First I made a sealed trait to represent\nthe error types and an alias to indicate that my log will be\nstrings. \n<\/p>\n\n<p>\nNote that ZPure is opinionated about the logging type. In the more\nconventional approach, the log has to be a monoid instance. With ZPure\nthe log is handled using the ZIO <code>Chunk<\/code> data type which is a\nhigh-performance data structure with a pure functional interface. What\nthat means for us is that we can consider our log type as a single\nentity and not worry about how it is appended.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">sealed<\/span> <span style=\"color: #b6a0ff;\">trait<\/span> <span style=\"color: #6ae4b9;\">Error<\/span>\n<span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">SymbolNotFound<\/span> <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Error<\/span>\n<span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">DivisionByZero<\/span> <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Error<\/span>\n\n<span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Log<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">String<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThese types will represent the <code>E<\/code> or error, and <code>W<\/code> or log. We can\nencode our symbol table using the <code>R<\/code> parameter.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nThe final type looks like this.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">ZPure<\/span>[<span style=\"color: #00bcff;\">Log<\/span>, <span style=\"color: #00bcff;\">Any<\/span>, <span style=\"color: #00bcff;\">Any<\/span>, <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>], <span style=\"color: #00bcff;\">Error<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nNote that I am not using the initial or updated state here so I use\nAny for those parameters so as not to constrain them.\n<\/p>\n\n<p>\nOnce again let's start with the implementation of literal values.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n  <span style=\"color: #00bcff;\">ZPure<\/span>.succeed(value).log(s<span style=\"color: #79a8ff;\">\"Literal value <\/span><span style=\"color: #00d3d0;\">$value<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nWhat's going on here is simple and refreshingly free of type\nannotation. Firstly I construct a ZPure consisting of the literal\nvalue, and then add a log using ZPure's log method. \n<\/p>\n\n<p>\nNow let's implement the symbol table lookup of variables.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span class=\"linenr\"> 1: <\/span><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>[<span style=\"color: #00bcff;\">A<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n<span class=\"linenr\"> 2: <\/span>    <span style=\"color: #00bcff;\">ZPure<\/span>.environment[<span style=\"color: #00bcff;\">Any<\/span>, <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>]].flatMap {\n<span class=\"linenr\"> 3: <\/span>      env <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n<span class=\"linenr\"> 4: <\/span>       <span style=\"color: #00bcff;\">ZPure<\/span>.fromOption(env.get(s)).\n<span class=\"linenr\"> 5: <\/span>       mapError(<span style=\"color: #b6a0ff;\">_<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">EvalZPure<\/span>.<span style=\"color: #00bcff;\">SymbolNotFound<\/span>).\n<span class=\"linenr\"> 6: <\/span>       flatMap{\n<span class=\"linenr\"> 7: <\/span>        a <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n<span class=\"linenr\"> 8: <\/span>          <span style=\"color: #00bcff;\">ZPure<\/span>.log(s<span style=\"color: #79a8ff;\">\"Var <\/span><span style=\"color: #00d3d0;\">$s<\/span><span style=\"color: #79a8ff;\"> value <\/span><span style=\"color: #00d3d0;\">$a<\/span><span style=\"color: #79a8ff;\">\"<\/span>).as(a)\n<span class=\"linenr\"> 9: <\/span>       }      \n<span class=\"linenr\">10: <\/span>    }\n<span class=\"linenr\">11: <\/span>}\n<\/pre>\n<\/div>\n\n<p>\nFirst I use the ZPure.environment to summon the symbol table and\nflatMap over it so we can access it as a concrete value <code>env<\/code>.\n<\/p>\n\n<p>\nRemember that looking up the variable in the symbol table\nis going to return an Option since it is a normal map get. We can then\nuse the ZPure.fromOption to convert that to a ZPure.\n<\/p>\n\n<p>\nWe may be a ZPure at that point but we have the wrong error type. In\nZPure and option is simulated by yielding a success value A for Some,\nor giving Unit in the error channel to indicate None. This reuse of\nthe error channel is neat, but since I would like a homogenous error\ntype for the program I need to convert that error channel from unit to\nmy own custom Error type. \n<\/p>\n\n<p>\nTo do that I use mapError which takes a function to map the error from\none type to another.\n<\/p>\n\n<p>\nThe final step is to add a log. Since I would like the log to show\nboth the variable name and the actual value I have to nest it inside a\nflatMap so we can access the success value. The last thing to note\nhere is the <code>as<\/code> which helps the type system make a ZPure of the right\ntype.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">numericZResult<\/span>[<span style=\"color: #00bcff;\">A<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>]<span style=\"color: #b6a0ff;\">:<\/span> \n  <span style=\"color: #00bcff;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>]] {\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(x<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>], y<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n      x.zip(y).flatMap{<span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">a<\/span>,<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n        <span style=\"color: #00bcff;\">ZPure<\/span>.succeed(a + b).log(s<span style=\"color: #79a8ff;\">\"Add <\/span><span style=\"color: #00d3d0;\">$a<\/span><span style=\"color: #79a8ff;\"> and <\/span><span style=\"color: #00d3d0;\">$b<\/span><span style=\"color: #79a8ff;\">\"<\/span>)}\n  }\n  <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">and so on<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThe final component is to make an instance of Numeric. Prelude takes\nthe approach to naming that concepts should be plain English where\npossible, so it uses <code>succeed<\/code> instead of <code>pure<\/code> or <code>unit<\/code> and\nsimilarly <code>zip<\/code> instead of applicative terminology.\n<\/p>\n\n<p>\nThat being the case, we use zip here to combine the left and right\nside effects and apply the appropriate arithmetic operator.\n<\/p>\n\n<p>\nSo far so good, but we can't log the result of the computation. This\nis easily solved.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(x<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>], y<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Result<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n    x.zip(y).flatMap{<span style=\"color: #b6a0ff;\">case<\/span> (<span style=\"color: #00d3d0;\">a<\/span>,<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span>  {\n      <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">result<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a + b\n      <span style=\"color: #00bcff;\">ZPure<\/span>.succeed(result).log(s<span style=\"color: #79a8ff;\">\"Add <\/span><span style=\"color: #00d3d0;\">$a<\/span><span style=\"color: #79a8ff;\"> and <\/span><span style=\"color: #00d3d0;\">$b<\/span><span style=\"color: #79a8ff;\"> (<\/span><span style=\"color: #00d3d0;\">$result<\/span><span style=\"color: #79a8ff;\">)\"<\/span>)}\n    }\n  }\n<\/pre>\n<\/div>\n\n<p>\nThe last part to note is the driver code to run the program.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">eval1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> eval(exp1).provide(env1).runAll()\n\neval1._2 <span style=\"color: #b6a0ff;\">match<\/span> {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Right<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n    println(s<span style=\"color: #79a8ff;\">\"Succeeded with value <\/span><span style=\"color: #00d3d0;\">${value._2}<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n    eval1._1.foreach {\n      l <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n        println(l)\n  }\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Left<\/span>(<span style=\"color: #00d3d0;\">err<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n    println(s<span style=\"color: #79a8ff;\">\"oops! <\/span><span style=\"color: #00d3d0;\">$err<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n}\n<\/pre>\n<\/div>\n\n<p>\nHere I run eval to create the effect, provide to give it the runtime\nenvironment and runAll. To be clear what eval does is not run a\nprogram, but build a data structure of objects based on the ZPure\noperations, and that data structure is evaluated in Prelude using an\nefficient interpreter, that yields the result of the program, the log\nand any state changes.\n<\/p>\n\n<pre class=\"example\">\nSucceeded with value 200\nLiteral value 10\nVar x value 1\nMul 10 with 1 (10)\nVar y value 10\nMul 10 with 10 (100)\nVar z value 100\nAdd 100 and 100 (200)\n<\/pre>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgcd6c223\" class=\"outline-2\">\n<h2 id=\"orgcd6c223\">Conclusion<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgcd6c223\">\n<p>\nIn this post I implemented and motivated ReaderT and WriterT and\ntransforming monads to combine effects. Even in Haskell where they\noriginated, monad transformers come with caveats about performance and\nergonomics. In Scala they are not used often.\n<\/p>\n\n<p>\nThere are techniques and libraries to make their use more\nconvenient. Although I have not used it <a href=\"https:\/\/github.com\/typelevel\/cats-mtl\">Cats MTL<\/a> offers solutions to\nsome of the problems, but it is not widely used.\n<\/p>\n\n<p>\nAlthough ZIO Prelude's ZPure is still somewhat experimental it seems\noffer the benefits of monad transformers such as composability and a\nprinicipled type safe api. But, it is also much easier to work with\nand anecdotally more performant on the JVM.\n<\/p>\n\n<p>\nIn the future I'm looking forward to exploring some traditional\nfunctional programming problems using Prelude and ZPure.\n<\/p>\n\n<p>\nHope you enjoyed this post and got to the end. You can find my contact\ndetails at the top of the page; I always welcome feedback and\nquestions.\n<\/p>\n\n<p>\n(C)2021 Justin Heyes-Jones, All Rights Reserved.\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Fri, 04 Jun 2021 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2021\/06\/04\/monad-transformers-the-prelude-to-zpure.html","guid":"http:\/\/justinhj.github.io\/2021\/06\/04\/monad-transformers-the-prelude-to-zpure.html","category":["scala","scala-3","dotty","monads","category-theory","popular"]},{"title":"Monads in Scala 3 for the Genius","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n<div id=\"outline-container-org9e88539\" class=\"outline-2\">\n<h2 id=\"org9e88539\">Introduction<\/h2>\n<div class=\"outline-text-2\" id=\"text-org9e88539\">\n<p>\nThis is a companion blog the seventh Functional Justin YouTube video\nwhich you can find here:\n<a href=\"https:\/\/www.youtube.com\/watch?v=B1FSxbmZpCE\">https:\/\/www.youtube.com\/watch?v=B1FSxbmZpCE<\/a>\n<\/p>\n\n<p>\nThe source code shown in the video and in the fragments below can be found here:\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\/blob\/video-7-r3\/src\/main\/scala\/livevideos\/Video7.scala\">https:\/\/github.com\/justinhj\/evalexample\/blob\/video-7-r3\/src\/main\/scala\/livevideos\/Video7.scala<\/a>\n<\/p>\n\n<p>\nThe goal here is to make 10-15 minute videos that each cover an\nisolated topic in pure functional programming with Scala. There is an\nalso overarching goal to cover a certain number of base topics you\nneed in functional programming. Once that is complete I will start\ndoing deep dives into FP libraries such as Cats and Zio.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgb5739ff\" class=\"outline-2\">\n<h2 id=\"orgb5739ff\">Monads for the Genius<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb5739ff\">\n<p>\nThe title may sound like clickbait, and it most surely is, but the\npoint is that for most Scala programmers, even those working with\nfunctional programming libraries, most of what you need to know about\nMonads is what the type signatures of the methods are and how you can\nleverage those in your code. For bonus points you can learn the Monad\nlaws and implement your own lawful Monad instances.\n<\/p>\n\n<p>\nIf you want to know why Monad consists of pure (or unit) and flatMap,\nand why Monads are functors (they have map) you need to dig a little\ndeeper, and for that reason I targeted this post at the genius, but\nperhaps the curious would be a better way to put it, it hopefully will\nnot be a really difficult topic to follow.\n<\/p>\n\n<p>\nIn this post and the accompanying video I will show the category\ntheory you need to understand monad and derive an implementation of\nthe monad type class from that theoretical foundation. From there the\nnext step is to show the monad in use on effects and how to implement\nand use flatMap (or bind).\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org1353719\" class=\"outline-2\">\n<h2 id=\"org1353719\">Just enough Category Theory<\/h2>\n<div class=\"outline-text-2\" id=\"text-org1353719\">\n<p>\nCategory theory is a candidate for a theory that describes all of mathematics, and has been applied to a number of areas.<sup><a id=\"fnr.1\" class=\"footref\" href=\"#fn.1\">1<\/a><\/sup>. If you want to know more about it than the very basics then I recommend Category Theory for Progammers.<sup><a id=\"fnr.2\" class=\"footref\" href=\"#fn.2\">2<\/a><\/sup>\n<\/p>\n\n<p>\nThe essence of category theory is the category itself, which consists of objects and morphisms that transition from one object to another. \n<\/p>\n\n<img class=\"img\" src=\"..\/..\/..\/images\/Categories3.png\" border=\"0\" style=\"padding: 30px;\" alt=\"Category theory diagram\" width=\"600\"\/>\n\n<p>\nIn addition there must be an identity morphism on each object. This simply gives you a way to transition from an object to itself.\n<\/p>\n\n<img class=\"img\" src=\"..\/..\/..\/images\/Categories4.png\" border=\"0\" style=\"padding: 30px;\" alt=\"Category theory diagram\" width=\"600\"\/>\n\n<p>\nMorphisms 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.\n<\/p>\n\n<img class=\"img\" src=\"..\/..\/..\/images\/Categories5.png\" border=\"0\" style=\"padding: 30px;\" alt=\"Category theory diagram\" width=\"600\"\/>\n\n<p>\nComposition must follow the associative law. As shown below that means if we have three morphisms f,g and h, it doesn't matter how we compose them as long we don't change the order they are applied. We can compose them in two different ways.\n<\/p>\n\n<img class=\"img\" src=\"..\/..\/..\/images\/Categories6.png\" border=\"0\" style=\"padding: 30px;\" alt=\"Category theory diagram\" width=\"600\"\/>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org1e6352a\" class=\"outline-2\">\n<h2 id=\"org1e6352a\">The category of Scala types and functions<\/h2>\n<div class=\"outline-text-2\" id=\"text-org1e6352a\">\n<p>\nLet'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.\n<\/p>\n\n<p>\nIn the code below we have a lawful category. The objects are the Scala\ntypes (Ints, Booleans, Strings) and the morphisms that take us from\none object to the next are ordinary Scala functions. There are three\nexamples f,g and h.\n<\/p>\n\n<p>\nRemember to be a category we need an identity morphism, which turns out to be simply the Scala <code>identity<\/code>. (A =&gt; A).\n<\/p>\n\n<p>\nThe other thing we need is a way to combine morphisms that must be associative. We have that with the built in function <code>compose<\/code>!\n<\/p>\n\n<p>\nAs you can see in the code it is straightforward to show the laws of the category are upheld.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Category of Scala functions<\/span>\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">f<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Int<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">g<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Boolean<\/span> <span style=\"color: #b6a0ff;\">=<\/span> b <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #b6a0ff;\">if<\/span>(b == <span style=\"color: #00bcff;\">1<\/span>) <span style=\"color: #00bcff;\">true<\/span> <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">false<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">h<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Boolean<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">String<\/span> <span style=\"color: #b6a0ff;\">=<\/span> c <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #b6a0ff;\">if<\/span>(c == <span style=\"color: #00bcff;\">true<\/span>) <span style=\"color: #79a8ff;\">\"Winner!\"<\/span> <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #79a8ff;\">\"Loser!\"<\/span>\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Identity<\/span>\nf.compose((a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> identity(a))(<span style=\"color: #00bcff;\">0<\/span>) == f(<span style=\"color: #00bcff;\">0<\/span>)\n\nf(<span style=\"color: #00bcff;\">0<\/span>) == f.compose((a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> identity(a))(<span style=\"color: #00bcff;\">0<\/span>)\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Composition must be associative<\/span>\nh.compose(g.compose(f))(<span style=\"color: #00bcff;\">0<\/span>) == (h.compose(g.compose(f)))(<span style=\"color: #00bcff;\">0<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nAbove you can see composing the identity function with f gives the same result as calling f alone. \n<\/p>\n\n<p>\nYou can also see that composition is associative. We compose h with g\nand f in different ways, without changing the order, and get the same\nresults.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgda19ef9\" class=\"outline-2\">\n<h2 id=\"orgda19ef9\">A monad is just a functor in the category of Kleisli arrows<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgda19ef9\">\n<p>\nWhat's the problem?\n<\/p>\n\n<p>\nWell there are two problems here. For one many readers may be saying\n\"What? Surely a monad is a just a monoid in the category of\nendofunctors!\"<sup><a id=\"fnr.3\" class=\"footref\" href=\"#fn.3\">3<\/a><\/sup>\n<\/p>\n\n<p>\nPerhaps another group are completely lost. Well the famous quote about\nmonads is absolutely right, but that is a different way to arrive at\nMonads than the simpler one we are looking at here.\n<\/p>\n\n<p>\nInstead we will arrive at Monads by making a simple change to the\nCategory of Scala types and functions. The only change we will make is\ninstead of Scala functions of the form <code>A =&gt; B<\/code> we will instead use\nwhat is known as a Kliesli arrow, which has the form <code>\"A =&gt; F[B]<\/code>.\n<\/p>\n\n<p>\nYou may recognize that shape of function from the argument to Scala's\nflatMap. In other words it is the type of function that maps a pure\nvalue to an effectful value.\n<\/p>\n\n<p>\nLet's look at how we can encode this new category directly in Scala as a monad!\n<\/p>\n\n<p>\nNote I will call the Monad type class Monad1 to avoid confusion with\nthe more usual Monad definition in the code.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">trait<\/span> <span style=\"color: #6ae4b9;\">Monad1<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>]]<span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">unit<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span><span style=\"color: #6ae4b9;\">A<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>]\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">compose<\/span>[<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>,<span style=\"color: #00bcff;\">C<\/span>](lf<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">B<\/span>], rf<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">C<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">C<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nIn the definition above we have all we need to implement the category\nof Scala objects and Kliesli arrows (and incidentally this is, by\ndefinition, a monad).\n<\/p>\n\n<p>\nFirstly what are the objects? Just like before the objects are Scala types.\n<\/p>\n\n<p>\nNext what are the morphisms? We stated the morphisms would be of the form <code>A =&gt; F[B]<\/code>.\n<\/p>\n\n<p>\nFinally what is the identity? The identity has the same form as any\nother morphism except that it maps a type to itself, so the identity\nis <code>A =&gt; F[A]<\/code>. We can implement that in Scala with the <code>unit<\/code>\nfunction above.\n<\/p>\n\n<p>\nWith Scala functions we used the compose function. Here we need to\nwrite our own code that composes two Kleisli arrows returning a new\none. This is the direct analog of the compose function that works with\nsimple functions.\n<\/p>\n\n<p>\nFor convenience, just like with any other Scala 3 type class we need a\nway to summon a Monad of a particular type into existence and for that\nwe write the apply function as follows.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">Monad1<\/span><span style=\"color: #b6a0ff;\">:<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">apply<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>]](using m<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monad1<\/span>[<span style=\"color: #00bcff;\">F<\/span>]) <span style=\"color: #b6a0ff;\">=<\/span> m\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org4f60c84\" class=\"outline-2\">\n<h2 id=\"org4f60c84\">Implementation of Monad for Option<\/h2>\n<div class=\"outline-text-2\" id=\"text-org4f60c84\">\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">given optionMonad1<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monad1<\/span>[<span style=\"color: #00bcff;\">Option<\/span>] <span style=\"color: #b6a0ff;\">with<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">unit<\/span>[<span style=\"color: #00bcff;\">A<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span><span style=\"color: #6ae4b9;\">A<\/span>) <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Option<\/span>(a)\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">compose<\/span>[<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>,<span style=\"color: #00bcff;\">C<\/span>](lf<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Option<\/span>[<span style=\"color: #00bcff;\">B<\/span>], rf<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Option<\/span>[<span style=\"color: #00bcff;\">C<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Option<\/span>[<span style=\"color: #00bcff;\">C<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n    a <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n      lf(a) <span style=\"color: #b6a0ff;\">match<\/span> {\n        <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Some<\/span>(<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n          rf(b) <span style=\"color: #b6a0ff;\">match<\/span> {\n            <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Some<\/span>(<span style=\"color: #00d3d0;\">b<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> rf(b)\n            <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">None<\/span>\n          }\n        <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">None<\/span>          \n      } \n  }\n<\/pre>\n<\/div>\n\n<p>\nYou can see that unit is just a call to the Option constructor, whilst\ncompose will return a new function that first applies <code>lf<\/code> to the\ninput, then if that yields a value and not a None, it will apply <code>rf<\/code>\nto that yielding a new Option. Please note I made an overly complex\nversion of this in the video, and only realized once it was too late.\n<\/p>\n\n<p>\nNow we can write code that composes \"effect generating\" functions (or\nKliesli arrows) together. Here I make three simple functions that\noperate on Scala values and produce Options.\n<\/p>\n\n<p>\nHere we use the Monad1 option to compose f,g and h&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">f<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span><span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Option<\/span>[<span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">if<\/span> n == <span style=\"color: #00bcff;\">4<\/span> then <span style=\"color: #00bcff;\">None<\/span> <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">Option<\/span>(n)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">g<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span><span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Option<\/span>[<span style=\"color: #00bcff;\">Boolean<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">if<\/span> n%<span style=\"color: #00bcff;\">2<\/span>==<span style=\"color: #00bcff;\">1<\/span> then <span style=\"color: #00bcff;\">Option<\/span>(<span style=\"color: #00bcff;\">true<\/span>) <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">Option<\/span>(<span style=\"color: #00bcff;\">false<\/span>)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">h<\/span>(b<span style=\"color: #b6a0ff;\">:<\/span><span style=\"color: #6ae4b9;\">Boolean<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Option<\/span>[<span style=\"color: #00bcff;\">String<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">if<\/span> b then <span style=\"color: #00bcff;\">Some<\/span>(<span style=\"color: #79a8ff;\">\"Winner!\"<\/span>) <span style=\"color: #b6a0ff;\">else<\/span> <span style=\"color: #00bcff;\">None<\/span>\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">fcomposed<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Monad1<\/span>[<span style=\"color: #00bcff;\">Option<\/span>].compose(f,g)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">fghComposed<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Monad1<\/span>[<span style=\"color: #00bcff;\">Option<\/span>].compose(fcomposed, h)\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">i<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Float<\/span>) <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">0.0<\/span>\n\nprintln(fghComposed(<span style=\"color: #00bcff;\">1<\/span>))\nprintln(fghComposed(<span style=\"color: #00bcff;\">2<\/span>))\nprintln(fghComposed(<span style=\"color: #00bcff;\">3<\/span>))\nprintln(fghComposed(<span style=\"color: #00bcff;\">4<\/span>))\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Output:<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Some(Winner!)<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">None<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Some(Winner!)<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">None<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgd24b5d9\" class=\"outline-2\">\n<h2 id=\"orgd24b5d9\">The Monad laws<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgd24b5d9\">\n<p>\nAt this point we've shown that one implementation of a Monad involves\nthe unit and compose functions. We can now see a demonstration of the\nmonad laws in this form.\n<\/p>\n\n<p>\nLeft and right indentity laws are shown by composing a function with\nunit. This is equivalent to what we did with Scala functions.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">left and right identity<\/span>\nm1.compose(f, m1.unit)(<span style=\"color: #00bcff;\">1<\/span>) == f(<span style=\"color: #00bcff;\">1<\/span>)\nf(<span style=\"color: #00bcff;\">1<\/span>) == m1.compose(f, m1.unit)(<span style=\"color: #00bcff;\">1<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nWe can also demonstrate the associtive law in action, whereby\ncomposing f,g and h works both ways.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">m1.compose(m1.compose(f,g), h)(<span style=\"color: #00bcff;\">1<\/span>) == m1.compose(f, m1.compose(g,h))(<span style=\"color: #00bcff;\">1<\/span>)\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org10cc5ed\" class=\"outline-2\">\n<h2 id=\"org10cc5ed\">What about flatMap?<\/h2>\n<div class=\"outline-text-2\" id=\"text-org10cc5ed\">\n<p>\nSo far so good, we conjured up a monad from just category theory and a\nsimple twist on the category of types and functions. You may be\nwondering how we get from this new definition of Monad to the one we\nsee in Cats and Scalaz, and why even in the Scala standard library we\nhave flatMap but not compose for Kliesli arrows.\n<\/p>\n\n<p>\nWell fortunately flatMap can be written in terms of compose, so we can\nbe assured that the more convenient and familiar representation of\nMonads is exactly equivalent!\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">flatMap<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>](fa<span style=\"color: #b6a0ff;\">:<\/span><span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>])(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">B<\/span>])(using m<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monad1<\/span>[<span style=\"color: #00bcff;\">F<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n  <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">F[A] =&gt; F[A]<\/span>\n  <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">A =&gt; F[B]<\/span>\n  m.compose((a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>]) <span style=\"color: #b6a0ff;\">=&gt;<\/span> identity(a), a <span style=\"color: #b6a0ff;\">=&gt;<\/span> f(a))(fa)\n}\n<\/pre>\n<\/div>\n\n<p>\nI found this implementation a bit tricky to understand at first but if\nyou look at it and reference the Option instance above it should make\nsense after a little thought. The \"trick\" is that we are given an\n<code>F[A]<\/code> and so we pass that as the first argument to compose using the\nidentity function to get it back unchanged. (Mapping an F[A] to itself\nis actually the map function of Functor!)\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org63d0031\" class=\"outline-2\">\n<h2 id=\"org63d0031\">compose from flatMap<\/h2>\n<div class=\"outline-text-2\" id=\"text-org63d0031\">\n<p>\nShould your starting point be the more traditional Monad with pure and\nflatMap, you can in fact derive the compose function as follows.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">import<\/span> org.justinhj.typeclasses.monad.{given,<span style=\"color: #b6a0ff;\">_<\/span>}\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">compose<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>],<span style=\"color: #00bcff;\">A<\/span>,<span style=\"color: #00bcff;\">B<\/span>,<span style=\"color: #00bcff;\">C<\/span>](lf<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">B<\/span>], rf<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">B<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">C<\/span>])(using m<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Monad<\/span>[<span style=\"color: #00bcff;\">F<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #00bcff;\">C<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> \n  a <span style=\"color: #b6a0ff;\">=&gt;<\/span> lf(a).flatMap(rf) \n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org67d3bb6\" class=\"outline-2\">\n<h2 id=\"org67d3bb6\">Final remarks<\/h2>\n<div class=\"outline-text-2\" id=\"text-org67d3bb6\">\n<p>\nOne 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.\n<\/p>\n\n<p>\nMy favourite reference for exploring Monads in Scala is the so called\nred book which devotes chapter 11 to the subject.<sup><a id=\"fnr.4\" class=\"footref\" href=\"#fn.4\">4<\/a><\/sup> The nice thing about\nthat particular book is it encourages the sort of exploration and\ndiscovery of these concepts that makes them so fun to work with!\n<\/p>\n\n<p>\nThere is some duplication in the names when we use category theory in Scala that can cause confusion. Here's a little guide.\n<\/p>\n\n<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">\n\n\n<colgroup>\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n\n<col  class=\"org-left\" \/>\n<\/colgroup>\n<thead>\n<tr>\n<th scope=\"col\" class=\"org-left\">Purpose<\/th>\n<th scope=\"col\" class=\"org-left\">Functions<\/th>\n<th scope=\"col\" class=\"org-left\">Kleislis<\/th>\n<th scope=\"col\" class=\"org-left\">&#xa0;<\/th>\n<th scope=\"col\" class=\"org-left\">&#xa0;<\/th>\n<th scope=\"col\" class=\"org-left\">&#xa0;<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td class=\"org-left\">Identity<\/td>\n<td class=\"org-left\">identity<\/td>\n<td class=\"org-left\">unit<\/td>\n<td class=\"org-left\">pure<\/td>\n<td class=\"org-left\">return<\/td>\n<td class=\"org-left\">point<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">Sequence two effects<\/td>\n<td class=\"org-left\">n\/a<\/td>\n<td class=\"org-left\">flatMap<\/td>\n<td class=\"org-left\">bind<\/td>\n<td class=\"org-left\">&#xa0;<\/td>\n<td class=\"org-left\">&#xa0;<\/td>\n<\/tr>\n\n<tr>\n<td class=\"org-left\">Flatten a nested effect<\/td>\n<td class=\"org-left\">n\/a<\/td>\n<td class=\"org-left\">flatten<\/td>\n<td class=\"org-left\">join<\/td>\n<td class=\"org-left\">&#xa0;<\/td>\n<td class=\"org-left\">&#xa0;<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n<p>\nFinally it was really my goal here to show that there is not much to\ncategories and therefore not much to monads. The terminology is\nunfamiliar but I think the concepts are quite straightforward. I would\nlove to know if this blog and\/or video failed to make sense, so feel\nfree to reach out to be on the youtube comments or via the contact\ndetails above and I will take on board your suggestions.\n<\/p>\n<\/div>\n<\/div>\n<div id=\"footnotes\">\n<h2 class=\"footnotes\">Footnotes: <\/h2>\n<div id=\"text-footnotes\">\n\n<div class=\"footdef\"><sup><a id=\"fn.1\" class=\"footnum\" href=\"#fnr.1\">1<\/a><\/sup> <div class=\"footpara\"><p class=\"footpara\">\nUses of Category Theory <a href=\"https:\/\/math.stackexchange.com\/a\/1210742\/2914\">https:\/\/math.stackexchange.com\/a\/1210742\/2914<\/a>\n<\/p><\/div><\/div>\n\n<div class=\"footdef\"><sup><a id=\"fn.2\" class=\"footnum\" href=\"#fnr.2\">2<\/a><\/sup> <div class=\"footpara\"><p class=\"footpara\">\nCategory Theory for Programmers <a href=\"https:\/\/github.com\/hmemcpy\/milewski-ctfp-pdf\">https:\/\/github.com\/hmemcpy\/milewski-ctfp-pdf<\/a>\n<\/p><\/div><\/div>\n\n<div class=\"footdef\"><sup><a id=\"fn.3\" class=\"footnum\" href=\"#fnr.3\">3<\/a><\/sup> <div class=\"footpara\"><p class=\"footpara\">\nJames Iry and the famous monad quote <a href=\"https:\/\/stackoverflow.com\/questions\/3870088\/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem#3870310\">https:\/\/stackoverflow.com\/questions\/3870088\/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem#3870310<\/a>\n<\/p><\/div><\/div>\n\n<div class=\"footdef\"><sup><a id=\"fn.4\" class=\"footnum\" href=\"#fnr.4\">4<\/a><\/sup> <div class=\"footpara\"><p class=\"footpara\">\nFunctional Programming in Scala <a href=\"https:\/\/www.manning.com\/books\/functional-programming-in-scala\">https:\/\/www.manning.com\/books\/functional-programming-in-scala<\/a>\n<\/p><\/div><\/div>\n\n\n<\/div>\n<\/div>\n","pubDate":"Tue, 02 Feb 2021 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2021\/02\/02\/monads-in-scala-3-for-the-genius.html","guid":"http:\/\/justinhj.github.io\/2021\/02\/02\/monads-in-scala-3-for-the-genius.html","category":["scala","scala-3","dotty","monads","category-theory"]},{"title":"Functional Error Handling with Applicative in Scala 3","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n<div id=\"outline-container-org56d8e82\" class=\"outline-2\">\n<h2 id=\"org56d8e82\">Introduction<\/h2>\n<div class=\"outline-text-2\" id=\"text-org56d8e82\">\n<p>\nThis is a companion blog my sixth Functional Justin YouTube video\nwhich you can find here: <a href=\"https:\/\/youtu.be\/3GPXEzO14ZE\">https:\/\/youtu.be\/3GPXEzO14ZE<\/a>\n<\/p>\n\n<p>\nIn the video I talked about the Functor Laws and continued working on\nthe example program that evaluates arithmetic expressions. I use\nMonad, then Applicative, to show how we can make a Numeric instance\nfor Either, so we can handle errors in a nice functional way.\n<\/p>\n\n<p>\nSince the episode I spent a bit of time cleaning up the code and\nputting what we already saw (Numeric and Functor) into their own\npackages. I also went ahead and implemented Applicative and Monad\nwhich will be used in the the video and below.\n<\/p>\n\n<p>\nYou can find the typeclasses here:\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\/tree\/video6\/src\/main\/scala\/org\/justinhj\/typeclasses\">https:\/\/github.com\/justinhj\/evalexample\/tree\/video6\/src\/main\/scala\/org\/justinhj\/typeclasses<\/a>\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orga7f44da\" class=\"outline-2\">\n<h2 id=\"orga7f44da\">Functor Laws<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga7f44da\">\n<p>\nOur Functor type class really only exists to implement the map\nfunction, and we already have a map function in the Scala standard\nlibrary for such things as Options, Lists and Futures. You might\nwonder why we would go the trouble of making our own abstraction just\nto write a function that we already had.\n<\/p>\n\n<p>\nThe goal of abstractions like Functor is not just to provide useful\nfunctions like map, but to provide a principled layer that we can\nbuild further abstractions upon. For example we will see that\nApplicative can be built on top of Functor, Monad on top of\nApplicative, and this is only possible because Functor behaves in\naccordance to strict rules that it brought with it from Category\nTheory.\n<\/p>\n\n<p>\nYou can read more about Functors on the Haskell documentation pages:\n<\/p>\n\n<p>\n<a href=\"https:\/\/wiki.haskell.org\/Functor\">https:\/\/wiki.haskell.org\/Functor<\/a>\n<\/p>\n\n<p>\nAnother great resource is the famous \"red book\"&#x2026; \n<\/p>\n\n<p>\n<a href=\"https:\/\/www.manning.com\/books\/functional-programming-in-scala\">https:\/\/www.manning.com\/books\/functional-programming-in-scala<\/a>\n<\/p>\n<\/div>\n\n<div id=\"outline-container-orgdf1599b\" class=\"outline-3\">\n<h3 id=\"orgdf1599b\">Functors preserve identity morphisms<\/h3>\n<div class=\"outline-text-3\" id=\"text-orgdf1599b\">\n<p>\nWhat this law states is that if we map over some effect with the\nidentity function, then neither the effect nor any value inside it\nwill change.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Identity law for functors...<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">l1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">List<\/span>(<span style=\"color: #00bcff;\">1<\/span>, <span style=\"color: #00bcff;\">2<\/span>, <span style=\"color: #00bcff;\">3<\/span>)\nassert(l1 == l1.fmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> identity(a)))\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">10<\/span>)\nassert(e1 == e1.fmap(identity))\n<\/pre>\n<\/div>\n\n<p>\nIn the two examples we mapped an Either and a List using the identity\nfunction and nothing changed.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org49b33c1\" class=\"outline-3\">\n<h3 id=\"org49b33c1\">Functors preserve composition of morphisms<\/h3>\n<div class=\"outline-text-3\" id=\"text-org49b33c1\">\n<p>\nIf we have two functions, f and g, it doesn't matter if we map over\nsome effect with f first then map over it with g, or we map over it\none time with the composition of f and g. Using the either and list\nfrom above we can show this the case here.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">f<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a + <span style=\"color: #00bcff;\">1<\/span>\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">g<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a - <span style=\"color: #00bcff;\">1<\/span>\n\nassert(e1.fmap(f).fmap(g) == e1.fmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> g(f(a))))\nassert(l1.fmap(f).fmap(g) == l1.fmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> g(f(a))))\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org2564946\" class=\"outline-3\">\n<h3 id=\"org2564946\">Importing given instances<\/h3>\n<div class=\"outline-text-3\" id=\"text-org2564946\">\n<p>\nNote that in Scala pre version 3 if you use a wildcard import <code>_<\/code> then\nyou get all everything exposed in that package. That means you get all\nthe implicit instances too. It was a source of confusion for beginners\nand even experienced Scala programmers to know which file to import\nand sometimes to know where instances you are using are defined.\n<\/p>\n\n<p>\nTo help with that NO implicits are imported with a regular wildcard\nand instead you must import them with the new given syntax.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">import<\/span> org.justinhj.typeclasses.functor.{given, <span style=\"color: #b6a0ff;\">_<\/span>}\n<\/pre>\n<\/div>\n\n<p>\nIf you want you can also import only specific instances. This, in my\nopinon, will make things a lot simpler and more precise.\n<\/p>\n\n<p>\nOne caveat here is that the given wildcard must appear before the\nunderscore wildcard.\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org43d9bbb\" class=\"outline-2\">\n<h2 id=\"org43d9bbb\">Implementing Numeric for Either<\/h2>\n<\/div>\n\n<div id=\"outline-container-orga9f41c5\" class=\"outline-2\">\n<h2 id=\"orga9f41c5\">Functor isn't enough<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga9f41c5\">\n<p>\nThe following code implements an arithmetic expression evaluator using\nthe Numeric type class developed in a previous video and adds error\nhandling by using Either. Each step of our evaluator has this signature.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">WithEnv<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Env<\/span>[<span style=\"color: #00bcff;\">A<\/span>] ?=&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nWhich means it is a function takes an input environment (our symbol\ntable) as an implicit argument, and returns an Either where the error\n(or Left) type is EvalError. EvalError represents the different errors\nour code will handle. It is a sum type implemented as a Scala 3 enum\n(seen in a previous video).\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">EvalError<\/span> {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">InvalidSymboName<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">SymbolNotFound<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nIn previous blogs\/videos I showed how we can implement a Numeric\ninstance so we can do arithmetic on many different types, just so long\nas we create an instance of Numeric to handle them. Now we must\nimplement Numeric for the following type <code>Numeric[Either[EvalError, A]]<\/code>.\n<\/p>\n\n<p>\nThe instance signature is\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">given evalResultNumeric[<span style=\"color: #00bcff;\">A<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>]<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">with<\/span> {\n<\/pre>\n<\/div>\n\n<p>\nNow we must implement the methods of Numeric. Because our numeric\nvalues are inside the EvalResult (an Either) we can't just implement\nthe multiply directly. We need a way to get inside it. As we saw in\nthe previous blog\/video, Functor gives us a way to apply a pure\nfunction to an effect. Since mul is a pure function, maybe we can use\nit?\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mul<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>], b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n  a.fmap { <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">DOES NOT COMPILE, WRONG TYPE<\/span>\n    aa <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n    b.fmap {\n      bb <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n        aa * bb\n    }\n  }\n}\n<\/pre>\n<\/div>\n\n<p>\nNote I am using the name fmap and fflatMap to make it clear we are not\nusing the standard library implementations here. This is just for\nclarity but is not a good practise because, for example, you will lose\nthe ability to use for comprehensions.\n<\/p>\n\n<p>\nWhat went wrong here is that Functor's map operation has the signature\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">extension [<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>](x<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>])\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">ffmap<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">B<\/span>]\n<\/pre>\n<\/div>\n\n\n<p>\nwhich means it takes our <code>Either[EvalError, Numeric[A]]<\/code> and a pure\nfunction, which it will apply to the Numeric. Unfortunately we end up\nwith an extra layer of Either! Let's see why&#x2026;\n<\/p>\n\n<img class=\"img\" src=\"..\/..\/..\/images\/flatmapcallout1.png\" border=\"0\" style=\"padding: 30px;\" alt=\"flatmap types diagram reproduced in code\" width=\"600\"\/>\n<img class=\"img\" src=\"..\/..\/..\/images\/flatmapcallout2.png\" border=\"0\" style=\"padding: 30px;\" alt=\"flatmap types diagram reproduced in code\" width=\"600\"\/>\n<img class=\"img\" src=\"..\/..\/..\/images\/flatmapcallout3.png\" border=\"0\" style=\"padding: 30px;\" alt=\"flatmap types diagram reproduced in code\" width=\"600\"\/>\n<img class=\"img\" src=\"..\/..\/..\/images\/flatmapcallout4.png\" border=\"0\" style=\"padding: 30px;\" alt=\"flatmap types diagram reproduced in code\" width=\"600\"\/>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org25495d6\" class=\"outline-2\">\n<h2 id=\"org25495d6\">Monad to the rescue<\/h2>\n<div class=\"outline-text-2\" id=\"text-org25495d6\">\n<p>\nSo instead of Functor with its map function, we need Monad and its\nflatMap which let's us implement all the arithmetic functions in a\nstraightforward manner.\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\/blob\/video6\/src\/main\/scala\/org\/justinhj\/typeclasses\/monad\/Monad.scala\">https:\/\/github.com\/justinhj\/evalexample\/blob\/video6\/src\/main\/scala\/org\/justinhj\/typeclasses\/monad\/Monad.scala<\/a>\n<\/p>\n\n<p>\nI've implemented Monad in the file above and made it available to the\ncode. The implementation is simple and based on the example given in\nthe Dotty documentation. The main difference is I've also implemented\nApplicative, since we will use that in a moment, and Monad extends\nApplicative.\n<\/p>\n\n<p>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/type-classes.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/type-classes.html<\/a>\n<\/p>\n\n<p>\nNow each arithmetic operator can be implemented as follows, which\nachieves our goal of being principled and functional and let's us\nhandle errors at the type level.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mul<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>], b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n  a.fflatMap {\n    aa <span style=\"color: #b6a0ff;\">=&gt;<\/span> \n      b.map {\n        bb <span style=\"color: #b6a0ff;\">=&gt;<\/span>\n          aa * bb\n      }\n  }\n}\n<\/pre>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org957c8d2\" class=\"outline-3\">\n<h3 id=\"org957c8d2\">Map2 we love you<\/h3>\n<div class=\"outline-text-3\" id=\"text-org957c8d2\">\n<p>\nUnfortunately it's bit verbose. Monad is more powerful than we need in\nfact. We could use Applicative instead. I will talk more about Monad\nand Applicative in a later video, but in short you can think of Monads\nas being good for putting two effects together and flattening the\nresult, whilst Applicative is good for passing multiple effect values\nas parameters to some pure function.\n<\/p>\n\n<p>\nYou can see the Applicative implementation here. \n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\/blob\/video6\/src\/main\/scala\/org\/justinhj\/typeclasses\/applicative\/Applicative\">https:\/\/github.com\/justinhj\/evalexample\/blob\/video6\/src\/main\/scala\/org\/justinhj\/typeclasses\/applicative\/Applicative<\/a>\n<\/p>\n\n<p>\nNow, Functor has map, Monad has flatMap and Applicative has its own\nmapping function called ap. Whilst it's out of scope for right now,\nthe ap mapping function makes it possible to apply two or more effects\nas parameters to a pure function, which is exactly what we need\nhere. From ap you can derive methods that make this much simpler, map2\nfor example. Here we use map 2 to take any two input effects and apply\nthe multiply operator to them&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mul<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>], b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> \n  a.map2(b)((a,b) <span style=\"color: #b6a0ff;\">=&gt;<\/span> a * b)\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org6accaa4\" class=\"outline-2\">\n<h2 id=\"org6accaa4\">Division by Zero<\/h2>\n<div class=\"outline-text-2\" id=\"text-org6accaa4\">\n<p>\nWhat we have at this point is a nice implementation of Numeric that\nuses Either's for error handling, which in turn is built on\nApplicative. Let's see how easy it is to add new errors and\ncapabilities to the expression evaluator.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">EvalError<\/span> {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">InvalidSymboName<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">SymbolNotFound<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">DivisionByZero<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nFirst we add a new error type DivisionByZero. The next thing we need\nis for Numeric to have a concept of whether a number is zero or\nnot. Remember that we can implement Numeric for many different types\nand not all of them represent zero the same way. We can therefore add\nan isZero predicate to the type class.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">isZero<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Boolean<\/span> \n<\/pre>\n<\/div>\n\n<p>\nNext every instance of Numeric needs an implementation of it, so for\nexapmle in the Int instance we have the following.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">isZero<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) <span style=\"color: #b6a0ff;\">=<\/span> a == <span style=\"color: #00bcff;\">0<\/span>\n<\/pre>\n<\/div>\n\n<p>\nThe implementation for Numeric Either let's us write the isZero for\nany value in an either as long as that value has a numeric instance of\nits own.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">given evalResultNumeric[<span style=\"color: #00bcff;\">A<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>]<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">EvalError<\/span>, <span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">with<\/span> {\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">isZero<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Boolean<\/span> <span style=\"color: #b6a0ff;\">=<\/span> {\n    a <span style=\"color: #b6a0ff;\">match<\/span> {\n      <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Right<\/span>(<span style=\"color: #00d3d0;\">a<\/span>) <span style=\"color: #b6a0ff;\">if<\/span> summon[<span style=\"color: #00bcff;\">Numeric<\/span>[<span style=\"color: #00bcff;\">A<\/span>]].isZero(a) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">true<\/span>\n      <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">_<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">false<\/span>\n    }\n  }\n<\/pre>\n<\/div>\n\n<p>\nFinally we can implement the division operator for Numeric Either like this.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">div<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>], b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">EvalResult<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n  <span style=\"color: #b6a0ff;\">if<\/span> isZero(b) then\n    <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #00bcff;\">EvalError<\/span>.<span style=\"color: #00bcff;\">DivisionByZero<\/span>)\n  <span style=\"color: #b6a0ff;\">else<\/span> \n    a.map2(b)(<span style=\"color: #b6a0ff;\">_<\/span> \/ <span style=\"color: #b6a0ff;\">_<\/span>)\n}\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org2c69f4b\" class=\"outline-2\">\n<h2 id=\"org2c69f4b\">Wrap up<\/h2>\n<div class=\"outline-text-2\" id=\"text-org2c69f4b\">\n<p>\nThat's all for now, I hope you enjoyed this post and video. Please\ncontact me using the methods above with any questions, suggestions or\ncorrections!\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Thu, 21 Jan 2021 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2021\/01\/21\/functional-error-handling-with-applicative-in-scala-3.html","guid":"http:\/\/justinhj.github.io\/2021\/01\/21\/functional-error-handling-with-applicative-in-scala-3.html","category":["scala","scala-3","dotty","applicative","monads","applicative-functor"]},{"title":"Handling Errors functionally with Scala 3","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n<div id=\"outline-container-org98c4581\" class=\"outline-2\">\n<h2 id=\"org98c4581\">Introduction<\/h2>\n<div class=\"outline-text-2\" id=\"text-org98c4581\">\n<p>\nThis is a companion blog my fifth Functional Justin YouTube video\nwhich you can find here: <a href=\"https:\/\/youtu.be\/wNVQ75KM8-4\">https:\/\/youtu.be\/wNVQ75KM8-4<\/a>\n<\/p>\n\n<p>\nIf you're new to the series I'm exploring Scala 3 and functional\nprogramming using a simple expression evaluator, and adding features\nto it every week. Most of the videos are coffee break sized (10-15\nminutes) but this one took a bit longer as I needed more time to\nexplain the concepts. Next time will probably be back down to the more\nbite-sized format.\n<\/p>\n\n<p>\nIn video 1, <a href=\"https:\/\/youtu.be\/J01u_Dmrx5U\">https:\/\/youtu.be\/J01u_Dmrx5U<\/a>, I showed how you can use\nScala 3 features like Context Functions to pass context around. The\neval function below is an expression evaluator that takes expressions\nof type <code>Exp<\/code>, returns a result of type <code>Int<\/code> and has an implicit\nenvironment <code>Env<\/code> which is a symbol table of values.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Env<\/span> ?=&gt; <span style=\"color: #00bcff;\">Int<\/span>\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">eval<\/span>(exp<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  exp <span style=\"color: #b6a0ff;\">match<\/span>\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">id<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleVar(id)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> value\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleAdd(l,r)\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>(s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  summon[<span style=\"color: #00bcff;\">Env<\/span>].get(s).get\n<\/pre>\n<\/div>\n\n<p>\nThis is a nice example of context functions, but not so good an\nexample of a pure functional program, let's see why.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org1650438\" class=\"outline-2\">\n<h2 id=\"org1650438\">Purity<\/h2>\n<div class=\"outline-text-2\" id=\"text-org1650438\">\n<p>\nWhat is a pure function? In short it has three properties&#x2026; it is a\ntotal function, it is deterministic and it has no side effects.\n<\/p>\n\n<p>\nA <code>total function<\/code> has an answer (of a fixed type) for everything. Our\nexpression evaluator is a total function because every expression you\nput in can be evaluated and returns a value. Now let's say we had a\ndivide function, and you can pass in a divisor that is zero and the\nanswer is infinity. That is not representable by Int so the function\nis not total. We can only throw an error at this point.\n<\/p>\n\n<p>\nBy <code>deterministic<\/code>, we mean that the evaluator gives the same answer for\nevery input expression, which may seem self-evident, but imagine if we\nhad a random number command. When used it would return different\nanswers every time and the program would not be deterministic.\n<\/p>\n\n<p>\nFinally, by <code>no side effects<\/code>, we mean the program does nothing\nimpure. It is not going to print to the screen, send an email, or\nthrow errors.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgb716616\" class=\"outline-2\">\n<h2 id=\"orgb716616\">Is the expression evaluator code pure?<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb716616\">\n<p>\nIf your nose wrinkled when you saw this code above\n<code>summon[Env].get(s).get<\/code> then you're probably an experienced Scala\nprogrammer who knows that you should not call get on an option.\n<\/p>\n\n<p>\nWhat's happening there is a symbol table look up. First I 'summon' the\nsymbol table (see video 1 to understand context functions and where\nthe symbol table is coming from), then I look up the symbol using\n<code>get<\/code>. This returns an <code>Option<\/code> because the symbol may be missing!\n<\/p>\n\n<p>\nI hopefully pointed out at the time that you shouldn't call <code>get<\/code> on\nan Option in serious code because it will throw an error. That means\nthat as a program that can throw errors, our program is not pure.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org21a7f0e\" class=\"outline-2\">\n<h2 id=\"org21a7f0e\">Handling errors with Either<\/h2>\n<div class=\"outline-text-2\" id=\"text-org21a7f0e\">\n<p>\nSince the 90s the Haskell folk have been dealing with impurity by\nwrapping it up in data types that describe the effects, and\nmanipulating them with type classes. If that sounds hopelessly\nabstract, then fear not, in practise it's quite simple and we will fix\nour problems with a few lines of code.\n<\/p>\n\n<p>\nFirstly let's look at what we mean by a data type&#x2026; it is usually a\nhigher kinded type that \"contains\" things of another type that you can\ndefine at compile time.\n<\/p>\n\n<p>\nScala's Either is a great example of a data type. It encodes the\nconcept of errors. Our pure code does not deal with errors but we can\nstill encode errors by wrapping them as follows.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">10<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e2<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #79a8ff;\">\"Oops\"<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nBy encoding our values like this we can represent a computation that\nhas succeeded as a <code>Right<\/code> value, and a computation that has failed\nwith some error as a <code>Left<\/code> value.\n<\/p>\n\n<p>\nWhat this means is we can no longer apply pure functions these values\ndirectly. That is sort of the point. What we wanted to do was isolate\npure functions from having to deal with errors at all. So how do we\noperate on Eithers? Well you are probably familiar with the <code>map<\/code>\nfunction, and that can be used to apply a pure function to an either!\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e3<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e1.map(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>)\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Right(11)<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e4<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e2.map(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>)\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Left(\"Oops\")<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org203832a\" class=\"outline-2\">\n<h2 id=\"org203832a\">Categorically Speaking<\/h2>\n<div class=\"outline-text-2\" id=\"text-org203832a\">\n<p>\nYou may not really think of it as Category Theory, but whenever you\nmap an Either you are using Functors!\n<\/p>\n\n<p>\nThe Haskell documentation is a nice place to learn about Functors. If\nyou think of a normal pure function as a mapping of values from A to\nB, a Functor can map values that have been embellished, or wrapped in\nsome special data type.\n<\/p>\n\n<p>\n<a href=\"https:\/\/wiki.haskell.org\/Functor\">https:\/\/wiki.haskell.org\/Functor<\/a>\n<\/p>\n\n<p>\nHelpfully, the kind folks behind Scala 3 have added how to implement\ntype classes to their documentation. We can use that a starting point\nto build our own Functor and then make an instance that works with\nEithers.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">trait<\/span> <span style=\"color: #6ae4b9;\">Functor<\/span>[<span style=\"color: #00bcff;\">F<\/span>[<span style=\"color: #b6a0ff;\">_<\/span>]]<span style=\"color: #b6a0ff;\">:<\/span>\n  extension [<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>](x<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">A<\/span>])\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">ffmap<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">F<\/span>[<span style=\"color: #00bcff;\">B<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nThis is all we need to define a Functor type class that can extend\nsupported types with a map function. Note that I've added an f to\ndifferentiate the function from the built in map. Then I added another\nf by mistake, don't tell anyone, they might not notice!\n<\/p>\n\n<p>\nBefore we can use this against an Either we need to implement an\ninstance of the typeclass. Remember that Functor needs a type of kind\n<code>F[_]<\/code>. It has one \"type hole\". Either has two, which is not going to\nwork, so let's start by specialising to Either with only a fixed error\ntype of String.\n<\/p>\n\n<p>\nFirst we make a type alias that reduces the Either to one unknown\ntype, the computation result type <code>A<\/code>.\n<\/p>\n\n<p>\nNext we provide an implementation of ffmap that does the work of\nmapping our pure function over an Either.\n<\/p>\n\n<p>\nNote that this is roughly the same as the pure function. Instead of <code>A\n=&gt; B<\/code> we are mapping <code>F[A] =&gt; F[B]<\/code> where F is the Either.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">StringEither<\/span>[<span style=\"color: #00bcff;\">A<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">A<\/span>]\n\ngiven <span style=\"color: #00bcff;\">Functor<\/span>[<span style=\"color: #00bcff;\">StringEither<\/span>] <span style=\"color: #b6a0ff;\">with<\/span>\n  extension [<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>](x<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">StringEither<\/span>[<span style=\"color: #00bcff;\">A<\/span>])\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">ffmap<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">StringEither<\/span>[<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n      x <span style=\"color: #b6a0ff;\">match<\/span> {\n        <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Right<\/span>(<span style=\"color: #00d3d0;\">a<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Right<\/span>(f(a))\n        <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Left<\/span>(<span style=\"color: #00d3d0;\">err<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Left<\/span>(err)\n      }\n    }\n<\/pre>\n<\/div>\n\n<p>\nLet's try it out.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">10<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e2<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #79a8ff;\">\"Oops\"<\/span>)\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e3<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e1.ffmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>) <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Right(11)<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e4<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e2.ffmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>) <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Left(\"Oops\")<\/span>\n<\/pre>\n<\/div>\n\n<p>\nWe can now apply pure functions to Eithers with String error\ntypes. Where we want to get to is to be able to apply pure functions\nto <code>Either[Error,Numeric[A]]<\/code> so we're not quite there yet.\n<\/p>\n\n<p>\nThe first problem is that we can't handle the Error type that I want\nto use in my expression evaluator, we can only handle String. Well we\ncan just make another instance of Functor for <code>Either[Error,A]<\/code>?\n<\/p>\n\n<p>\nWell, yes we could, but how about we make a generic instance of\nFunctor for <code>all<\/code> Eithers?\n<\/p>\n\n<p>\nTo do that we need to use type lambdas. These were available in Scala\n2 but are greatly simplified in Scala 3.\n<\/p>\n\n<p>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/new-types\/type-lambdas.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/new-types\/type-lambdas.html<\/a>\n<\/p>\n\n<p>\nHere's the new instance for Functor with some notable changes.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span class=\"linenr\">1: <\/span>given eitherFunctor[<span style=\"color: #00bcff;\">E<\/span>]<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Functor<\/span>[[<span style=\"color: #00bcff;\">A<\/span>] =&gt;&gt; <span style=\"color: #00bcff;\">Either<\/span>[<span style=\"color: #00bcff;\">E<\/span>, <span style=\"color: #00bcff;\">A<\/span>]] <span style=\"color: #b6a0ff;\">with<\/span>\n<span class=\"linenr\">2: <\/span>  extension [<span style=\"color: #00bcff;\">A<\/span>, <span style=\"color: #00bcff;\">B<\/span>](x<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">E<\/span>,<span style=\"color: #00bcff;\">A<\/span>])\n<span class=\"linenr\">3: <\/span>      <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">ffmap<\/span>(f<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">A<\/span> <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">B<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">E<\/span>,<span style=\"color: #00bcff;\">B<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> {\n<span class=\"linenr\">4: <\/span>        x <span style=\"color: #b6a0ff;\">match<\/span> {\n<span class=\"linenr\">5: <\/span>          <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Right<\/span>(<span style=\"color: #00d3d0;\">a<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Right<\/span>(f(a))\n<span class=\"linenr\">6: <\/span>          <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Left<\/span>(<span style=\"color: #00d3d0;\">err<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> <span style=\"color: #00bcff;\">Left<\/span>(err)\n<span class=\"linenr\">7: <\/span>        }\n<span class=\"linenr\">8: <\/span>      }\n<\/pre>\n<\/div>\n\n<p>\nLine 1 is where the action is. First note that we named the given\ninstance <code>eitherFunctor<\/code>. Our previous instance had no name. You <code>can<\/code>\nleave the name out, but it's not recommended, especially for\nlibraries, since it makes the code easier to work with. See also that\nthe instance itself takes parameter <code>E<\/code> which will represent our error\ntype.\n<\/p>\n\n<p>\nNext the instance of Functor is for the type <code>[A] =&gt;&gt; Either[E, A]<\/code>\nwhich is our type lambda. It means please give me a type that has a\nsingle parameter A but that will be substituted into the <code>Either[E,A]<\/code>\nin a way that is similar to how parameters are substituted into a\nlambda function.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e1<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Right<\/span>(<span style=\"color: #00bcff;\">10<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e2<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Either<\/span>[<span style=\"color: #00bcff;\">Int<\/span>, <span style=\"color: #00bcff;\">Int<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Left<\/span>(<span style=\"color: #00bcff;\">1<\/span>)\n\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e3<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e1.ffmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>) <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Right(11)<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">e4<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e2.ffmap(a <span style=\"color: #b6a0ff;\">=&gt;<\/span> a + <span style=\"color: #00bcff;\">1<\/span>) <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Left(1)<\/span>\n<\/pre>\n<\/div>\n\n<p>\nNow we can map over any type of Either! As you can see in the first\ncase the pure function mapped over the A. In the second case the pure\nfunction was not executed and the error value is simply passed along.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org837bdc6\" class=\"outline-2\">\n<h2 id=\"org837bdc6\">Functor Laws<\/h2>\n<div class=\"outline-text-2\" id=\"text-org837bdc6\">\n<p>\nNext time we'll look at the Functor laws and show that our code obeys them.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgb73242c\" class=\"outline-2\">\n<h2 id=\"orgb73242c\">Wrap up<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb73242c\">\n<p>\nI hope you enjoyed this blog and\/or video. Please share, like or\nsubscribe and help me spread this content to those that may find it\nuseful.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org00245d4\" class=\"outline-2\">\n<h2 id=\"org00245d4\">For further info<\/h2>\n<div class=\"outline-text-2\" id=\"text-org00245d4\">\n<p>\nSource code\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\">https:\/\/github.com\/justinhj\/evalexample<\/a>\n<\/p>\n\n<p>\nRead more\n<\/p>\n\n<p>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/new-types\/type-lambdas.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/new-types\/type-lambdas.html<\/a>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/extension-methods.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/extension-methods.html<\/a>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/type-classes.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/type-classes.html<\/a>\n<\/p>\n\n<p>\n&copy; 2020 Justin Heyes-Jones. All Rights Reserved.\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Wed, 06 Jan 2021 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2021\/01\/06\/handling-errors-functionaly-with-scala-3.html","guid":"http:\/\/justinhj.github.io\/2021\/01\/06\/handling-errors-functionaly-with-scala-3.html","category":["scala","scala-3","dotty"]},{"title":"Type classes with Scala 2","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n<p>\n<img src=\"\/..\/images\/crissy-jarvis-cHhbULJbPwM-unsplash-small.jpg\" alt=\"A colourful abascus\" title=\"Abacus\" \/>\n<\/p>\n<span>Photo by <a href=\"https:\/\/unsplash.com\/@crissyjarvis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Crissy Jarvis<\/a> on <a href=\"https:\/\/unsplash.com\/s\/photos\/abacus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Unsplash<\/a><\/span>\n\n<div id=\"outline-container-orge38ea18\" class=\"outline-2\">\n<h2 id=\"orge38ea18\">Make your own Numeric type class<\/h2>\n<div class=\"outline-text-2\" id=\"text-orge38ea18\">\n<p>\nThis is the companion blog for a Functional Justin video which you can\nfind here <a href=\"https:\/\/youtu.be\/pJFfXhZlR5o\">https:\/\/youtu.be\/pJFfXhZlR5o<\/a>. This is a series of\ncoffee-break sized videos that each explore a topic in the world of\nScala Functional Programming.\n<\/p>\n\n<p>\nIn this video I talk about Type classes and here is the blog version for those that would rather read.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orge66e206\" class=\"outline-2\">\n<h2 id=\"orge66e206\">What are type classes<\/h2>\n<div class=\"outline-text-2\" id=\"text-orge66e206\">\n<p>\nHere are some good references for reading about type classes in Scala (they can of course be implemented in other functional programming languages).\n<\/p>\n\n<p>\nSam Halliday has a great introduction to data types and type classes in his book Functional Programming for Mortals.\n<a href=\"https:\/\/leanpub.com\/fpmortals\/read#leanpub-auto-data-and-functionality\">https:\/\/leanpub.com\/fpmortals\/read#leanpub-auto-data-and-functionality<\/a>\n<\/p>\n\n<p>\nThis 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.\n<a href=\"https:\/\/typelevel.org\/cats\/typeclasses.html\">https:\/\/typelevel.org\/cats\/typeclasses.html<\/a>\n<a href=\"https:\/\/typelevel.org\/cats\/datatypes\">https:\/\/typelevel.org\/cats\/datatypes<\/a>\n<\/p>\n\n<p>\nMy former colleague and functional programming advocate Francis Toth also has a nice blog on this topic.\n<a href=\"https:\/\/contramap.dev\/2020\/04\/09\/typeclasses.html\">https:\/\/contramap.dev\/2020\/04\/09\/typeclasses.html<\/a>\n<\/p>\n\n<p>\nIn my own words, type classes are not explicitly part of the Scala\nlanguage, but are rather a pattern of implementation that enable you\nto define behaviours which can then be implemented for data\ntypes. Data types are values like strings and numbers, collections\nlike lists and sets and \"higher kinded types\" like IO, ZIO and so on.\n<\/p>\n\n<p>\nType classes do not have to be implemented a certain way, but in Cats,\nScalaz and other libraries you will find them implemented just as they\nare here, but additional layers of complexity to manage things like\nstack safety and take advantage of tools to generate boilerplate code.\n<\/p>\n\n<p>\nIn general type classes consist of:\n<\/p>\n\n<ul class=\"org-ul\">\n<li>A trait that has one, or sometimes more, type parameters.<\/li>\n<li>It contains one or more abstract methods. These define behaviours that must be implemented for each <code>instance<\/code>.<\/li>\n<li>Also you will find generalized methods that are built using the abstract ones.<\/li>\n<li>Typically a type class contains no data<\/li>\n<\/ul>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org6576dab\" class=\"outline-2\">\n<h2 id=\"org6576dab\">Numeric<\/h2>\n<div class=\"outline-text-2\" id=\"text-org6576dab\">\n<p>\nIn the video I implemented the Numeric type class. What is Numeric? It\nis a type class you'll find in the Scala standard library and is used\nto build a generic representation of numbers.\n<\/p>\n\n<p>\n<a href=\"https:\/\/www.scala-lang.org\/api\/current\/scala\/math\/Numeric.html\">https:\/\/www.scala-lang.org\/api\/current\/scala\/math\/Numeric.html<\/a>\n<\/p>\n\n<p>\nWhat I develop here is just enough that we can use it for the\nexpression evaluator in the first video (which only requires add and\nmultiply operations).\n<\/p>\n\n<p>\nYou can find the complete code here\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\/blob\/master\/src\/main\/scala\/Scala2Numeric.scala\">https:\/\/github.com\/justinhj\/evalexample\/blob\/master\/src\/main\/scala\/Scala2Numeric.scala<\/a>\n<\/p>\n\n<p>\nLet's look at the pieces one by one&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">trait<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">T<\/span>] {\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">Add<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>, b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">Mul<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>, b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>\n\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">square<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> mul(a, a)\n}\n<\/pre>\n<\/div>\n\n<p>\nHere we define the trait which decribes the core of our type class;\nwhat it can do, and what you need to implement if you want your data\ntype to be an instance of this typeclass.\n<\/p>\n\n<p>\nAdd and Mul are abstract, whilst the square function is derived or\ngeneralized and does not need to be implemented when making new\nsupported instances.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org059d026\" class=\"outline-2\">\n<h2 id=\"org059d026\">Instances<\/h2>\n<div class=\"outline-text-2\" id=\"text-org059d026\">\n<p>\nOnce you have the interface for your type class you can define instances for various data types. Here we define the instance for <code>Long<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">numericLong<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Long<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">Long<\/span>] {\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Long<\/span>, b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Long<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Long<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a + b\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mul<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Long<\/span>, b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Long<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Long<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a * b\n}\n<\/pre>\n<\/div>\n\n<p>\nNote that this is implicit to make it easier to use our instances with\nother types, taking advantage of the fact that users can import the\ndefinititions and then use them in their code.\n<\/p>\n\n<p>\nHere's an example function that is written using the Numeric type\nclass as a parameter. This function displays what we call <code>ad-hoc\npolymorphism<\/code>, in that this function does not know all of the\ninstances that exist for the input type <code>T<\/code>, nor does it need to. All\nit knows is that to do its work it needs an instance of <code>Numeric[T]<\/code>\nso that it can access the <code>add<\/code> method.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">sumList<\/span>[<span style=\"color: #00bcff;\">T<\/span>](ts<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">List<\/span>[<span style=\"color: #00bcff;\">T<\/span>])(<span style=\"color: #f78fe7;\">implicit<\/span> numeric<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">T<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> {\n  ts.reduce((a, b) <span style=\"color: #b6a0ff;\">=&gt;<\/span> numeric.<span style=\"color: #00bcff;\">Add<\/span>(a,b))\n}\n<\/pre>\n<\/div>\n\n<p>\nNow we can sum a list of any <code>T<\/code> where T has a Numeric instance. Here we use the Int instance (not shown).\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">l1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">List<\/span>(<span style=\"color: #00bcff;\">1<\/span>, <span style=\"color: #00bcff;\">2<\/span>, <span style=\"color: #00bcff;\">3<\/span>, <span style=\"color: #00bcff;\">4<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">sum<\/span> <span style=\"color: #b6a0ff;\">=<\/span> sumList(l1)\n\nprintln(s<span style=\"color: #79a8ff;\">\"sum of int list is <\/span><span style=\"color: #00d3d0;\">$sum<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">sum of int list is 10<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org645a66c\" class=\"outline-2\">\n<h2 id=\"org645a66c\">Improving the ergonomics<\/h2>\n<div class=\"outline-text-2\" id=\"text-org645a66c\">\n<p>\nSo that's all you need to build type classes but we can take a couple\nof steps to make things more ergonomic. For one we can ditch the\nimplicit parameter and instead make use of\n[[<a href=\"https:\/\/docs.scala-lang.org\/tutorials\/FAQ\/context-bounds.html\">https:\/\/docs.scala-lang.org\/tutorials\/FAQ\/context-bounds.html<\/a>]context\nbounds]]. This makes things clearer for the caller of the function.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">sumList<\/span>[<span style=\"color: #00bcff;\">T<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>](ts<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">List<\/span>[<span style=\"color: #00bcff;\">T<\/span>])<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> {\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">numeric<\/span> <span style=\"color: #b6a0ff;\">=<\/span> implicitly[<span style=\"color: #00bcff;\">Numeric<\/span>[<span style=\"color: #00bcff;\">T<\/span>]]\n  ts.reduce((a, b) <span style=\"color: #b6a0ff;\">=&gt;<\/span> numeric.add(a,b))\n}\n<\/pre>\n<\/div>\n\n<p>\nNote that we have to <code>summon<\/code> the implicit Numeric instance using\n<code>implicitly<\/code>. This is a function in the standard library which takes\nadvantage of the way context bounds work: the context bound <code>Numeric<\/code>\nspecifies that there is an implicit Numeric instance in scope, but\nthere is no named parameter as before. The implicitly function lets\nus access that implicit in a succinct way.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">implicitly<\/span>[<span style=\"color: #00bcff;\">T<\/span>](<span style=\"color: #f78fe7;\">implicit<\/span> e<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> e\n<\/pre>\n<\/div>\n\n<p>\nSo using context bounds helps a little with the use of type classes,\nthe next step is to use implicit conversions so that we take the\nfunctions in our type class and make them look like ordinary methods\non the data type.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">ops<\/span> {\n\n  <span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">NumericOps<\/span>[<span style=\"color: #00bcff;\">T<\/span>](a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)(<span style=\"color: #f78fe7;\">implicit<\/span> numeric<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">T<\/span>]) {\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> numeric.add(a, b)\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mul<\/span>(b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> numeric.mul(a, b)\n\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">+<\/span>(b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> add(b)\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">*<\/span>(b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">T<\/span> <span style=\"color: #b6a0ff;\">=<\/span> mul(b)\n  }\n\n}\n<\/pre>\n<\/div>\n\n<p>\nNow 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">s1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #79a8ff;\">\"abcd\"<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">s2<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #79a8ff;\">\"efgh\"<\/span>\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">product<\/span> <span style=\"color: #b6a0ff;\">=<\/span> s1 * s2\nprintln(s<span style=\"color: #79a8ff;\">\"product <\/span><span style=\"color: #00d3d0;\">$product<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">product aeafagahbebfbgbhcecfcgchdedfdgdh<\/span>\n<\/pre>\n<\/div>\n\n<p>\nSo you can see that by implementing a somewhat goofy instance of\nNumeric for string (given below) we now have the ability to use the\nmultiplication operator on it as if it was a regular number.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">stringNumeric<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">String<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">new<\/span> <span style=\"color: #6ae4b9;\">Numeric<\/span>[<span style=\"color: #00bcff;\">String<\/span>] {\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">add<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>, b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span> <span style=\"color: #b6a0ff;\">=<\/span> a + b\n\n    <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">mul<\/span>(a<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>, b<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #b6a0ff;\">for<\/span> (\n      as <span style=\"color: #b6a0ff;\">&lt;-<\/span> a;\n      bs <span style=\"color: #b6a0ff;\">&lt;-<\/span> b;\n      s <span style=\"color: #b6a0ff;\">&lt;-<\/span> as.toString ++ bs.toString) <span style=\"color: #b6a0ff;\">yield<\/span> s\n  }\n<\/pre>\n<\/div>\n\n<p>\nNote that while this implentation of string arithmetic is not very\nrigorous and just for fun, there's nothing to stop you from\nimplementing Numeric for data types that do have well defined\narithmetic operations such as Roman Numerals.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org40f4c54\" class=\"outline-2\">\n<h2 id=\"org40f4c54\">Coherence<\/h2>\n<div class=\"outline-text-2\" id=\"text-org40f4c54\">\n<p>\nType class coherence is an important concept I'll leave you with. This\nis a guideline in place to keep programs easy to reason about. It's a\ngood practice to keep common instances together with your type classes\nso that users can easily find them, and don't duplicate the work. It's\nalso important that you don't try to make multiple instances and let\nthe users select one depending on their needs. The reason for that is\nthe behaviour of your program can change profoundly when you do this,\nand that's terrible. It means you can't take advantage of <code>local\nreasoning<\/code>, one of the benefits of functional programming. You would\nneed to be very careful with imports to make sure you are using the\ninstance you think you are.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgc682686\" class=\"outline-2\">\n<h2 id=\"orgc682686\">Final words<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgc682686\">\n<p>\nIf you're coming from Java or similar OOP language you may recognise\nsome of this as the adapter pattern (except with Scala\nimplicits). Type class traits also have similarities to Go interfaces,\nalthough the type class pattern goes a bit beyond them in scope.\n<\/p>\n\n<p>\nI would be amiss not to mention Haskell here, which has type classes\nimplemented as a first-class language construct, and for some people\nthe over-use of type classes in Scala is somewhat of an\nanti-pattern. We will see in future videos that the pattern will be\ngreatly simplified in Scala 3 however.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgc07e8a4\" class=\"outline-2\">\n<h2 id=\"orgc07e8a4\">References<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgc07e8a4\">\n<p>\nTypelevel Cats functional programming library documentation\n<a href=\"https:\/\/typelevel.org\/cats\/\">https:\/\/typelevel.org\/cats\/<\/a>\n<\/p>\n\n<p>\nFunctional Programming for Mortals\n<a href=\"https:\/\/leanpub.com\/fpmortals\">https:\/\/leanpub.com\/fpmortals<\/a>\n<\/p>\n\n<p>\n&copy; 2020 Justin Heyes-Jones. All Rights Reserved.\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Sun, 06 Dec 2020 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2020\/12\/06\/type-classes-scala-2.html","guid":"http:\/\/justinhj.github.io\/2020\/12\/06\/type-classes-scala-2.html","category":["scala","functional-programming"]},{"title":"Scala 3 Context Functions","description":"<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/..\/..\/_orgcss\/site.css\" \/>\n<div id=\"outline-container-orgf6c3f62\" class=\"outline-2\">\n<h2 id=\"orgf6c3f62\">Some Scala 3 Things: Context functions, Enums and significant whitespace<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgf6c3f62\">\n<p>\n<code>Updated: for Scala 3.0.0-M3 `as` keyword was removed<\/code>\n<\/p>\n\n<p>\nThis is the companion blog for my first Functional Justin video which you can find here <a href=\"https:\/\/youtu.be\/J01u_Dmrx5U\">https:\/\/youtu.be\/J01u_Dmrx5U<\/a>. I spend around 15 minutes adding some Scala 3 (formerly Dotty) features to an Scala 2 program.\n<\/p>\n\n<p>\nThe program itself builds a simple Algebraic Data Type (ADT) to represent a simple arithmetic expressions. We can then build expressions in this <code>algebra<\/code> and evaluate it using an eval function using pattern matching&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">sealed<\/span> <span style=\"color: #b6a0ff;\">trait<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n<span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(value<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n<span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(left<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, right<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n<span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">Mul<\/span>(left<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, right<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n<span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #b6a0ff;\">class<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(identifier<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n<\/pre>\n<\/div>\n\n<p>\nNow given an expression like <code>Mul(Var(\"z\"), Add(Val(30), Mul(Var(\"x\"), Var(\"y\"))))<\/code> I'd like to be able to recursively traverse it and calculate a final Int value at the end.\n<\/p>\n\n<p>\n<code>Val<\/code> represents an Int value, whilst <code>Add<\/code> and <code>Mul<\/code> take care of addition and multiplication. You could go ahead and add more functions. <code>Var<\/code> 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Env<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>[<span style=\"color: #00bcff;\">String<\/span>, <span style=\"color: #00bcff;\">Int<\/span>]\n<\/pre>\n<\/div>\n\n<p>\nFor the eval function we just use a pattern match to dispatch to functions that handle each particular operation. These handler functions and eval are <code>mutally recursive<\/code>, and note that every function has to have the <code>Env<\/code> passed to it as an implicit parameter, yet only <code>Var<\/code> needs it. This will be important later.\n<\/p>\n\n<p>\nHere's the eval function and handlers.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">eval<\/span>(exp<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)(<span style=\"color: #f78fe7;\">implicit<\/span> env <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span> <span style=\"color: #b6a0ff;\">=<\/span> {\n  exp <span style=\"color: #b6a0ff;\">match<\/span> {\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">id<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleVar(id)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> value\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleAdd(l,r)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Mul<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleMul(l,r)\n  }\n}\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleAdd<\/span>(l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)(<span style=\"color: #f78fe7;\">implicit<\/span> env <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>) <span style=\"color: #b6a0ff;\">=<\/span> eval(l) + eval(r)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleMul<\/span>(l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)(<span style=\"color: #f78fe7;\">implicit<\/span> env <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>) <span style=\"color: #b6a0ff;\">=<\/span> eval(l) * eval(r)\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>(s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)(<span style=\"color: #f78fe7;\">implicit<\/span> env<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>) <span style=\"color: #b6a0ff;\">=<\/span> env.getOrElse(s, <span style=\"color: #00bcff;\">0<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nNote that we could have inlined these functions in eval, but it a larger example it's important to break things out to keep things managable.\n<\/p>\n\n<p>\nThat 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">exp1<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Mul<\/span>(<span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"z\"<\/span>), <span style=\"color: #00bcff;\">Add<\/span>(<span style=\"color: #00bcff;\">Val<\/span>(<span style=\"color: #00bcff;\">30<\/span>), <span style=\"color: #00bcff;\">Mul<\/span>(<span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span>), <span style=\"color: #00bcff;\">Var<\/span>(<span style=\"color: #79a8ff;\">\"y\"<\/span>))))\n\n<span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">env<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span> -&gt; <span style=\"color: #00bcff;\">17<\/span>, <span style=\"color: #79a8ff;\">\"y\"<\/span> -&gt; <span style=\"color: #00bcff;\">10<\/span>, <span style=\"color: #79a8ff;\">\"z\"<\/span> -&gt; <span style=\"color: #00bcff;\">2<\/span>)\n<span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">eval1<\/span> <span style=\"color: #b6a0ff;\">=<\/span> eval(exp1)\n\nprintln(s<span style=\"color: #79a8ff;\">\"Eval exp gives <\/span><span style=\"color: #00d3d0;\">$eval1<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nYou can compile and run the code to see this working. The code is here. <a href=\"https:\/\/github.com\/justinhj\/evalexample\/blob\/master\/src\/main\/scala\/Scala2Eval.scala\">https:\/\/github.com\/justinhj\/evalexample\/blob\/master\/src\/main\/scala\/Scala2Eval.scala<\/a>\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgb5b329b\" class=\"outline-2\">\n<h2 id=\"orgb5b329b\">Fun with Enum<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb5b329b\">\n<p>\nScala enums have been improved greatly. For one they are very simple to create and use just as in other languages.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">StatusCode<\/span><span style=\"color: #b6a0ff;\">:<\/span>\n   <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">OK<\/span>, <span style=\"color: #00bcff;\">TimedOut<\/span>, <span style=\"color: #00bcff;\">Error<\/span>\n<\/pre>\n<\/div>\n\n<p>\nHere we've defined three enums that have ordinal values 0 to 2. You can access the ordinal value with the <code>.ordinal<\/code> method, convert ordinal values to Enums using <code>.fromOrdinal<\/code> and convert Strings to enums (assuming they match) with <code>.valueOf<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">println(s<span style=\"color: #79a8ff;\">\"Ordinal value of StatusCode.Error is <\/span><span style=\"color: #00d3d0;\">${StatusCode.Error.ordinal}<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\nprintln(s<span style=\"color: #79a8ff;\">\"StatusCode from ordinal 1 is <\/span><span style=\"color: #00d3d0;\">${StatusCode.fromOrdinal(1)}<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\nprintln(s<span style=\"color: #79a8ff;\">\"StatusCode from string OK is <\/span><span style=\"color: #00d3d0;\">${StatusCode.valueOf(\"OK\")}<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Ordinal value of StatusCode.Error is 2<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">StatusCode from ordinal 1 is TimedOut<\/span>\n<span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">StatusCode from string OK is OK<\/span>\n<\/pre>\n<\/div>\n\n<p>\nYou 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">HttpStatusCode<\/span>(code<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">OK<\/span> <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">HttpStatusCode<\/span>(<span style=\"color: #00bcff;\">200<\/span>)\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">NotModified<\/span> <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">HttpStatusCode<\/span>(<span style=\"color: #00bcff;\">304<\/span>)\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #00bcff;\">Forbidden<\/span> <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">HttpStatusCode<\/span>(<span style=\"color: #00bcff;\">404<\/span>)\n\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">isSuccess<\/span> <span style=\"color: #b6a0ff;\">=<\/span> code &gt;= <span style=\"color: #00bcff;\">200<\/span> &amp;&amp; code &lt; <span style=\"color: #00bcff;\">300<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nScala 3 team also took the opportunity to make Enums <code>a more concise notation for ADTs and GADTs<\/code>. For our purposes that means we can simply the definition of <code>Exp<\/code> as follows.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">Exp<\/span> {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">left<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, <span style=\"color: #00d3d0;\">right<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">identifier<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>) <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>\n}\n<\/pre>\n<\/div>\n\n<p>\nIn fact you can further simplify to the following (you could also remove the braces).\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">enum <span style=\"color: #00bcff;\">Exp<\/span> {\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">left<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, <span style=\"color: #00d3d0;\">right<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)\n  <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">identifier<\/span><span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)\n}\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orgf9c19ca\" class=\"outline-2\">\n<h2 id=\"orgf9c19ca\">Explicit implicits<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgf9c19ca\">\n<p>\nA 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 <code>given<\/code> syntax instead of <code>implicit<\/code>.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #f78fe7;\">implicit<\/span> <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">env<\/span> <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span> -&gt; <span style=\"color: #00bcff;\">17<\/span>, <span style=\"color: #79a8ff;\">\"y\"<\/span> -&gt; <span style=\"color: #00bcff;\">10<\/span>, <span style=\"color: #79a8ff;\">\"z\"<\/span> -&gt; <span style=\"color: #00bcff;\">2<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nbecomes&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\">given envMap<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Map<\/span>(<span style=\"color: #79a8ff;\">\"x\"<\/span> -&gt; <span style=\"color: #00bcff;\">7<\/span>, <span style=\"color: #79a8ff;\">\"y\"<\/span> -&gt; <span style=\"color: #00bcff;\">6<\/span>, <span style=\"color: #79a8ff;\">\"z\"<\/span> -&gt; <span style=\"color: #00bcff;\">22<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nSimilarly, the method parameters now no longer use the implicit keyword and instead you prefix the parameter name with <code>using<\/code>.\n<\/p>\n\n<pre class=\"example\">\ndef eval(exp: Exp)(implicit env : Env): Int\n<\/pre>\n\n<p>\nbecomes&#x2026;\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">eval<\/span>(exp<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)(using env <span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Env<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>\n<\/pre>\n<\/div>\n\n<p>\nYou don'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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org08f0809\" class=\"outline-2\">\n<h2 id=\"org08f0809\">Context Functions<\/h2>\n<div class=\"outline-text-2\" id=\"text-org08f0809\">\n<p>\nLast 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 <code>Function1[A,B]<\/code>. 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't see it your code), with an input and an output type. The difference is that the input is understood to be provided implicitly.\n<\/p>\n\n<p>\nLet's make this more concrete. Assume you have a function that needs an <code>ExecutionContext<\/code>. We can make a Context Function type that will take an implicit execution context and return some paramaterized type T.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Executable<\/span>[<span style=\"color: #00bcff;\">T<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">ExecutionContext<\/span> ?=&gt; <span style=\"color: #00bcff;\">T<\/span>\n<\/pre>\n<\/div>\n\n<p>\nHow would that be used in a real program? Let'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'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.\n<\/p>\n\n<p>\nWith Scala 3 you can define the function to be of type <code>Executable[T]<\/code> and then we don'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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">import<\/span> scala.concurrent.{<span style=\"color: #00bcff;\">Future<\/span>, <span style=\"color: #00bcff;\">ExecutionContext<\/span>, <span style=\"color: #00bcff;\">Await<\/span>}\n<span style=\"color: #b6a0ff;\">import<\/span> scala.concurrent.duration.<span style=\"color: #b6a0ff;\">_<\/span>\n<span style=\"color: #b6a0ff;\">import<\/span> scala.language.postfixOps\n\n<span style=\"color: #b6a0ff;\">object<\/span> <span style=\"color: #00bcff;\">Executable<\/span> <span style=\"color: #b6a0ff;\">extends<\/span> <span style=\"color: #6ae4b9;\">App<\/span> {\n\n  <span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">Executable<\/span>[<span style=\"color: #00bcff;\">T<\/span>] <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">ExecutionContext<\/span> ?=&gt; <span style=\"color: #00bcff;\">T<\/span>\n\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">f1<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Executable<\/span>[<span style=\"color: #00bcff;\">Future<\/span>[<span style=\"color: #00bcff;\">Int<\/span>]] <span style=\"color: #b6a0ff;\">=<\/span> f2(n + <span style=\"color: #00bcff;\">1<\/span>)\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">f2<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Executable<\/span>[<span style=\"color: #00bcff;\">Future<\/span>[<span style=\"color: #00bcff;\">Int<\/span>]] <span style=\"color: #b6a0ff;\">=<\/span> f3(n + <span style=\"color: #00bcff;\">1<\/span>)\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">f3<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Executable<\/span>[<span style=\"color: #00bcff;\">Future<\/span>[<span style=\"color: #00bcff;\">Int<\/span>]] <span style=\"color: #b6a0ff;\">=<\/span> f4(n + <span style=\"color: #00bcff;\">1<\/span>)\n  <span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">f4<\/span>(n<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Int<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Executable<\/span>[<span style=\"color: #00bcff;\">Future<\/span>[<span style=\"color: #00bcff;\">Int<\/span>]] <span style=\"color: #b6a0ff;\">=<\/span> {\n    <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">ex<\/span> <span style=\"color: #b6a0ff;\">=<\/span> summon[<span style=\"color: #00bcff;\">ExecutionContext<\/span>]\n    <span style=\"color: #00bcff;\">Future<\/span> {\n      println(s<span style=\"color: #79a8ff;\">\"Hi from the future! n is <\/span><span style=\"color: #00d3d0;\">$n<\/span><span style=\"color: #79a8ff;\">\"<\/span>)\n      n\n    }\n  }\n\n  {\n    given ec<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">ExecutionContext<\/span> <span style=\"color: #b6a0ff;\">=<\/span> scala.concurrent.<span style=\"color: #00bcff;\">ExecutionContext<\/span>.global\n    <span style=\"color: #00bcff;\">Await<\/span>.result(f1(<span style=\"color: #00bcff;\">10<\/span>), <span style=\"color: #00bcff;\">1<\/span> second)\n    <span style=\"color: #a8a8a8;\">\/\/ <\/span><span style=\"color: #a8a8a8;\">Hi from the future! n is 13<\/span>\n  }\n\n}\n<\/pre>\n<\/div>\n\n<p>\nContext 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.\n<\/p>\n\n<div class=\"org-src-container\">\n<pre class=\"src src-scala\"><span style=\"color: #b6a0ff;\">type<\/span> <span style=\"color: #00bcff;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span> <span style=\"color: #00bcff;\">Env<\/span> ?=&gt; <span style=\"color: #00bcff;\">Int<\/span>\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">eval<\/span>(exp<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  exp <span style=\"color: #b6a0ff;\">match<\/span> {\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Var<\/span>(<span style=\"color: #00d3d0;\">id<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleVar(id)\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Val<\/span>(<span style=\"color: #00d3d0;\">value<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> value\n    <span style=\"color: #b6a0ff;\">case<\/span> <span style=\"color: #6ae4b9;\">Add<\/span>(<span style=\"color: #00d3d0;\">l<\/span>,<span style=\"color: #00d3d0;\">r<\/span>) <span style=\"color: #b6a0ff;\">=&gt;<\/span> handleAdd(l,r)\n  }\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleAdd<\/span>(l<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>, r<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">Exp<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span> eval(l) + eval(r)\n\n<span style=\"color: #b6a0ff;\">def<\/span> <span style=\"color: #feacd0;\">handleVar<\/span>(s<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">String<\/span>)<span style=\"color: #b6a0ff;\">:<\/span> <span style=\"color: #6ae4b9;\">WithEnv<\/span> <span style=\"color: #b6a0ff;\">=<\/span>\n  <span style=\"color: #b6a0ff;\">val<\/span> <span style=\"color: #00d3d0;\">env<\/span> <span style=\"color: #b6a0ff;\">=<\/span> summon[<span style=\"color: #00bcff;\">Env<\/span>]\n  env.getOrElse(s, <span style=\"color: #00bcff;\">0<\/span>)\n<\/pre>\n<\/div>\n\n<p>\nYou can take a look at the final Scala 3 version of the code here.\n<\/p>\n\n<p>\n<a href=\"https:\/\/github.com\/justinhj\/evalexample\/blob\/master\/src\/main\/scala\/Scala3Eval.scala\">https:\/\/github.com\/justinhj\/evalexample\/blob\/master\/src\/main\/scala\/Scala3Eval.scala<\/a>\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-org7baa236\" class=\"outline-2\">\n<h2 id=\"org7baa236\">Final notes<\/h2>\n<div class=\"outline-text-2\" id=\"text-org7baa236\">\n<p>\nOf all the new features in Scala 3, I found Context Functions of most interest because of Martin Odersky's blog from 2016 <a href=\"https:\/\/www.scala-lang.org\/blog\/2016\/12\/07\/implicit-function-types.html\">https:\/\/www.scala-lang.org\/blog\/2016\/12\/07\/implicit-function-types.html<\/a> where this intriguing quote appears near the end. (Context functions were initially known as implicit functions).\n<\/p>\n\n<blockquote>\n<p>\nThere 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\u2019s an argument to be made that implicits have better composability than monads and why that is.\n<\/p>\n\n<p>\nOn 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.\n<\/p>\n\n<p>\nBut these discussions will have to wait for another time, as this blog post is already too long.\n<\/p>\n<\/blockquote>\n\n<p>\nSomewhat of a Fermat'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.\n<\/p>\n<\/div>\n<\/div>\n\n<div id=\"outline-container-orga7482f9\" class=\"outline-2\">\n<h2 id=\"orga7482f9\">References<\/h2>\n<div class=\"outline-text-2\" id=\"text-orga7482f9\">\n<p>\n<a href=\"https:\/\/en.wikiquote.org\/wiki\/Pierre_de_Fermat\">https:\/\/en.wikiquote.org\/wiki\/Pierre_de_Fermat<\/a>\n<\/p>\n\n<p>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/enums\/enums.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/enums\/enums.html<\/a>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/enums\/adts.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/enums\/adts.html<\/a>\n<\/p>\n\n<p>\n<a href=\"http:\/\/dotty.epfl.ch\/docs\/reference\/other-new-features\/indentation.html\">http:\/\/dotty.epfl.ch\/docs\/reference\/other-new-features\/indentation.html<\/a>\n<\/p>\n\n<p>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/givens.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/givens.html<\/a> <a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/using-clauses.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/using-clauses.html<\/a>\n<\/p>\n\n<p>\n<a href=\"https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/context-functions.html\">https:\/\/dotty.epfl.ch\/docs\/reference\/contextual\/context-functions.html<\/a>\n<\/p>\n\n<p>\nFoundations and Applications of Implicit Function Types\n<a href=\"https:\/\/infoscience.epfl.ch\/record\/229878\/files\/simplicitly_1.pdf\">https:\/\/infoscience.epfl.ch\/record\/229878\/files\/simplicitly_1.pdf<\/a>\n<\/p>\n\n<p>\n<a href=\"http:\/\/recurse.se\/2019\/09\/implicit-functions-in-scala-3\/\">http:\/\/recurse.se\/2019\/09\/implicit-functions-in-scala-3\/<\/a>\n<\/p>\n\n<p>\n&copy; 2020 Justin Heyes-Jones. All Rights Reserved.\n<\/p>\n<\/div>\n<\/div>\n","pubDate":"Wed, 18 Nov 2020 00:00:00 +0000","link":"http:\/\/justinhj.github.io\/2020\/11\/18\/scala-3-context-functions.html","guid":"http:\/\/justinhj.github.io\/2020\/11\/18\/scala-3-context-functions.html","category":["scala","scala-3","dotty"]}]}}